Question:
How do you read multiple input types from a scanner?
Answer:
Here is an example.
Code:
import java.util.Scanner; public class ReadInput { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first string: "); String str1 = sc.nextLine(); System.out.print("Enter first int: "); int i1 = sc.nextInt(); sc.nextLine(); // needed to empty buffer System.out.print("Enter second string: "); String str2 = sc.nextLine(); System.out.print("Enter second int: "); int i2 = sc.nextInt(); System.out.println("First string: " + str1); System.out.println("Second string: " + str2); System.out.println("First int: " + i1); System.out.println("Second int: " + i2); sc.close(); } }
Output:
$ java ReadInput Enter first string: the cat in the hat Enter first int: 100 Enter second string: i like java Enter second int: 200 First string: the cat in the hat Second string: i like java First int: 100 Second int: 200