0

我需要从这段代码中获得最大值,但这真的很麻烦。有人有什么建议吗?

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);
         }
    }
}
4

2 回答 2

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);
于 2012-04-06T01:30:14.170 回答
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);
于 2012-04-06T01:34:24.820 回答