You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何用try-catch处理数组无效输入,避免程序从头重启

Fixing Input Handling to Resume from Error Position

Got it, let's tackle this problem where invalid inputs force the entire process to restart instead of just re-prompting for the bad entry. We can adjust your code to build each array incrementally, catch errors per-input, and keep going without resetting everything.

Key Changes We'll Make:

  • Move array initialization and the Scanner instance outside the try-catch block so we don't reset them every time there's an error
  • Handle input validation per element instead of wrapping the entire array input in one try-catch
  • Clear the invalid input from the Scanner buffer when an error occurs to avoid infinite loops
  • Simplify the sum calculation (no need to cast loop variables unnecessarily)

Modified Code:

import java.util.Scanner;

public class Array {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in); // Initialize Scanner once
        int z = 1;
        
        do {
            double[] myArr1 = new double[10];
            System.out.println("\nEnter 10 elements for the first array: ");
            
            // Build first array with per-input error handling
            for (int x = 0; x < myArr1.length; ) {
                System.out.print("Element " + (x + 1) + ": ");
                try {
                    myArr1[x] = scanner.nextDouble();
                    x++; // Only increment index if input is valid
                } catch (Exception e) {
                    System.out.println("Invalid input! Please enter a number.");
                    scanner.next(); // Clear the invalid input from buffer
                }
            }
            
            // Calculate sum for first array
            double sum1 = 0;
            for (double num : myArr1) {
                sum1 += num;
            }
            
            double[] myArr2 = new double[10];
            System.out.println("\nEnter 10 elements for the second array: ");
            
            // Build second array with same error handling
            for (int y = 0; y < myArr2.length; ) {
                System.out.print("Element " + (y + 1) + ": ");
                try {
                    myArr2[y] = scanner.nextDouble();
                    y++; // Increment only on valid input
                } catch (Exception e) {
                    System.out.println("Invalid input! Please enter a number.");
                    scanner.next(); // Clear invalid input
                }
            }
            
            // Calculate sum for second array
            double sum2 = 0;
            for (double num : myArr2) {
                sum2 += num;
            }
            
            // Output results
            System.out.println("\nSum of first 10 elements is: " + sum1);
            System.out.println("Sum of second 10 elements is: " + sum2);
            
        } while (z == 1);
        
        scanner.close(); // Clean up Scanner
    }
}

How This Works:

  • For each array element, we prompt the user and try to read a double. If the input is invalid, we catch the exception, tell the user to try again, and clear the bad input from the Scanner (using scanner.next()) so it doesn't keep causing errors.
  • We only increment the loop index (x or y) when we get a valid input, so we stay on the same element until the user enters something correct.
  • The Scanner is initialized once at the start, and we close it at the end to avoid resource leaks.
  • We use enhanced for-loops for summing, which makes the code cleaner and avoids unnecessary casting.

内容的提问来源于stack exchange,提问作者Haganation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:12:28