用另一个while循环Java扩展我的程序

时间:2017-11-11 18:28:49

标签: java while-loop do-while

首先,我是java的新手,请原谅下面代码的混乱。

我当前的程序从StdIn获取输入并输出输入的最高和最低值。

如果他们输入一个非正数的整数,是否可以扩展为再次使用ר?我几乎可以肯定while循环可以做到这一点,但不确定是否用我当前的代码执行了。再一次,我很新,来自音乐背景,所以我的逻辑意义不是最好的。

public class PositiveIntegers
{
public static void main(String[] args)
  {

do {
   StdOut.println("Enter your integers:");
} while (StdIn.isEmpty());

int max = StdIn.readInt();
int min = max;

while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
if (value > max) max = value;
if (value < min) min = value;
}

do {
  StdOut.println("Maximum = " + max + ", Minimum = " + min);
  return;
} while (StdIn.readInt() > 0);


  }
}

干杯

3 个答案:

答案 0 :(得分:0)

首先,您的程序中不需要这么多循环。在while循环中输入用户输入,然后在循环外打印该数字。

请记住使用try-catch进行用户输入的错误处理。

尝试这种方式:

try{
       do {
            StdOut.println("Enter your integers:");
       } while (StdIn.isEmpty() && StdIn.readInt() < 0);
}catch(Exception ex){
      StdOut.println("Error while taking user input !");
}

答案 1 :(得分:0)

你可以通过添加一个if语句来检查给定的数字是否为负数,然后打印消息再次添加它。

检查以下ENHANCED代码:

public class PositiveIntegers
{
   public static void main(String[] args)
   { 

   StdOut.println("Enter your integers:");

   int max = Integer.MIN_VALUE;
   int min = Integer.MAX_VALUE;

   while (!StdIn.isEmpty()) {

      int value = StdIn.readInt();

      // Adding the if-statement here to check if number is negative.
      if(value < 0){
         StdOut.println("You entered negative number, try positive numbers.");
         // just reset the max and min variables..
         max = Integer.MIN_VALUE;
         min = Integer.MAX_VALUE;
         continue;
      }

      if (value > max) max = value;
      if (value < min) min = value; 
   }

   StdOut.println("Maximum = " + max + ", Minimum = " + min);

   }
}

答案 2 :(得分:0)

快速回答这个问题

public class PositiveIntegers {
    public static void main(String[] args) {

        do {
            StdOut.println("Enter your integers:");
        } while (StdIn.isEmpty());

        int max = StdIn.readInt();
        int min = max;

        while (!StdIn.isEmpty()) {
            int value = StdIn.readInt();
            if (value < 0) {
                StdOut.println("Please enter a positive integer");
            } else {
                if (value > max) max = value;
                if (value < min) min = value;
            }
        }

        do {
            StdOut.println("Maximum = " + max + ", Minimum = " + min);
            return;
        } while (StdIn.readInt() > 0);


    }
}

我确保尽可能少地改变,但这应该会给你你想要的结果。