程序输出最大值和最小值

时间:2012-10-19 00:03:58

标签: java for-loop io max min

//基本上在这个程序中,你必须要求用户提供一个终止值,然后是一组数字。当您输入终止号码时,程序结束。然后输出您输入的数字的最大值和最小值,但不输出终止值。我正在寻找有关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);
        }       
    }
}

3 个答案:

答案 0 :(得分:0)

如何使用while循环代替for,

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

答案 1 :(得分:0)

你的循环应该是

while (s !=t ) 

并且println应该在循环之后出现。

答案 2 :(得分:0)

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

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

退出前会跑t次。

如果你想要t终止值而不是使用for循环,你可以使用一段时间。

不是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程序员,因此您应该检查我的代码是否存在语法错误,但它应该让您知道如何执行此操作。