Skip to content
Advertisement

When having String and int as an output – how do I print string first?

This code doesn’t work, whenever I as an user input String data first and then int data, it just accepts input and doesn’t print out the data. If I change:

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

position of these two code blocks, and enter int first and String as second value after then it happily prints first int number and then String. Please help out how to solve it. I want to be able Name and Family name first and then I want to have age.

package package1;

import java.util.Scanner;

public class experiment {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.println("Please enter your age and name: ");

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

            System.out.println("Your age is: " + age);
            System.out.println("Your name is: " + name);
        } finally {
            input.close();
        }
    }

}

My input is:

Aks Eyeless 2022

Advertisement

Answer

Here’s how to enter the name and age on one line.

Please enter your name and age: Gilbert Le Blanc 66
Your age is: 66
Your name is: Gilbert Le Blanc

You perform a Scanner nextLine method, and then you parse (separate) the age from the name. The String class has lots of useful methods for parsing a string.

Here’s the modified code.

import java.util.Scanner;

public class Experiment {
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            System.out.print("Please enter your name and age: ");

            String text = input.nextLine();
            int endIndex = text.lastIndexOf(' ');
            String name = text.substring(0, endIndex);
            int age = Integer.valueOf(text.substring(endIndex + 1));

            System.out.println("Your age is: " + age);
            System.out.println("Your name is: " + name);
        } finally {
            input.close();
        }
    }

}

Advertisement