Do you add objects to an array when using switch statement with a For loop?
I meant....
"HOW" do you add objects to an array....
I have four classes.
Person is the super class, Student, Undergraduate, and PolymorphismExample.
I somewhat understand how to add objects into an array, whoever, I'm not sure how to do it when using inputs in a switch statement contained in a for loop. How would I go about in doing that?
Code :
import java.util.Scanner;
public class PolymorphismExample
{
public static void main(String[] args)
{
Person[] people = new Person[4];
people[0] = new Person();
people[1] = new Undergraduate( );
people[2] = new Person();
people[3] = new Student();
char userInput;
Scanner keyboard = new Scanner (System.in);
for(int i=0; i<4; i++)
{
String name;
int number;
int level;
System.out.print("Enter the type of Person: ");
userInput = keyboard.next().charAt(0);
switch(userInput)
{
case 'P':
System.out.print("Enter in a name: ");
name = keyboard.next();
break;
case 'S':
System.out.print("Enter in a name: ");
name = keyboard.next();
System.out.print("Enter a student number: ");
number = keyboard.nextInt();
break;
case 'U':
System.out.print("Enter in a names: ");
name = keyboard.next();
System.out.print("Enter a student number: ");
number = keyboard.nextInt();
System.out.print("Enter a level ");
level = keyboard.nextInt();
break;
default:
System.out.println("You picked a value other than P, S, U");
}
}
}
}
The ultimate goal is to get to here....
Enter the type of person: P
Enter a name: Philip Rivers
Enter the type of person: U
Enter a name: Vincent Jackson
Enter a student number: 83
Enter a level: 3
Enter the type of person: P
Enter a name: Ryan Mathews
Enter the type of person: S
Enter a name: Antonio Gates
Enter a student number: 85
Person 1:
Name: Philip Rivers
Person 2:
Name: Vincent Jackson
Student Number: 83
Student Level: 3
Person 3:
Name: Ryan Mathews
Person 4:
Name: Antonio Gates
Student Number: 85
Re: Do you add objects to an array when using switch statement with a For loop?
Hi,
For two word input from user try nextLine.
Core java
Re: Do you add objects to an array when using switch statement with a For loop?
Quote:
I'm not sure how to do it when using inputs in a switch statement contained in a for loop.
The location of the assignment statement should not make any difference. If you know how to write a statement to assign a value to an element of an array, you can code that statement in the loop or switch statement