JOptionPane输入

时间:2015-02-19 04:28:15

标签: java joptionpane

我是Java新手,我必须编写一个Java应用程序,要求用户使用JOptionPane输入对话框输入句子,go 通过输入中的每个字符来计算大写字母,小写字母和小写字母的数量 数字,然后使用JOptionPane消息对话框打印计数。然后应用程序应重复此操作 进程直到用户输入单词STOP(或Stop,或STop等)

我认为我到目前为止所做的大部分事情都是我需要做的,但由于某种原因,程序会忽略所有其他输入,除非我输入stop,这并不意味着它是字符串,但退出字。我很感激帮助和解释。

import javax.swing.JOptionPane; 
public class Project0 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String string1 = ""; 
    while(!string1.equalsIgnoreCase("Stop")){
        string1 = JOptionPane.showInputDialog("Input words or type 'stop' to end.");
        string1 += string1;
    }
    charcount(string1);



}
public static void charcount(String userin){
    int uppercount, lowercount, digitscount; variables
    uppercount = 0;
    lowercount = 0;
    digitscount = 0;

    for(int c = 0; c < userin.length(); c++ ){ 
        char ch = userin.charAt(c); 
        if(Character.isUpperCase(ch)){ uppercount += 1; } 
        else if(Character.isLowerCase(ch)){ lowercount += 1; } 
        else if(Character.isDigit(ch)){ digitscount += 1; }

    }
    JOptionPane.showMessageDialog(null, "There are " + uppercount + " uppercase characters, " + lowercount + " lowercase characters and " + digitscount + " digits."); 
  }

}

3 个答案:

答案 0 :(得分:0)

逻辑错误很少:

while(!string1.equalsIgnoreCase("Stop")){
        string1 = JOptionPane.showInputDialog("Input words or type 'stop' to end.");
        string1 += string1;// gets doubled the input, resulting into infinite loop
    }
    charcount(string1);// possibly has to be inside loop

尝试改为:

String string1;
do {
    string1 = JOptionPane.showInputDialog("Input words or type 'stop' to end.");
    charcount(string1);
} while("stop".equalsIgnoreCase(string1));

答案 1 :(得分:0)

在您执行代码之前:

while(!string1.equalsIgnoreCase("Stop")){ string1 = JOptionPane.showInputDialog("Input words or type 'stop' to end."); string1 += string1; }

您应该检查string1是否等于“停止”。如果没有,请冷却,添加就像你已经做的那样,如果没有,break循环。

由于string1已经创建,我建议使用do-while类型循环:

do { string1 = JOptionPane.showInputDialog(...); if (!string1.equalsIgnoreCase("Stop") { // Add to string1 } } while (!string1.equalsIgnoreCase("Stop"));

答案 2 :(得分:0)

如果我正确思考,这可能是因为,除非您从头开始直接输入“停止”,否则您的字符串将永远等于“停止”。例如,当您检查contains“停止”时,它会检查您的字符串等于“停止”(忽略大小写)。您可以尝试以下方法:

while(!string1.contains("stop")) {
    //Run your code here.
}

如果您正在检查忽略大小写的字符串,那么您可以创建一个名为“checkStop”的字符串并将其设置为string1,然后将其转换为全部大写,如下所示:

String checkStop = string1.toUpperCase();

您也可以将其转换为小写:

String checkStop = string1.toLowerCase();

然后,您可以使用checkStop来确定该字符串是否包含“STOP”或“stop”。