-1

I have this program to reverse the order of words, but the input is messed up. This is my output log.

1
this is a trial
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at Store_Credit.main(Store_Credit.java:13)

Process finished with exit code 1

And, here is my code :

import java.util.Scanner;

public class Reverse_Words {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N;
        N = scanner.nextInt();
        for(int i = 0; i < N; i++) {
            int h  = i+1;
            String[] s = scanner.nextLine().split(" ");
            System.out.print("Case #"+h+": ");
            for(int j = s.length-1; j >=0; j++) {
                System.out.print(s[j]+" ");
            }
            System.out.println();
        }
    }
}

1 Answers1

-1

try executing this and check if you still get errors

public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        int n;
        System.out.println("enter number");
        n = scanner.nextInt();
        for(int i = 0; i < n; i++) {
            int h  = i+1;

            System.out.println("enter string");

            String[] s = scanner1.nextLine().split(" ");
            System.out.print(s.length);
            System.out.print("Case #"+h+": ");
            for(int j = s.length-1; j >=0; j--) {
                System.out.print(s[j]+" ");
            }
            System.out.println();
        }
    }

decrement j value in the last for loop ie., j-- (not j++)

K.Shali
  • 11
  • 2
  • 1
    The code in the question isn't throwing the mentioned errors. Having two Scanners is unnecessary – OneCricketeer May 27 '17 at 15:29
  • Yup you are right. I realize that. Since I wasn't getting the above said errors I wasn't exactly sure what was wrong with the code. So I gave a code that runs correctly. – K.Shali May 27 '17 at 15:34
  • i think i figured it out. place a scanner.nextLine() after your scanner.nextInt(). Problem is nextInt() doesnt take return. and the nextLine() takes the number n you type as well as the string you type. so adding another scanner.nextLine() helps. – K.Shali May 31 '17 at 03:49