获取“用户输入的最大值”?

时间:2012-04-06 01:25:49

标签: java max

我需要从这段代码中获取最大值,但这真的很棘手。有人有任何建议吗?

import java.util.Scanner;
public class Test{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);

         final int sentinel = 0;
         int number;
         int maxval = 0;
         int count = 0;

         System.out.println ("Enter a number: ");

         number = scan.nextInt();
         while (number != sentinel)
         {
            count++;
            System.out.println("Enter another number");
            number = scan.nextInt();
            maxval = number;
         }

         if (number > maxval)
         {
            maxval = number;
            System.out.println ("The max value is " + maxval);
         }
    }
}

2 个答案:

答案 0 :(得分:1)

每次获得新号码时都会覆盖maxval变量。你必须做这样的事情

 while (number != sentinel)
 {
     count++;
     System.out.println("Enter another number");
     number = scan.nextInt();
     if (number > maxval && number != sentinel) //So you don't overwrite it when you get the sentinel character
        maxval = number;
 }
 System.out.println ("The max value is " + maxval);

答案 1 :(得分:0)

试试这个,它有点简单,并修复了代码中的主要问题:比较number > maxval 必须在主循环中

    Scanner scan = new Scanner(System.in);

    final int sentinel = 0;
    int maxval = 0;
    int number = 0;

    do {
        System.out.print("Enter a number: ");
        number = scan.nextInt();
        if (number > maxval)
            maxval = number;
    } while (number != sentinel);

    System.out.println("The max value is " + maxval);