【问题标题】:Printing multiple JOptionPane string input dialogs in one sentence一句话打印多个JOptionPane字符串输入对话框
【发布时间】:2016-10-10 12:35:14
【问题描述】:

我想从多个 JOptionPane 输入对话框中读取输入,并在一个句子中打印 JOptionPane 消息对话框中每个对话框的输入。例如: 这是一条消息。

将输出为:这是一条消息

这是我正在尝试调整的代码,它当前计算所有输入中的字符总数。

  // A Java Program by Gavin Coll 15306076 to count the total number of characters in words entered by a user //
import javax.swing.JOptionPane;

public class WordsLength    
{
public static void main(String[] args)
{
    String words = JOptionPane.showInputDialog(null, "Enter your word: "); // Getting the first word

    int length = words.length(); 

    int totallength = length; 
    int secondaryLength;

    do 
    {
        String newwords = JOptionPane.showInputDialog(null, "Enter another word: (Enter nothing to stop entering words) "); // Getting more words
        secondaryLength = newwords.length(); // Getting the length of the new words

        totallength += secondaryLength; // Adding the new length to the total length

    } 

    while(secondaryLength != 0);

    JOptionPane.showMessageDialog(null, "The total number of characters in those words is: " + totallength);

    System.exit(0);
}
}

【问题讨论】:

    标签: java


    【解决方案1】:

    只需使用StringBuilder 来连接每个新单词。

        import javax.swing.JOptionPane;
    
        public class WordsLength {
            public static void main(final String[] args) {
                String words = JOptionPane.showInputDialog(null, "Enter your word: "); // Getting the first word
    
                int length = words.length();
    
                int secondaryLength;
                int totallength = length; 
    
                StringBuilder builder = new StringBuilder();
                builder.append(words);
    
                do {
                    String newwords = JOptionPane.showInputDialog(null,
                            "Enter another word: (Enter nothing to stop entering words) "); // Getting more words
    
                    secondaryLength = newwords.length(); // Getting the length of the new words
    
                    totallength += secondaryLength; // Adding the new length to the total length
    
                    builder.append(' ');
                    builder.append(newwords);
    
                }
    
                while (secondaryLength != 0);
    
                JOptionPane.showMessageDialog(null, "The total number of characters in those words is : " + totallength);
                JOptionPane.showMessageDialog(null, "The full sentence is : " + builder);
    
                System.exit(0);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      相关资源
      最近更新 更多