having trouble with nextInt before nextLine, WHERE am I going wrong?

When I use a scanner class with nextInt before a nextLine it ignores the nextLine command, please help!

import java.util.Scanner;

public class test1
public static void main( String [] args )
int yes=0,no=1;

    Scanner scan = new Scanner( System.in );

    System.out.println("Enter a 1 or a 0");
    int choice = scan.nextInt();

        System.out.println( "\nEnter your name > " );
        String name = scan.nextLine();
        System.out.println( "\nYour name is " + name );

            System.out.println( "\nEnter your age > " );
            int age = scan.nextInt();
            System.out.println( "\nYour age is " + age );

        System.out.println("Enter 1");



  • ThriceHexThriceHex Illinois, US

    The nextInt() call is likely leaving a newline character "\n" in the scanner that it's reading instead. Add an extra scan.nextLine() without assigning it a variable before String name = scan.nextLine()

  • ThriceHexThriceHex Illinois, US

    You can also replace scan.nextInt() with Integer.parseInt(scan.nextLine()) as well and not have to worry about putting in the extra scan.nextLine()

  • Thanks ThriceHex

  • cmihadcmihad Bangladesh

    just use scan.next()
    instead of using scan.nextLine

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!