import java.util.Scanner;
public class StudentRoster {
public static void main (String [] args) {
// Declarations of variables
Scanner reader = new Scanner (System.in);
String name; //Student Name
int NumStu; //Number of students
//Prompt user for info
System.out.print ("Enter the number of students: ");
NumStu = reader.nextInt();
int[] roster = new int [NumStu];
for (int i = 0; i < NumStu; i++){
System.out.print ("Enter student name: ");
name = reader.next();
}
System.out.println ("\nStudent Roster");
System.out.print (roster);
}
}
Array Manipulations Program Question
Page 1 of 12 Replies - 432 Views - Last Post: 25 October 2012 - 11:46 PM
#1
Array Manipulations Program Question
Posted 25 October 2012 - 07:06 PM
I'm not sure how to take the student names entered and display it all under Student Roster. I would like help on this.
Replies To: Array Manipulations Program Question
#2
Re: Array Manipulations Program Question
Posted 25 October 2012 - 07:37 PM
name = reader.next();
should probably be
roster[i] = reader.next();
should probably be
roster[i] = reader.next();
#3
Re: Array Manipulations Program Question
Posted 25 October 2012 - 11:46 PM
Although that is one of the problem with the code, I also added additional comments:
Hope this helps you out
import java.util.Scanner;
public class StudentRoster {
public static void main (String [] args) {
// Declarations of variables
Scanner reader = new Scanner (System.in);
// This variable is actually unnecessary
String name; //Student Name
int NumStu; //Number of students
//Prompt user for info
System.out.print ("Enter the number of students: ");
NumStu = reader.nextInt();
// Roster should not be declared as an array which holds integers, but as an array holding strings! (You want to store the names of a student (which is a string))
int[] roster = new int [NumStu];
for (int i = 0; i < NumStu; i++){
System.out.print ("Enter student name: ");
name = reader.next(); //Read pbl's comment, this should be roster[i] = reader.next(). At i'th location, you want to store the name of the i'th student.
}
System.out.println ("\nStudent Roster");
// This will only print a memory reference, instead of the names of the student. You either need a for loop to print or you use the Arrays.toString(<your array>) method to print. The latter one requires an import from java.util.Arrays though.
System.out.print (roster);
}
}
Hope this helps you out
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|