Skip to content
Advertisement

Program is having issues with inputting arrays

The output for the following code is: Please enter your words: hello, keshav, bob, doan kehsavbob Exception in thread “main” java.lang.NumberFormatException: For input string: “kehsavbob” at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:668) at java.base/java.lang.Integer.parseInt(Integer.java:786) at MyClass.main(MyClass.java:101)

      public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read in the method name that we want to call
        System.out.print("Please enter your words: ");
        String methodName = sc.nextLine();
        // Read in number of words
        int numWords = Integer.parseInt(sc.nextLine());
        // Read in list of words
        String[] words = new String[numWords];
        for (int i = 0; i < numWords; i++) {
            words[i] = sc.nextLine();
        }
        sc.close();

        // Run the specified method
        switch (methodName) {
            case MIN_METHOD_NAME:
                System.out.println(minWordLength(words));
                break;
            case MAX_METHOD_NAME:
                System.out.println(maxWordLength(words));
                break;
            case RANGE_METHOD_NAME:
                System.out.println(wordLengthRange(words));
                break;
            case AVERAGE_METHOD_NAME:
                System.out.println(averageWordLength(words));
                break;
            case MODE_METHOD_NAME:
                System.out.println(mostCommonWordLength(words));
                break;
            default:
                throw new UnsupportedOperationException();
        }

}

Advertisement

Answer

You are trying to parse an integer from a word, which won’t work.

Replace:

int numWords = Integer.parseInt(sc.nextLine());
String[] words = new String[numWords];

with:

String[] words = sc.nextLine().split("W+");
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement