【问题标题】:Java Try Catch if 4 numbers are entered, 3 int inputs expected via array & while loop iterator如果输入 4 个数字,Java Try Catch,通过数组和 while 循环迭代器预期 3 个 int 输入
【发布时间】:2017-10-15 23:30:25
【问题描述】:

我正在对我的 Java 程序进行故障排除,以使用 while 循环和 try-catch 语句来引发异常,如果用户输入了 4 个整数输入,而预期只有 3 个。我使用了一个结合了 while 循环和 hasNextInt 方法的数组,但我无法让它运行。任何见解都会很棒。

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    int count = 3;

    int[] numbers = new int[count];
    System.out.println("Enter 3 integers");
    Scanner numScanner = new Scanner(scanner.nextLine());
    while (numbers[] > count) {
        if (numScanner.hasNextInt()) {
            numbers[] = numScanner.hasNextInt();
        } else
        {
            System.out.println("You didn't provide enough numbers");
            break;
        }
    }   
}

【问题讨论】:

  • 您的 numbers[] 变量需要方括号内的索引

标签: java arrays while-loop try-catch


【解决方案1】:

需要注意的一点是,当您访问数组中的元素时,您需要提供一个索引,而且在 java 中,原始数组默认初始化为零[1],因此您的 while 语句条件失败。您还需要关闭扫描仪。

以下代码稍作修改。希望能达到你的预期效果。

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int count = 3;
        int[] numbers = new int[count];
        System.out.println("Enter 3 integers");
        Scanner numScanner = new Scanner(scanner.nextLine());
        int currentIndex = 0;
        while (currentIndex < count) {
            if (numScanner.hasNextInt()) {
                numbers[currentIndex] = numScanner.nextInt();
            } else {
                System.out.println("You didn't provide enough numbers");
                break;
            }
            currentIndex++;
        }
        numScanner.close();
        scanner.close();
    }
}
  1. java: primitive arrays -- are they initialized?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2020-01-25
    • 1970-01-01
    • 2021-06-25
    • 2018-09-18
    相关资源
    最近更新 更多