Scanner doesn't collecting number and char values in same time

`public static void main(String[] args) {
// TODO code application logic here

    Scanner input = new Scanner(System.in);
    System.out.print("Please enter a number base and an English letter base, separated by space: ");

int numberBase = input.nextInt();
char englishBase = input.nextLine().charAt(0);`

    System.out.println("numberbase is: "+ numberBase + "englishBase is : " + englishBase);
}

I want to collect two value and store first one to int and the secont one to char, I can store the int value but not char after int . could you please check what is my wrong.

I tried following code but doesn’t work:

System.out.print("Please enter a number base and an English letter base, separated by space: "); int numberBase = input.nextInt(); input.nextLine(); char englishBase = input.nextLine().charAt(0);

>Solution :

input.nextInt() will read only integer value, if you want to read both from same line then either read this as a String and you will have to do some additional operation to extract the values. You can refer the below code for that –

Scanner input = new Scanner(System.in);
System.out.print("Please enter a number base and an English letter base, separated by space: ");
String[] line = input.nextLine().split(" ");
int numberBase = Integer.parseInt(line[0]);
char englishBase = line[1].charAt(0);
System.out.println("numberbase is: "+ numberBase + " englishBase is : " + englishBase);

Or use below approach –

 System.out.print("Please enter a number base and an English letter base, separated by space: ");
 int numberBase = input.nextInt();
 char englishBase = input.next().charAt(0);
 System.out.println("numberbase is: "+ numberBase + " englishBase is : " + englishBase);

Leave a Reply