我正在编写一个程序,用户将继续输入数字,直到使用循环输入0。然后,它将显示输入的最大数字,输入的最小数字以及所有数字的平均值。这是我必须开始的:
import javax.swing.JOptionPane;
public class MaxMinAvg
{
public static void main(String args[])
{
String inString = " ";
int count = 0;
inString = JOptionPane.showInputDialog("Enter a String");
//perform until the end of file
while(inString.length() != 0)
{
count++;
System.out.println("record " + count + " is " + inString);
// second read
inString = JOptionPane.showInputDialog("Enter a String");
} // end while loop
System.out.println("All done");
}
}
尝试将输入字符串与退出条件进行比较:
import javax.swing.JOptionPane;
public class MaxMinAvg
{
public static void main(String args[])
{
String inString = " ";
int count = 0;
inString = JOptionPane.showInputDialog("Enter a String");
//perform until the end of file
while(inString.length() != 0 && !inString.equal("0"))
{
count++;
System.out.println("record " + count + " is " + inString);
// second read
inString = JOptionPane.showInputDialog("Enter a String");
} // end while loop
System.out.println("All done");
}
}
First,您不需要两次JOptionPane.showInputDialog("Enter a String");
。在while
循环内调用一次。
Second,定义一个无限的while
循环-while(true)
,因为您不知道用户将输入多少次。
第三,要停止基于输入loop
的0
,请将逻辑放在循环内。
trim()
输入,用户可以在unmber之前或之后插入空格int
==
检查给定输入的用户是否相等0
break
循环 public static void main(String args[]) {
String inString = "";
int count = 0;
while(true) {
inString = JOptionPane.showInputDialog("Enter a String");
count++;
System.out.println("record " + count + " is " + inString);
if (Integer.parseInt(inString.trim()) == 0) {
break;
}
}
System.out.println("All done");
}