import java.util.*;
//student class
class Student{
String name;
int rollNo;
Student(String name, int rollNo){
this.name=new String(name);
this.rollNo=rollNo;
}
}
class Demo {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int noOfStudents = in.nextInt();
Student[] StudentList= new Student[noOfStudents];
PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
public int compare(Student a, Student b){
return b.rollNo-a.rollNo;
}
});
for(int i=0;i<noOfStudents;i++){
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
set.add(new Student(name,rollNo));
}
while(!set.isEmpty()){
Student tmp = set.poll();
System.out.println(tmp.name+" "+tmp.rollNo);
}
}
}
I am trying to take n students name and roll no and then printing it. But this is not printing the names of student
I have added the extra nextline() to enable integer entry
I always feel difficulty in this thing. Please help!
Replace
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
by
in.nextLine();
String name = in.nextLine();
int rollNo = in.nextInt();
You can find the full explanation of your issue here : https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/
Change:
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
to
String name = in.next();
int rollNo = in.nextInt();
I think this version works as you can see from the picture. I added this line:
in.nextLine(); // it consumes the newline and moves to the starting of the next line.
Here's the code:
import java.util.*;
//student class
class Student{
String name;
int rollNo;
Student(String name, int rollNo){
this.name=new String(name);
this.rollNo=rollNo;
}
}
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Inert the number of students, please");
int noOfStudents = in.nextInt();
Student[] StudentList= new Student[noOfStudents];
PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
public int compare(Student a, Student b){
return b.rollNo-a.rollNo;
}
});
for(int i=0;i<noOfStudents;i++){
in.nextLine(); // it consumes the newline and moves to the starting of the next line.
System.out.println("Enter the student's name "+i);
String name = in.nextLine();
System.out.println("Enter the student ID number "+i);
int rollNo = in.nextInt();
set.add(new Student(name,rollNo));
}
while(!set.isEmpty()){
Student tmp = set.poll();
System.out.println(tmp.name.toString()+" "+tmp.rollNo);
}
}
}
Execution of Java program
Best regards from Italy.
Related
I tried adding a new class per a suggestion I was given, which is seen at line 67. I am unsure how to link the new class with the entries created from user input and the goal is to sort the ArrayList by the last name and to calculate averages of each of the entries 4 test scores, resulting in an average score - I would like the average score to be added to each students entry and added to the final ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
//information given by user input that will eventually go into the ArrayList
public class studentInformation {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Object> studentdatabase = new ArrayList<Object>();
char cont;
do {
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
//String fn = fnInput.nextLine();
studentdatabase.add(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
//String ln = lnInput.nextLine();
studentdatabase.add(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
//int score1 = score1Input.nextInt();
studentdatabase.add(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
//int score2 = score2Input.nextInt();
studentdatabase.add(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
//int score3 = score3Input.nextInt();
studentdatabase.add(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
//int score4 = score4Input.nextInt();
studentdatabase.add(score4Input.nextInt());
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//calculate the average score for each student
//sort the ArrayList prior to printing
//Collections.sort(studentdatabase);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' || cont != 'C');
}
class Students {
String firstName, lastName;
int firstScore, secondScore, thirdScore, fourthScore, averagescore;
char lettergrade;
}
}
Fisrt, create a real Student class (singular, not plural). An instance of this class is only one student. It will handle average calculation in a dedicated method.
Think about using getters and setters with the correct accessors on your attributes.
public class Student {
private String firstName, lastName;
private int firstScore, secondScore, thirdScore, fourthScore, averagescore;
private char lettergrade;
public float computeAverage(){
int sum = firstScore + secondScore + thirdScore + fourthScore;
return (float) sum / 4;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getFirstScore() {
return firstScore;
}
public void setFirstScore(int firstScore) {
this.firstScore = firstScore;
}
public int getSecondScore() {
return secondScore;
}
public void setSecondScore(int secondScore) {
this.secondScore = secondScore;
}
public int getThirdScore() {
return thirdScore;
}
public void setThirdScore(int thirdScore) {
this.thirdScore = thirdScore;
}
public int getFourthScore() {
return fourthScore;
}
public void setFourthScore(int fourthScore) {
this.fourthScore = fourthScore;
}
public int getAveragescore() {
return averagescore;
}
public void setAveragescore(int averagescore) {
this.averagescore = averagescore;
}
public char getLettergrade() {
return lettergrade;
}
public void setLettergrade(char lettergrade) {
this.lettergrade = lettergrade;
}
}
Then, don't use Object in your list but Student. You created an object. Use it !
You can't sort the list until you're done with feeding it. Put the sort out of the loop.
cont != 'c' || cont != 'C'
will always be true. So you will never get out of your loop.
Finally, I would suggest something like this.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Student> studentdatabase = new ArrayList<Student>();
char cont;
do {
Student currentStudent = new Student();
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
currentStudent.setFirstName(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
currentStudent.setLastName(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
currentStudent.setFirstScore(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
currentStudent.setSecondScore(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
currentStudent.setThirdScore(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
currentStudent.setFourthScore(score4Input.nextInt());
studentdatabase.add(currentStudent);
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' && cont != 'C');
//sort the arrayList prior to printing
studentdatabase.sort(Comparator.comparing(Student::getLastName));
//studentdatabase.sort(Comparator.comparing(Students::getLastName).reversed());
for (Student student:studentdatabase) {
System.out.println(student.getLastName() + " " + student.getFirstName() + " : " + student.computeAverage());
}
}
}
My program below prompts the user for how many children they have in their class. After entering the number they will enter all of the names of their students (first) and (last). Because of this I entered a scan Next Line statement instead of just scan.next. Because of this whatever number you enter the program will prompt you for one less. Please help.
public class studentRoster {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String [] students;
int size;
System.out.println("Enter the amount of students in your class: ");
size = scan.nextInt();
students = new String[size];
for (int i = 0; i < students.length; i++ ){
System.out.println("Enter a student name: ");
students [i] = scan.next();
}
System.out.println("Student Roster");
for ( int i = 0; i < students.length; i++ ){
System.out.println(students[i]);
}
}
}
Using scan.next() only captures up to the first space encountered, so you'll want to use .nextLine() if the user is entering both the first and last name at the same time.
To make this code work, add scan.nextLine(); after you assign sizeto the user input. Then, change students [i] = scan.next(); to students [i] = scan.nextLine();.
The reason you need to do this is because .nextInt() doesn't take in the last newline of the user's input, so you need to call .nextLine() to account for that.
public class StudentRoster {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String [] students;
int size;
System.out.print("Enter the amount of students in your class: ");
size = scan.nextInt();
scan.nextLine();
students = new String[size];
for (int i = 0; i < students.length; i++ ){
System.out.print("Enter a student name: ");
students [i] = scan.nextLine();
}
System.out.println("Student Roster");
for ( int i = 0; i < students.length; i++ ){
System.out.println(students[i]);
}
}
}
Test output
Enter the amount of students in your class: 4
Enter a student name: john Q
Enter a student name: albert E
Enter a student name: tyler D
Enter a student name: mickey M
Student Roster
john Q
albert E
tyler D
mickey M
the problem is this line
size = scan.nextInt();
becuase nextInt() method doesn't consume all the input buffer, it leaves the last (\n) character. When you call nextLine() after that it will not wait for the user to enter any thing but it will consume the (\n) character left in the buffer as a residue from the previous nextInt() method
so to correct this you have 2 options :
put additional scan.nextLine() directly after each scan.nextInt() method to consume the (\n)
size = scan.nextInt();
scan.nextLine();
students = new String[size];
//your code
Get the size as a string then convert it to int
String temp = scan.nextLine();
int size = Integer.parseInt(temp);
I suggest you to use an object better suited for your purpose (I think it's easier to hold data and improves readability):
import java.util.Scanner;
public class StudentRoster {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student[] students;
int size;
String name;
String lastname;
System.out.println("Enter the amount of students in your class: ");
size = scan.nextInt();
students = new Student[size];
Student student;
for (int i = 0; i < students.length; i++) {
student = new Student();
System.out.println("Enter a student name: ");
name = scan.next();
System.out.println("Enter a student lastname: ");
lastname = scan.next();
student.setName(name);
student.setLastname(lastname);
students[i] = student;
}
System.out.println("Student Roster");
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName());
System.out.println(students[i].getLastname());
}
}
static class Student {
String name;
String lastname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
}
Could anybody tell me how to list some data in an arrayList according to the integer value that each component of the ArrayList has? This is my main class
import java.util.Scanner;
import java.io.*;
import java.util.Collections;
import java.util.ArrayList;
public class StudentDriver {
public static void main(String[] args) throws IOException {
Scanner scan, urlScan, fileScan;
String url, file;
int count = 0;
scan = new Scanner(System.in);
System.out.println("Enter the name of the file");
fileScan = new Scanner(new File("Data.csv"));
ArrayList<Student> studentList = new ArrayList<Student>();
while(fileScan.hasNext()){
url = fileScan.nextLine();
urlScan = new Scanner(url);
urlScan.useDelimiter(",");
count++;
while(urlScan.hasNext()){
String name = urlScan.next();
String last = urlScan.next();
int score = urlScan.nextInt();
Student e = new Student(name,last, score);
studentList.add(e);
}
}
System.out.println("The file has data for" +count+ "instances");
int option;
do{
System.out.println("********");
System.out.println("Options:");
System.out.println("********\n1. List \n2. Add Student \n3.Delete Student \n4. Exit \n******** ");
System.out.print("Select option: ");
option = scan.nextInt();
if(option == 1){
int index = 0;
while(index<studentList.size()){
System.out.println(studentList.get(index));
index++;
}
}
else if(option == 2){
System.out.print("Enter the name of the student: ");
String newName = scan.next();
System.out.print("Enter the last name of the student: ");
String newLastName = scan.next();
System.out.print("Enter the exam score of the student: ");
int newScore = scan.nextInt();
Student b = new Student(newName, newLastName, newScore);
studentList.add(b);}
else if(option == 3){
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
location = studentList.indexOf(remove1);
studentList.remove(location);
}
}while(option!=4 && option <4);
}//main
}//class
And this is the other class
public class Student implements Comparable<Student>{
String firstName, lastName;
int score;
public Student(String firstName, String lastName, int score){
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return firstName + " " + lastName + ", exam score is "+ score;
}
#Override
public int compareTo(Student c) {
return score-c.getScore();
}
}
As you can see, up to now I have created the class where my compare method is but I have difficulties on using it. Also I have had difficulties on deleting one of the Array List parts by just writing the name and last name of the student. If somebody would help me, I would be very thankful.
well you can change your compareTo method as
public int compareTo(Student another)
{
if (this.score > another.score)
return -1;
if (this.score < another.score)
return 1;
else
return 0;
}
this should show it as decreasing order you can change the operator
than use whereever you want to sort it
Collections.sort(studentList)
Also if you don't want to use Collections.sort() method I can show you how you can write it with for loop under add option
Student newStd = new Student(name, last, score);
for(int i=0;studentList.size()>i;i++)
{
int size = studentList.size();
if(newStd.compareToCustom(studentList.get(i))>0)
{
studentList.add(i, newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(size-1))<0)
{
studentList.add(studentList.size(), newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(i))==0)
{
studentList.add(i++, newStd);
break;
}
}
for the remove part you can use
else if ( option == 3)
{
System.out.print("Enter the first name of student will be deleted: ");
String removeName = scan.next();
System.out.print("Enter the last name of student will be deleted: ");
String removeLastName = scan.next();
for ( int i = 0; i < studentList.size(); i++)
{
Student deleted = studentList.get(i);
if ( deleted.getFirstName().toLowerCase().equals(removeName.toLowerCase()) && deleted.getLastName().toLowerCase().equals(removeLastName.toLowerCase()))
{
studentList.remove(i);
System.out.println("The student has been deleted.");
break;
}
else
{
System.out.println("This student is not found");
break;
}
}
}
Basically what you want is an ordered collection. As #duffymo has stated, think about a creating a custom Comparator using your score.
There is plenty of info here
In terms of deleting students from the list.
The studentList is a list containing Student objects.
This means that the follow code:
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
Tries to find the index of a Student given the first name. This will return -1 as you're searching for a String and not a Student object.
Instead you have to iterate through your studentList and compare the first and last name of each Student element with the values of remove and remove1.
for(Student student : studentList) {
if(student.getFirstName.equals(remove) && student.getLastName.equals(remove1)) {
// remove the student.
}
}
Also you could consider giving each Student an ID as an unique identifier.
try this to sort studentList
Collections.sort(studentList, new Comparator<Student>()
{
#Override
public int compare(Student x, Student y)
{
if(x.score >= y.score)
return 1;
else
return -1;
}
});
I am almost done with this project. I need help figuring out why it does not pause after asking for the last name before it asks for the first name. I also keep getting an error when I try to add a new Comparator to sort by score.
package student.scores;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.*;
public class StudentScores{
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
Scanner input = new Scanner (System.in);
System.out.println("Enter number of students: ");
int numStudents = input.nextInt();
List<Student> students = new ArrayList<>();
for (int i = 0; i < numStudents; i++) {
System.out.println("Enter Student Last Name: ");
String lastName = input.nextLine();
System.out.println("Enter Student First Name: ");
String firstName = input.nextLine();
System.out.println("Enter Student Score: ");
int score = input.nextInt();
students.add(new Student(lastName, firstName, score));
}
Collections.sort(students);
System.out.println("Students in alphabetical order");
for (Student s : students) {
System.out.println(s);
}
Collections.sort(students, new Comparator() {});
System.out.println("Students by score");
for (Student s : students) {
System.out.println(s);
}
static class Student implements Comparable<Student>
{
private String lastName;
private String firstName;
private int scores;
public Student (String lastName, String firstName, int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.scores = score;
}
public int getScores()
{
return scores;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
#Override
public int compareTo(Student s)
{
if (s.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(s.firstName);
}
return lastName.compareToIgnoreCase(s.lastName);
}
static class StudentScoreComparator implements Comparator<Student>
{
#Override
public int compare(Student o1, Student o2)
{
return (Integer.valueOf(o1.getScores())).compareTo(o2.getScores());
}
}
#Override
public String toString() {
return String.format("%s %s %d", firstName, lastName, scores);
}
}
}
I believe the easiest approach for also sorting by score is to add a second class that implements Comparator<Student> like
static class StudentScoreComparator implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
return (Integer.valueOf(o1.getScores())).compareTo(o2.getScores());
}
}
Then you can pass an instance of that Comparator to the sort methods, and sort by score.
Edit
Then I would add a toString() to Student like
#Override
public String toString() {
return String.format("%s %s %d", firstName, lastName, scores);
}
Edit 2
I think your main() was supposed to look like,
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
Scanner input = new Scanner (System.in);
System.out.println("Enter number of students: ");
int numStudents = input.nextInt();
List<Student> students = new ArrayList<>();
for (int i = 0; i < numStudents; i++) {
System.out.println("Enter Student Last Name: ");
String lastName = input.nextLine();
System.out.println("Enter Student First Name: ");
String firstName = input.nextLine();
System.out.println("Enter Student Score: ");
int score = input.nextInt();
students.add(new Student(lastName, firstName, score));
}
Collections.sort(students);
System.out.println("Students in alphabetical order");
for (Student s : students) {
System.out.println(s);
}
Collections.sort(students, new StudentScoreComparator());
System.out.println("Students by score");
for (Student s : students) {
System.out.println(s);
}
}
Your code is not using the Student class at all. You need to be capturing the first name, last name, and score of each Student and storing the entry in an array of Student objects.
System.out.print("Enter student's first name: ");
String fname = input.next(); // Since names should not have white spaces, use next() instead of nextLine()
System.out.print("Enter student's last name: ");
String lname = input.next();
System.out.print("Enter student's score");
int score = input.next();
record[i] = new Student(fname, lname, score);
The code snippet above should be inside your loop. Each iteration you are capturing a student's full name and score, and adding a new instance of Student inside your Student array. The way I understood your assignment, each Student object represents a record. The array can (and will) have multiple entries for a particular student, but not necessarily in order. The sorting helps with printing out all records for the same student one after the other. For example, index 0 of the array could be for "Joe Smith" while index 1 could be for "Anne Johnson". When sorted, all of the records for Anne Johnson should be listed first, then Joe Smith's records.
To sort by name, you need to compare the current index to the next, if there is one to compare. First, you must grab the last name and compare them. If they are equal, grab the first name. If they are equal, assume they (the records) are for the same student (and you can decide at that point to grab the score to sort by score). If the names are different, the records are for different students so you must execute sorting. I am sure this is a school assignment, so use one of the sorting algorithms taught in class (maybe bubble sort) and sort the array. Most likely, you will need multiple passes for the array to be fully sorted by name and scores.
I figured out my problem. I added an import for the Comparable method. I also changed it to add a line between the output.
package student.scores;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.*;
import student.scores.StudentScores.Student.StudentScoreComparator;
public class StudentScores{
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
Scanner input = new Scanner (System.in);
System.out.println("Enter number of students: ");
int numStudents = input.nextInt();
List<Student> students = new ArrayList<>();
int counter = 1;
for(int i = 0; i < numStudents; i++) {
int studentNum = counter++;
System.out.println("\nStudent " + studentNum);
System.out.println("Enter Student Last Name: ");
String lastName = input.next();
System.out.println("Enter Student First Name: ");
String firstName = input.next();
System.out.println("Enter Student Score: ");
int score = input.nextInt();
students.add(new Student(lastName, firstName, score));
}
Collections.sort(students);
System.out.println("Students in alphabetical order: ");
for (Student s : students) {
System.out.println(s);
}
System.out.println();
Collections.sort(students, new StudentScoreComparator());
System.out.println("Students by score:");
for (Student s : students) {
System.out.println(s);
}
}
static class Student implements Comparable<Student>
{
private String lastName;
private String firstName;
private int scores;
public Student (String lastName, String firstName, int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.scores = score;
}
public int getScores()
{
return scores;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
#Override
public int compareTo(Student s)
{
if (s.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(s.firstName);
}
return lastName.compareToIgnoreCase(s.lastName);
}
static class StudentScoreComparator implements Comparator<Student>
{
#Override
public int compare(Student o1, Student o2)
{
return (Integer.valueOf(o1.getScores())).compareTo(o2.getScores());
}
}
#Override
public String toString() {
return String.format("%s %s %d", firstName, lastName, scores);
}
}
}
import java.util.*;
public class Student {
private String [] first;
private String [] last;
private String [] HKID;
private String[] SID;
private int []Exam;
private int num;
Scanner kb= new Scanner(System.in);
public Student (String f, String l, String h, String s, int e, int n){
System.out.println("Please enter number of students:");
n = kb.nextInt();
for(int i=0;i >n; i++){
System.out.println("First name:");
f = kb.next();
first = new String[f];
System.out.println("Last name:");
l=kb.next();
last= new String[l];
System.out.println("HKID:");
h=kb.next();
HKID=new String[h];
System.out.println("SID:");
s=kb.next();
SID=new String [s];
System.out.println("Final exam score:");
e=kb.nextInt();
Exam=new int [e];
}
public String[] getFirst(){return first;}
public String [] getLast(){return last;}
public String [] getHKID(){return HKID;}
public String [] getSID(){return SID;}
public int [] getExam(){return Exam;}
public void setFirst(String [] f){f=first;}
public void setLast(String [] l){l=last;}
public void setHKID(String [] h){h=HKID;}
public void setSID(String [] s){s= SID;}
public void setExam(int [] e){e=Exam;}
}
I am creating a code that first asks user how many students are in the class. From this it asks several details to enter for each student and stored in their respective arrays. Problem: I can't put enter a String variable into my String array. I can't think of any way around this. Please help.
Problem is :
for(int i=0;i >n; i++)
{
}
Write This :
for(int i=0;i <n; i++)
{
// your code
}
You are not initialize a String array .
import java.util.*;
class Student
{
private String [] first;
private String [] last;
private String [] HKID;
private String[] SID;
private int []Exam;
private int num;
Scanner kb= new Scanner(System.in);
int n=0;
public Student (){
System.out.println("Please enter number of students:");
n = kb.nextInt();
first = new String[n];
last= new String[n];
HKID=new String[n];
SID=new String [n];
Exam=new int [n];
for(int i=0;i <n; i++)
{
System.out.println("First name:");
first[i]= kb.next();
System.out.println("Last name:");
last[i]=kb.next();
System.out.println("HKID:");
HKID[i]=kb.next();
System.out.println("SID:");
SID[i]=kb.next();
System.out.println("Final exam score:");
Exam[i]= kb.nextInt();
}
System.out.print("Student Detail");
System.out.print("First Name \t Last Name \t HKID \t SID \t Final exam score \n " );
for(int i=0;i<n;i++)
{
System.out.print(first[i]+"\t"+last[i]+"\t"+HKID[i]+"\t"+SID[i]+"\t"+Exam[i]);
System.out.println();
}
}
public static void main (String[] args) {
new Student();
}
}
Firstly initialize all arrays to size 'n' which you are reading outside for loop.
Then,Inside your for loop you can directly mention
for(i=o;i<n;i++){
System.out.println("First name:");
f = kb.next();
first[i] = f;
}
kb.next() returns a String object so u can also directly do first[i]=kb.next();
The main issue with your code here is that you are passing string object to define size of array which is incorrect (i.e here new String[f])
Hope this helps!
All The Best!
First , I don't konw why you create the constructor like this
public Student (String f, String l, String h, String s, int e, int n)
Meanwhile , you override each parameter in it
Second , one way to convert a String parameter into array is
char arr1[]=new char[len1];
arr1=s1.toCharArray()
String[] is an array of String , and char[] is a array of char ,which means a String.