我需要一种方法来修复我的代码中的这些错误

问题描述 投票:0回答:0

我不明白为什么我的代码很奇怪。如果我给出 3 的索引,我只能为数组获得 2 个输入。它不应该发生。所以我在收到的输入中加了 1,但我也需要原因。然后错误是 StringOutOfBoundsException 和 NumberFormatException。通常我会收到 StringOutOfBoundsException,所以我删除了子字符串方法并将数字作为输入,然后我收到了 NumberFormatException。我只给了整数作为输入,这没有错。

`

import java.util.Scanner;
class Main{
    public static void main(String [] args){
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a number : ");
        int n = s.nextInt();
        n+=1;
        int max = 0;
        int a = 0;
        int b = 0;
        String [] arr = new String [n];
        System.out.println("Enter elements of array : ");
        for (int i =0;i<n;i++){
            arr[i] = s.nextLine();
        }
        for (int i =0;i<n;i++){
            System.out.println(arr[i]);
        }
        for(int i = 0;i<n;i++){
            for(int j = i+1;j<n;j++){
                a = Integer.parseInt(arr[i].substring(9));
                b = Integer.parseInt(arr[j].substring(9));
                if(a<b){
                    max = b;
                }
                else{
                    max = a;
                }
            }
        }
        System.out.println(max);
    }
}

`

arrays string numberformatexception
© www.soinside.com 2019 - 2024. All rights reserved.