Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading