输入0时如何结束循环?

问题描述 投票:0回答:2

我正在编写一个程序,用户将继续输入数字,直到使用循环输入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");

   }
}
java
2个回答
1
投票

尝试将输入字符串与退出条件进行比较:

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");

   }
}

0
投票

First,您不需要两次JOptionPane.showInputDialog("Enter a String");。在while循环内调用一次。

Second,定义一个无限的while循环-while(true),因为您不知道用户将输入多少次。

第三,要停止基于输入loop0,请将逻辑放在循环内。

  • 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");
    }
© www.soinside.com 2019 - 2024. All rights reserved.