在不使用数组的情况下获取N个输入的最大值

时间:2020-03-21 00:48:26

标签: java

我正在努力寻找N个值的最大输入值。我能够打印最大值,但是练习要求仅打印最大值,而我无法从IF语句之外返回它。

运动说明:

编写一个程序,该程序:

  1. 从控制台读取数字N(必须大于0)
  2. 从控制台读取N个数字
  3. 显示输入的N个数字中的最大值。

我的代码:

public class Solution {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        int i=0;  
        int count=1; 
        int max=Integer.MIN_VALUE; 

        for (i=0; i<count; i++) {
            int cur = sc.nextInt();
            count++;

            if (cur>0){
            if (cur>max) {
                max=cur ;
                System.out.println(max);
            }
            }
        }


    }}

在控制台中,我得到了所需的输入以及此错误

java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)

5 个答案:

答案 0 :(得分:2)

首先,使用Scanner类时必须导入java.util.Scanner。 我更改了代码的几行,我认为这是您想要的:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // get N (how many numbers)
        int number;
        int max = Integer.MIN_VALUE;

        if (n > 0) {
            for (int i = 0; i < n; i++) {
                number = sc.nextInt(); // get numbers
                if (number > max)
                    max = number;
            }

            System.out.println(max); // print the maximum number

        } else
            System.out.println("Please enter greather than 0 number"); // when n is negative or zero

    }
}

答案 1 :(得分:1)

您应该仔细阅读练习。首先,您必须读取N号,以确定总共应该从控制台读取多少个数字。

此外,您还必须使用在读取或解析期间可能抛出的try-catch块来处理异常情况。试试这个:

游乐场:https://repl.it/repls/OrnateViolentSoftwaresuite(加载可能需要一些时间)。

public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);

  // 1. reads a number N (must be greater than 0) from the console
  int N = 0;

  while(N == 0) {
      try {
          System.out.print("Enter N: ");
          // Use sc.nextLine() instead of .next() or .nextInt()
          N = Integer.parseInt(sc.nextLine());
      } catch (Exception ignored) {}
  }

  // 2.reads N numbers from the console
  int max = Integer.MIN_VALUE;
  for (int i = 0; i < N; i++) {
      while(true) {
          try {
              System.out.printf("Enter %d. number: ", i + 1);
              // determine the max during reading
              max = Math.max(max, Integer.parseInt(sc.nextLine()));
              break; // cancels while(true)
          } catch (Exception ignored) {}
      }
  }

  // 3. Displays the maximum of the N entered numbers
  System.out.printf("The max number is %d\n", max);

  System.out.println("Goodbye!");
  sc.close(); // don't forget to close the resource
}

更新

如果您确实还没有学习过try / catch,那么您也不必使用它。您可以简单地从上述代码中删除try-catch块,这也应该起作用(仅适用于有效的整数输入)

例如代替

try {
    System.out.print("Enter N: ");
    // Use sc.nextLine() instead of .next() or .nextInt()
    N = Integer.parseInt(sc.nextLine());
} catch (Exception ignored) {}

只需使用

System.out.print("Enter N: ");
// Use sc.nextLine() instead of .next() or .nextInt()
N = Integer.parseInt(sc.nextLine());

答案 2 :(得分:0)

好的,这就是我解决的方法。最初,我并不了解第一个输入就是输入的数量。一旦我明白了,它就会变得容易一些。

基本上,我不得不告诉程序仅在最后一次输入(n-1)之后打印最大数量。感谢所有的帮助。

public class Solution {
    public static void main(String[] args)  {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); // get N (how many numbers)  
        int number; 
        int max=Integer.MIN_VALUE; 

        for (int i=0; i<n; i++) {
            number = sc.nextInt();

            if (number>max) {
                max=number ;
            } 

            if (i==n-1)
            System.out.print(max);
            }
    }
            }

答案 3 :(得分:0)

这是逐步的说明。

  1. 读入数字N(N> 0)
int n = sc.nextInt();
  • 检查N> 0
if (n <= 0) {
   System.out.println("Must be >  0, please try again.");
}

要继续执行此操作,请使用while循环。

int n = -1;
while (n <= 0) {
    n = sc.nextInt();
     if (n <= 0) {
        System.out.println("Must be > 0, please try again.");
     }
}
  1. 现在找到最大值。
// initialize to first value
int max = sc.nextInt();
  1. 现在得到其他人
// start from 1 since we already have a value
for(i = 1; i < n; i++) {
   int v = sc.nextInt();
   // if current value is greater than max
   // replace max with current value
   if (v > max) {
       max = v;
   }
}

  1. 打印答案。
System.out.println("max = " + max);

答案 4 :(得分:0)

您也可以按照以下步骤进行操作:

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int i, count, cur, max = Integer.MIN_VALUE;

        // Read a number N (must be greater than 0) from the console
        do {
            System.out.print("How many integers? ");
            count = sc.nextInt();
            if (count <= 0) {
                System.out.println("Enter a positive integer.");
            }
        } while (count <= 0);

        // Reads N numbers from the console
        System.out.println("Enter " + count + " integers");
        for (i = 0; i < count; i++) {
            max = Math.max(max, sc.nextInt()); // Find maximum
        }

        // Display the maximum of the N entered numbers.
        System.out.println("Maximum of the numbers is: " + max);
    }
}

示例运行:

How many integers? -4
Enter a positive integer.
How many integers? 0
Enter a positive integer.
How many integers? 5
Enter 5 integers
90
-86
230
5
78
Maximum of the numbers is: 230
相关问题