有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java比较数字并处理输入集合

Comparing one input to a known value is common enough, but you’ll often need to process a collection of inputs.

Write a program that asks for three numbers. Check first to see that all numbers are different. If they’re not different, then exit the program. Otherwise, display the largest number of the three.

Constraint

Write the algorithm manually. Don’t use a built-in function for finding the largest number in a list.

请看下面我的代码。我遇到的问题是,这个程序不断地询问数字,但它并没有在3个数字上停下来,然后取最大的数字

import java.util.Scanner;
public class Assignment_1_Exercise_22 {
    public static boolean contain(int[] numbs, int x) {

        for (int n : numbs)

            if (n == x)
                // Return true if connection is successful
                return true;

        return false;

    }

    public static void main(String[] args)

    {
        Scanner sc = new Scanner(System.in);
        int[] numbs = new int[100];
        int count = 0;
        int largest = 0;

        while (true) { // make it while(count<10) for entering 10 numbers

            System.out.print("Enter any number (-1 to stop): ");

            int x = sc.nextInt();

            if (x == -1)

                break;

            if (contain(numbs, x)) {

                System.out.println("Number already entered. Please enter a different number!");

                continue;

            }

            numbs[count++] = x;

            largest = Math.max(x, largest);

        }

        System.out.println("The largest number is " + largest);

        sc.close();

    }

}

共 (1) 个答案

  1. # 1 楼答案

    使用 而(计数<;3) 而不是 虽然(真的)