【问题标题】:Program to output the max and min输出最大值和最小值的程序
【发布时间】:2012-10-09 13:17:21
【问题描述】:

//基本上在这个程序中,你必须向用户询问一个终止值,然后是一组数字。当您输入您的终止号码时,程序结束。然后,您输出您输入的数字的最大值和最小值,但不是终止值。我正在为我的 for 语句寻求帮助,因为循环只运行了两次。请只做 IO。

public class smalllargest {     
    public static void main(String[] args) {
        System.out.println("Enter any number, then re-enter that number when you wish to be done.");
        int t = IO.readInt();
        System.out.println("Enter your set of numbers");
        int s = IO.readInt();
        int max = s;
        int min = s;
        for(int i = 0; i!=t; i++) {
            int n = IO.readInt();
            if(n > max) {
                max = n ;
            }
            if(n< max) {
                min = n;
            }
            if(n == t){
                break;
            }
            System.out.println("max:");
            IO.outputIntAnswer(max);
            System.out.println("min:");
            IO.outputIntAnswer(min);
        }       
    }
}

【问题讨论】:

    标签: java for-loop io max min


    【解决方案1】:

    用while循环代替for怎么样,

    while(s!=t) {
     s = IO.readInt();
    ...
    }
    

    【讨论】:

      【解决方案2】:

      你的循环应该是

      while (s !=t ) 
      

      并且 println 应该在循环之后。

      【讨论】:

        【解决方案3】:

        对于我在这段代码中看到的内容,第一个插入的数字不用作终止值。

        for(int i = 0; i!=t; i++)
        

        在退出前会运行 t 次。

        如果您希望 t 成为终止值而不是使用 for 循环,则可以使用 while。

        不是 Java 专家,但类似:

        int t = IO.readInt();    
        int s = t + 1; // just to be sure s != t
        int min = 999999999;
        int max = 0;
        System.out.println("Enter your set of numbers");
        while (s != t) {
          int s = IO.readInt();
          if (s != t) { // to exclude t from the output
            if (min > s) min = s;
            if (max < s) max = s;
          }
        }
        
        System.out.println("max: ");
        IO.outputIntAnswer(max);
        System.out.println("Min: ");
        IO.outputIntAnswer(min);
        

        再说一次,我不是 Java 程序员,所以你应该检查我的代码是否有语法错误,但它应该让你知道如何去做。

        【讨论】:

          猜你喜欢
          • 2023-03-19
          • 1970-01-01
          • 2020-08-27
          • 2022-01-03
          • 1970-01-01
          • 2019-06-23
          • 1970-01-01
          • 2017-06-26
          • 2014-01-13
          相关资源
          最近更新 更多