-1

I'm new to java and I was trying to Scanner. Everything works but when I input the age the adress gets skipped:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your surname: ");
        String surname = scanner.nextLine();

        System.out.println("Enter your age: ");
        int age = scanner.nextInt();

        System.out.println("Enter your address: ");
        String address = scanner.nextLine();

        System.out.println("Your name is " + name + " " + surname);
    }
}

I'm stuck so, could someone help please?

1 Answers1

0

the problem you are facing is because after you enter the age, the nextInt() method does not consume the newline character. So, when you call nextLine() to read the address, it consumes the newline character left by the nextInt() method and returns an empty string. There are 2 ways to fix this. The first method is to use nextLine() again after the age:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your surname: ");
        String surname = scanner.nextLine();

        System.out.println("Enter your age: ");
        int age = scanner.nextInt();
        scanner.nextLine(); // consume the newline character

        System.out.println("Enter your address: ");
        String address = scanner.nextLine();

        System.out.println("Your name is " + name + " " + surname);
    }
}

The other way which I prefer is by using the type that you need:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your surname: ");
        String surname = scanner.nextLine();

        System.out.println("Enter your age: ");
        int age = Integer.parseInt(scanner.nextLine());

        System.out.println("Enter your address: ");
        String address = scanner.nextLine();

        System.out.println("Your name is " + name + " " + surname);
    }
}

So in this second example you are getting something in input, and you are transforming in into the type that you want. Hope this helps!

Skerdi Velo
  • 121
  • 2
  • 13