程序卡说明中显示换行符

我正在使用Java为课程项目创建Tarot读卡器。它从文本文件中读取信息。奇怪的是,当我运行程序时,换行符会打印出来,而不是实际创建新行。

代码如下:

public class TarotDAO {
    public static ArrayList < TarotCard > getall() {
        ArrayList < TarotCard > cardList = new ArrayList < > ();

        //Create something to read from the file
        Path thePath = Paths.get("cars.txt");
        File theFile = thePath.toFile();
        try (
            BufferedReader reader = new BufferedReader(
                new FileReader(theFile))
        ) {
            //read each line of the file
            String curLine = reader.readLine();
            System.out.println(curLine);

            while (curLine != null) {
                String[] temp = curLine.split(">");

                //---create a new object with the values from the array
                //add object to results
                String id = temp[0];
                String name = temp[1];
                String upright = temp[2];
                String reverse = temp[3];
                TarotCard card = new TarotCard(id,name,upright,reverse);
                cardList.add(card);

                //...or as a 1-liner
                //results.add(new ExpenseReport(temp[0],Double.parseDouble(temp[1])));

                //get the next line from the file
                curLine = reader.readLine();
            }
            return cardList;

        } catch (FileNotFoundException e) {
            System.err.println("File not found");
        } catch (IOException e) {}
        return cardList;
    }

}

package Business;

public class TarotCard 
{
    protected String name;
    protected String identifier;
    protected String upright;
    protected String reverse;

    public TarotCard (String identifier,String name,String upright,String reverse)
    {
        this.identifier = identifier;
        this.name = name;
        this.upright = upright;
        this.reverse = reverse;
    }

    public TarotCard()
    {

    }

    public String getName() 
    {
        return name;
    }

    public void setName(String name) 
    {
        this.name = name;
    }

    public String getIdentifier() 
    {
        return identifier;
    }

    public void setIdentifier(String identifier) 
    {
        this.identifier = identifier;
    }

    public String getUpright() 
    {
        return upright;
    }

    public void setUpright(String upright) 
    {
        this.upright = upright;
    }

    public String getReverse() 
    {
        return reverse;
    }

    public void setReverse(String reverse) 
    {
        this.reverse = reverse;
    }

    public String getImage()
    {
        String image = identifier + ".jpg";
        return image;
    }

    public String toString()
    {
        String result = "";
        result += this.getName() + "\n\n";
        result += this.getUpright() + "\n\n";
        result += this.getReverse();
        return result;
    }
}

下面的代码可以打印出所有内容:

    package Application;

    import Business.TarotCard;
    import Controller.TarotDAO;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.JOptionPane;
    import static javax.swing.JOptionPane.WARNING_MESSAGE;

    public class Reading extends javax.swing.JDialog 
    {

    public Reading(java.awt.Frame parent,boolean modal) 
    {
        super(parent,modal);
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the 
    form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        cbSpread = new javax.swing.JComboBox<>();
        lblGenLove1 = new javax.swing.JLabel();
        lblGenLove2 = new javax.swing.JLabel();
        lblGenLove3 = new javax.swing.JLabel();
        lblGenLove4 = new javax.swing.JLabel();
        lbl3Card3 = new javax.swing.JLabel();
        lbl3Card1 = new javax.swing.JLabel();
        lbl3Card2 = new javax.swing.JLabel();
        chkInclRev = new javax.swing.JCheckBox();
        btnSave = new javax.swing.JButton();
        btnDeal = new javax.swing.JButton();
        btnShuffle = new javax.swing.JButton();
        cbDeck = new javax.swing.JComboBox<>();
        jScrollPane2 = new javax.swing.JScrollPane();
        taResult = new javax.swing.JTextArea();
        lblBackground = new javax.swing.JLabel();


    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Reader");
        setMinimumSize(new java.awt.Dimension(1143,835));
        setModal(true);
        setResizable(false);
        setSize(new java.awt.Dimension(1130,800));
        getcontentPane().setLayout(null);

        cbSpread.setBackground(new java.awt.Color(136,54,25));
        cbSpread.setfont(new java.awt.Font("felix Titling",12)); // 
        NOI18N
        cbSpread.setforeground(new java.awt.Color(204,255,204));
        cbSpread.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] 
    { "Select Spread","3 Card","General Love Reading" }));
        getcontentPane().add(cbSpread);
        cbSpread.setbounds(820,20,190,30);

        lblGenLove1.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lblGenLove1Mouseclicked(evt);
            }
        });
        getcontentPane().add(lblGenLove1);
        lblGenLove1.setbounds(20,70,240,400);

        lblGenLove2.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lblGenLove2Mouseclicked(evt);
            }
        });
        getcontentPane().add(lblGenLove2);
        lblGenLove2.setbounds(300,120,400);

        lblGenLove3.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lblGenLove3Mouseclicked(evt);
            }
        });
        getcontentPane().add(lblGenLove3);
        lblGenLove3.setbounds(570,400);

        lblGenLove4.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lblGenLove4Mouseclicked(evt);
            }
        });
        getcontentPane().add(lblGenLove4);
        lblGenLove4.setbounds(850,80,400);

        lbl3Card3.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lbl3Card3Mouseclicked(evt);
            }
        });
        getcontentPane().add(lbl3Card3);
        lbl3Card3.setbounds(840,100,400);

        lbl3Card1.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lbl3Card1Mouseclicked(evt);
            }
        });
        getcontentPane().add(lbl3Card1);
        lbl3Card1.setbounds(50,400);

        lbl3Card2.addmouseListener(new java.awt.event.MouseAdapter() {
            public void mouseclicked(java.awt.event.MouseEvent evt) {
                lbl3Card2Mouseclicked(evt);
            }
        });
        getcontentPane().add(lbl3Card2);
        lbl3Card2.setbounds(450,400);

        chkInclRev.setBackground(new java.awt.Color(117,47,24));
        chkInclRev.setfont(new java.awt.Font("felix Titling",12)); // 
        NOI18N
        chkInclRev.setforeground(new java.awt.Color(204,204));
        chkInclRev.setText("Include Reversals?");
        getcontentPane().add(chkInclRev);
        chkInclRev.setbounds(580,160,30);

        btnSave.setBackground(new java.awt.Color(117,24));
        btnSave.setfont(new java.awt.Font("felix Titling",12)); // NOI18N
        btnSave.setforeground(new java.awt.Color(51,51));
        btnSave.setText("Save");
        getcontentPane().add(btnSave);
        btnSave.setbounds(1030,31);

        btnDeal.setBackground(new java.awt.Color(117,24));
        btnDeal.setfont(new java.awt.Font("felix Titling",12)); // NOI18N
        btnDeal.setforeground(new java.awt.Color(51,51));
        btnDeal.setText("Deal Cards");
        btnDeal.addactionListener(new java.awt.event.actionListener() {
            public void actionPerformed(java.awt.event.actionEvent evt) {
                btnDealactionPerformed(evt);
            }
        });
        getcontentPane().add(btnDeal);
        btnDeal.setbounds(410,150,31);

        btnShuffle.setBackground(new java.awt.Color(117,24));
        btnShuffle.setfont(new java.awt.Font("felix Titling",12)); // 
        NOI18N
        btnShuffle.setforeground(new java.awt.Color(51,51));
        btnShuffle.setText("Shuffle Deck");
        btnShuffle.addactionListener(new java.awt.event.actionListener() {
            public void actionPerformed(java.awt.event.actionEvent evt) {
                btnShuffleactionPerformed(evt);
            }
        });
        getcontentPane().add(btnShuffle);
        btnShuffle.setbounds(240,31);

        cbDeck.setBackground(new java.awt.Color(136,25));
        cbDeck.setfont(new java.awt.Font("felix Titling",12)); // NOI18N
        cbDeck.setforeground(new java.awt.Color(204,204));
        cbDeck.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { 
    "Select Deck","Rider-Waite" }));
        cbDeck.addactionListener(new java.awt.event.actionListener() {
            public void actionPerformed(java.awt.event.actionEvent evt) {
                cbDeckactionPerformed(evt);
            }
        });
        getcontentPane().add(cbDeck);
        cbDeck.setbounds(20,200,30);

        taResult.setEditable(false);
        taResult.setBackground(new java.awt.Color(51,51));
        taResult.setColumns(20);
        taResult.setfont(new java.awt.Font("Footlight MT Light",18)); // 
        NOI18N
        taResult.setforeground(new java.awt.Color(204,204));
        taResult.setLineWrap(true);
        taResult.setRows(5);
        taResult.setautoscrolls(false);
        jScrollPane2.setViewportView(taResult);

        getcontentPane().add(jScrollPane2);
        jScrollPane2.setbounds(10,550,1110,240);

        lblBackground.setIcon(new 


   javax.swing.ImageIcon(getclass().getResource("/Business/Background/Magick- 
     Background2.png"))); // NOI18N
        getcontentPane().add(lblBackground);
        lblBackground.setbounds(0,1132,800);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void cbDeckactionPerformed(java.awt.event.actionEvent evt) {                                       
        String deckSelect = (String) cbDeck.getSelectedItem();

    }                                      

    private void btnShuffleactionPerformed(java.awt.event.actionEvent evt) {                                           
        if (cbDeck.getSelectedItem().toString().equalsIgnoreCase("Select Deck"))
        {
            JOptionPane.showmessagedialog(this,"Select a deck before shuffling.","WARNING",WARNING_MESSAGE);
        }
        else
        {
            if (cbDeck.getSelectedItem().toString().equalsIgnoreCase("Rider-Waite"))
            {
                cardList = TarotDAO.getall();
                Collections.shuffle(cardList);
            }
        }
    }                                          

    private void btnDealactionPerformed(java.awt.event.actionEvent evt) {                                        
        if (cbDeck.getSelectedItem().toString().equalsIgnoreCase("Select Deck"))
        {
            JOptionPane.showmessagedialog(this,"Select a deck before dealing.",WARNING_MESSAGE);
        }
        else if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("Select Spread"))
        {
            JOptionPane.showmessagedialog(this,"Select a spread before dealing.",WARNING_MESSAGE);
        }
        else
        {
            if (cbDeck.getSelectedItem().toString().equalsIgnoreCase("Rider-Waite"))
            {
                if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("3 Card"))
                {   
                    lblGenLove1.setVisible(false);
                    lblGenLove1.setVisible(false);
                    lblGenLove1.setVisible(false);
                    lblGenLove1.setVisible(false);
                    lbl3Card1.setVisible(true);
                    lbl3Card2.setVisible(true);
                    lbl3Card3.setVisible(true);
                    card1 = cardList.get(0);
                    card2 = cardList.get(1);
                    card3 = cardList.get(2);
                    lbl3Card1.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                    lbl3Card2.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                    lbl3Card3.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                }
                else if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("General Love Reading"))
                {
                    lbl3Card1.setVisible(false);
                    lbl3Card2.setVisible(false);
                    lbl3Card3.setVisible(false);
                    lblGenLove1.setVisible(true);
                    lblGenLove1.setVisible(true);
                    lblGenLove1.setVisible(true);
                    lblGenLove1.setVisible(true);
                    card1 = cardList.get(0);
                    card2 = cardList.get(1);
                    card3 = cardList.get(2);
                    card4 = cardList.get(3);
                    lblGenLove1.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                    lblGenLove2.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                    lblGenLove3.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                    lblGenLove4.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/Back.jpg")));
                }
            }
        }
    }                                       

    private void lbl3Card1Mouseclicked(java.awt.event.MouseEvent evt) {                                       
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("3 Card"))
        {
            String cardImage1 = card1.getImage();
            lbl3Card1.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + cardImage1)));
            taResult.setText("This card is about your past:\n\n" + card1.getUpright());
        }
    }                                      

    private void lbl3Card2Mouseclicked(java.awt.event.MouseEvent evt) {                                       
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("3 Card"))
        {
            String cardImage2 = card2.getImage();
            lbl3Card2.setIcon(new javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + cardImage2)));
            taResult.setText("This card is about your present:\n\n" + card2.getUpright());
        }
    }                                      

    private void lbl3Card3Mouseclicked(java.awt.event.MouseEvent evt) {                                       
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("3 Card"))
        {
            String cardImage3 = card3.getImage();
            lbl3Card3.setIcon(new 
    javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + 
    cardImage3)));
            taResult.setText("This card is about your future:\n\n" + card3.getUpright());
        }
    }                                      

    private void lblGenLove4Mouseclicked(java.awt.event.MouseEvent evt) {                                         
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("General Love Reading"))
        {
            String cardImage4 = card4.getImage();
            lblGenLove4.setIcon(new 
    javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + 
    cardImage4)));
            taResult.setText("This card is general glimpse of your future:\n\n" + card4.getUpright());
        }
    }                                        

    private void lblGenLove3Mouseclicked(java.awt.event.MouseEvent evt) {                                         
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("General Love Reading"))
        {
            String cardImage3 = card3.getImage();
            lblGenLove3.setIcon(new 
    javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + cardImage3)));
            taResult.setText("This card tells you how to prepare yourself:\n\n" + card3.getUpright());
        }
    }                                        

    private void lblGenLove2Mouseclicked(java.awt.event.MouseEvent evt) {                                         
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("General Love Reading"))
        {
            String cardImage2 = card2.getImage();
            lblGenLove2.setIcon(new 
    javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + cardImage2)));
            taResult.setText("This card advises of a positive omen to look for:\n\n" + card2.getUpright());
        }
    }                                        

    private void lblGenLove1Mouseclicked(java.awt.event.MouseEvent evt) {                                         
        if (cbSpread.getSelectedItem().toString().equalsIgnoreCase("General Love Reading"))
        {
            String cardImage1 = card1.getImage();
            lblGenLove1.setIcon(new 
     javax.swing.ImageIcon(getclass().getResource("/Business/RWImages/" + cardImage1)));
            taResult.setText("This card is general glimpse of your future:\n\n" + card1.getUpright());
        }
    }                                        
    ArrayList <TarotCard> cardList;
    TarotCard card1;
    TarotCard card2;
    TarotCard card3;
    TarotCard card4;
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnDeal;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnShuffle;
    private javax.swing.JComboBox<String> cbDeck;
    private javax.swing.JComboBox<String> cbSpread;
    private javax.swing.JCheckBox chkInclRev;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbl3Card1;
    private javax.swing.JLabel lbl3Card2;
    private javax.swing.JLabel lbl3Card3;
    private javax.swing.JLabel lblBackground;
    private javax.swing.JLabel lblGenLove1;
    private javax.swing.JLabel lblGenLove2;
    private javax.swing.JLabel lblGenLove3;
    private javax.swing.JLabel lblGenLove4;
    private javax.swing.JTextArea taResult;
    // End of variables declaration                   
}

以下是输出示例:

Upright Nine of Swords Meaning\n\nThe Nine of Swords is often associated with fear and anxiety,about all the things that worry you and keep you up at night. Sometimes this card can be associated 
with trauma - one which may be shameful for you to confide with others about,and all the 
psychological responses that come from experiencing that trauma.\n\nWhen we are never released from 
the entrapment depicted in the Eight of Swords,we escalate into the Nine of Swords,where we are 
plagued by nightmares.

以下是我正在调用的某些文本文件:

  

0MA> The Fool>直立的Fool含义\ n \ nFool卡的编号为0,即       被认为是无限的潜力。认为他是一片空白       对于“傻瓜”尚未建立清晰的个性。他是我的象征       天真-他的未来之旅将塑造他的性格。\ n \ n要看到       傻瓜通常意味着新旅程的开始,您将在那里       充满乐观和自由,摆脱生活中常见的束缚。什么时候我们       遇见他,他几乎以幼稚的方式每天冒险。       他认为生活中可能发生任何事情,并且有很多       世界上正在等待的机会       并且发达。他过着简单的生活,无后顾之忧,似乎没有       他无法说出自己将来会遇到什么而感到困扰。\ n \ nTo       在阅读中与他见面也可以看作是对冒险的要求       你自己的角色。他鼓起勇气,因为他了解每一天
      是一个机会,开拓您的生活新领域,随之而来的是一种混合       充满期待,惊奇,敬畏和好奇心。傻瓜在那里展示       那个...

我也尝试过CRLF,但也没有用。我已经尝试过使程序能够读取两个定界符,但不幸的是,该定界符也不起作用。我是Java的新手,并且仍然在学习,因此我们将不胜感激。

mixiumingxiaoxiao 回答:程序卡说明中显示换行符

您的输出包含\ n,因为您的输入实际上包含\ n。您看到的那个字符组合不是换行符,而是一个斜杠,后面跟一个n,因此,如果在输入中看到它,就不会在输出中看到它。

转义字符仅适用于String文字,即当您创建这样的String对象时:

String foo = "I need a newline on the end of this line.\n";

如果您print(foo),则将得到文本,并按指定的位置输入换行符。

如果读取的文件包含\ n,则不是换行符。换行符是非打印字符。

解决方案:在输入的每一行的末尾,按回车键,而不要键入\ n。

另一种解决方案:如果您坚持在输入文件中保留\ n字符组合,则需要在使用输入之前处理该行以消除它们。

curLine = curLine.replaceAll("\\n","");

请注意,由于我们在此处使用了正则表达式,因此我已避免使用反斜杠,否则,正则表达式将查找换行符,而不是\ n。

如果只想在输出中使用换行符,只需使用System.out.println();打印它,或使用+ "\n"在末尾附加一个换行符。您没有包括要打印的部分,所以我不知道您实际上在做什么。

本文链接:https://www.f2er.com/2929794.html

大家都在问