0

So this is the code I am using:

System.out.println("Create a name.");
name = input.nextLine();
System.out.println("Create a password.");
password = input.nextLine();

But when it reaches this point it just says "Create a name." and "Create a password." both at the same time and then I have to type something. So it's basically skipping the Scanner parts where I need to type a String. After "Create a name." and "Create a password." is outprinted and I type then, both name and password are changing to what I typed in. How do I fix this?

This is the full class. I am just testing so it isn't actually going to be a program:

package just.testing;

import java.util.Scanner;
public class TestingJava
{
    static int age;
    static String name;
    static String password;
    static boolean makeid = true;
    static boolean id = true;

    public static void main(String[] args){
        makeid(null);
        if(makeid == true){
            System.out.println("Yay.");
        }else{

        }
    }
    public static void makeid(String[] args){
        System.out.println("Create your account.");
        Scanner input = new Scanner(System.in);
        System.out.println("What is your age?");
        int age = input.nextInt();
        if(age<12){
            System.out.println("You are too young to make an account.");
            makeid = false;
            return;
        }
        System.out.println("Create a name.");
        name = input.nextLine();
        System.out.println("Create a password.");
        password = input.nextLine();
        return;
    }
}

And sorry for my bad grammar. I am not English so it is kinda hard for me to explain this.

Reflex Donutz
  • 11
  • 1
  • 1
  • 7

4 Answers4

10

The nextInt() ate the input number but not the EOLN:

Create your account.
What is your age?
123 <- Here's actually another '\n'

so the first call to nextLine() after create name accept that as an input.

System.out.println("Create a name.");
name = input.nextLine(); <- This just gives you "\n"

User Integer.parseInt(input.nextLine()) or add another input.nextLine() after reading the number will solve this:

int age = Integer.parseInt(input.nextLine());

or

int age = input.nextInt();
input.nextLine()

Also see here for a duplicated question.

Community
  • 1
  • 1
zw324
  • 25,032
  • 15
  • 79
  • 112
1

This doesnt actually tell you why the lines are being skipped, but as you're capturing names and passwords you could use Console:

Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));
Sean Landsman
  • 6,458
  • 2
  • 24
  • 29
0

You can also use next() instead of nextLine(). I have tested it in eclipse. its working fine.

RajputAdya
  • 63
  • 1
  • 8
0

next() will work but it will not read the string after space.

Robert
  • 5,191
  • 43
  • 59
  • 113