0
package newproj;

import java.util.Scanner;

public class MyFirstClass 

{

    public static void main(String[] args) 
    {
        char a;
        int b;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter value b: ");
        b= sc.nextInt();
        System.out.print("Enter char: ");
        a = sc.nextLine().charAt(0);
        System.out.println("This is "+a);
    }

}

The error reflected on console during runtime is Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1.

Can someone teach me how to scan a character after scanning an integer. In C programming, there is the "fflush(stdin)" to help the scanf function. So, I was thinking along the line that the newline character was scanned in instead.

Albert Iordache
  • 409
  • 5
  • 15
  • 1
    possible duplicate of [Skipping nextLine() after use nextInt()](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint) – Rohit Jain Sep 06 '13 at 09:43
  • Thanks for the reference. Didn't expect the answer to be so simple. –  Sep 06 '13 at 09:48

2 Answers2

1

Read the input line by line and parse the first line to int. If it contains invalid characters, a NumberFormatException will be thrown.

public static void main(String[] args) throws NumberFormatException
{
    char a;
    int b;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter value b: ");
    b = Integer.parseInt(sc.nextLine());
    System.out.println("Enter char: ");
    a = sc.nextLine().charAt(0);
    System.out.println("This is "+a);
}
Konstantin Yovkov
  • 59,030
  • 8
  • 92
  • 140
1

Change your code as follows

    char a;
    int b;
    Scanner sc = new Scanner(System.in);
    Scanner sc1 = new Scanner(System.in);
    System.out.print("Enter value b: ");
    b= sc.nextInt();
    System.out.print("Enter char: ");
    a = sc1.nextLine().charAt(0);
    System.out.println("This is "+a);
Ruchira Gayan Ranaweera
  • 32,406
  • 16
  • 66
  • 105