0

My code had a problem with Scanner, when I created a Scanner to receive variables from the user when I used the different methods of ".next", it was dismissing certain inputs. Here is what I got:

package com.company;

import java.util.Scanner;

public class Practice6 {
    public static void main(String[] arg) {
        
        Scanner input = new Scanner(System.in);

        System.out.println("It is a simple calculator sums two variables,");

        System.out.print("Please enter the first number: ");
        byte firstNumber = input.nextByte();
        System.out.print("Please enter the second number: ");
        byte secondNumber = input.nextByte();

        System.out.print("Please enter your name: ");
        String name = input.nextLine();
        System.out.print("Please enter your student ID: ");
        String id = input.nextLine();

        System.out.print(name + " (" + id + ")" + " the result is: ");
        System.out.println(firstNumber+secondNumber);

    }
}

What it shows in the terminal is:

It is a simple calculator sums two variables,
Please enter the first number: 2
Please enter the second number: 3
Please enter your name: Please enter your student ID: 9524021
 (9524021) the result is: 5

Can you explain to me why "String name = input.nextLine();" is being ignored?

Mohammad Rahmani
  • 364
  • 1
  • 3
  • 11

0 Answers0