Question:
I want to be able to type in some names and their numbers into my java app and when they're typed in for them to be stored and displayed afterwards on screen. How is this possible? Thanks!
Answer:
By using a scanner and a parallel array.
Code:
import java.util.Scanner; public class NameAndNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int count = 5; String name[] = new String[count]; int number[] = new int[count]; for (int i=0; i<count;i++){ System.out.print("Enter name: "); name[i] = sc.nextLine(); System.out.print("Enter number: "); number[i] = Integer.parseInt(sc.nextLine()); } System.out.println("Output:"); for (int i=0; i<count;i++){ System.out.println(name[i] + " " + number[i]); } } }
Output:
$ java NameAndNumbers Enter name: Tom Jones Enter number: 11 Enter name: Tom Sawyer Enter number: 33 Enter name: Tom Brady Enter number: 12 Enter name: Tom Cruise Enter number: 55 Enter name: Tom Hanks Enter number: 100 Output: Tom Jones 11 Tom Sawyer 33 Tom Brady 12 Tom Cruise 55 Tom Hanks 100