0

I was practice using methods in java and made a program for calculating two numbers (code posted below).

My program gives java.lang.StringIndexOutOfBoundsException error when the user reaches this message:

Press 'y' to show the menu again or 'n' to terminate!

I know that if I used char again = input.next().charAt(0); the program will work just fine!

BUT why using char again = input.nextLine().charAt(0); gives an error while the user didn't even have the chance to enter a string?


Here is the full code:

import java.util.Scanner;

public class Test1 {


 public static void menu (){

    System.out.println("1.Addition");
    System.out.println("2.Subtraction");
    System.out.println("3.Multiplication");
    System.out.println("");

 }

 public static int add (int n1, int n2){

     int result = n1 + n2;

     return result;
 }

public static int sub (int n1, int n2){

     int result = n1 - n2;

     return result;
 }

public static int mul (int n1, int n2){

     int result = n1 * n2;

     return result;
}


public static void main (String[] args){

    Scanner input = new Scanner (System.in);

    int menu, reset = 0; 

    while (reset != 1){
    do {
    menu();
    System.out.print("Choose from 1 ~ 3: ");
    menu = input.nextInt();

    } while( menu <= 0 || menu > 3); 

    System.out.print("Enter first number: ");
    int n1 = input.nextInt();
    System.out.print("Enter second number: ");
    int n2 = input.nextInt();


    switch (menu){

    case 1: System.out.println("The addition of " + n1 + " + " + n2 + " is " + add(n1, n2)); break;
    case 2: System.out.println("The subtraction of " + n1 + " - " + n2 + " is " + sub(n1, n2)); break;
    case 3: System.out.println("The multiplication of " + n1 + " * " + n2 + " is " + mul(n1, n2)); break;

    }

    System.out.print("\nPress 'y' to show the menu again or 'n' to terminate!: ");
    char again = input.nextLine().charAt(0); // here is the problem



    if (again == 'y'){

        reset = 0;
    }

    else if ( again == 'n'){

        reset = 1;

        System.out.println("BYE!");

    }

    else {

        System.out.println("INVAILD INPUT!");
        reset = 1;
        System.exit(1);
    }
}
}

}
Abdulelah
  • 75
  • 5
  • 1
    `nextLine()` might return an empty string. – Thomas Oct 20 '16 at 13:49
  • Your problem is that your `nextInt()` calls are not handling the End-Of-Line token. Please look at the [duplicate question](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) to see more on this. – Hovercraft Full Of Eels Oct 20 '16 at 13:50

0 Answers0