Next Line problems with spacing - java

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;
}
}
}

Related

Need help sorting ArrayList & Calculating averages of test scores

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());
}
}
}

String name is not getting printed

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.

Java - Taking user input to create an unknown number of class objects/arrays/arrayLists

I need to allow the user to input any number of students. They press "C" to end data entry. I was thinking to make a student class (my code does not currently represent that) and 4 objects per student. Each set of 4 objects are the number grades that will be summed up and averaged.
I've already tried using a while loop, making arrayLists, and I've looked into maps. Each set of 4 grades corresponds to a student and must be summed and averaged separately.
package arrayList;
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> studentName = new ArrayList<String>();
ArrayList<Double> studentGrade = new ArrayList<Double>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String student = scanner.nextLine();
if(student.equals("C"))
{
break;
}
else
{
studentName.add(student);
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++) {
Double grade = Double.parseDouble(scanner.nextLine());
studentGrade.add(grade);
}
System.out.println(studentName);
System.out.print(studentGrade);
}
}
}
Problem here really is that I have all the entered numbers in one arrayList and I don't know if I can automatically create a new arrayList each time they enter a new student. Each arrayList would ideally hold just 4 double values.
Well please consider that grades are related to student and limited to always 4.
Therefore I suggest to implement a dynamic list of a class student with enclosed array of grades.
Example:
import java.util.Scanner;
import java.util.ArrayList;
public class TestGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Student> studlist = new ArrayList<Student>();
boolean loop = true;
while (loop) {
System.out.println(" Please Enter Student Name");
String scanedline = scanner.nextLine();
if(scanedline.equals("C"))
{
break;
}
else
{
studlist.add(new Student(scanedline));
}
System.out.println("Please enter Student Grade");
for (int j = 0; j < 4; j++)
{
System.out.print(""+j+">");
Double scannedgrade = Double.parseDouble(scanner.nextLine());
studlist.get(studlist.size() - 1).grade[j]=scannedgrade;
}
System.out.println(studlist.get(studlist.size() - 1).name);
for (int j = 0; j < 4; j++)
System.out.print(studlist.get(studlist.size() - 1).grade[j] + " ");
System.out.println("");
}
}
private static class Student
{
String name;
Double [] grade;
Student (String s)
{
this.name = s;
grade = new Double[4];
}
}
}

Why is the value of the subclass data member not displayed?

I have created 2 java files: XCompanyShortlist.java and StudentDemo.java. The XCompanyShortlist.java contains the main method and all the user input like Student Registration No., Name, Semester, GPA, CGPA, Branch Name, Placement status and Internship status.
The StudentDemo.java has a superclass StudentDemo which initializes Reg. No., Name, Semester, GPA, CGPA using parameterized constructor and it also contains a method display() which displays all there informations.
A class BranchStudent extends StudentDemo class and contains an extra String named BranchName. This class also contains a display() method which calls the display() method in the superclass and also prints the BranchName. Another class StudentPlacement contains variables for InternshipStatus, PlacementStatus, and an array of preferred company list.
Here is the StudentDemo.java file code:
class StudentDemo {
long RegNo;
String fname;
short sem;
float gpa;
float cgpa;
StudentDemo() {
RegNo = 0;
fname = "";
sem = 0;
gpa = (float) 0.0;
cgpa = (float)0.0;
}
StudentDemo(long RegNo, String fname, short sem, float gpa, float cgpa) {
this.RegNo = RegNo;
this.fname = fname;
this.sem = sem;
this.gpa = gpa;
this.cgpa = cgpa;
}
StudentDemo(StudentDemo obj) {
RegNo = obj.RegNo;
fname = obj.fname;
sem = obj.sem;
gpa = obj.gpa;
cgpa = obj.cgpa;
}
void display() {
System.out.println("------------------------------------------");
System.out.println("Registration No. :"+RegNo);
System.out.println("Full Name: "+fname);
System.out.println("Semester: "+sem);
System.out.println("GPA: "+gpa);
System.out.println("CGPA: "+cgpa);
System.out.println("------------------------------------------");
}
}
class BranchStudent extends StudentDemo {
public String BranchName;
BranchStudent(long RegNo,String fname,short sem,float gpa,float cgpa,String BranchName) {
super(RegNo,fname,sem,gpa,cgpa);
this.BranchName = BranchName;
}
BranchStudent() {
super();
BranchName = "CSE";
}
BranchStudent(BranchStudent obj) {
super(obj);
BranchName = obj.BranchName;
}
void display() {
super.display();
System.out.println("Student Branch: "+BranchName);
}
}
class StudentPlacement extends BranchStudent {
String compList[];
int StatusPlacement, StatusIntern;
StudentPlacement() {
super();
StatusPlacement = 0;
StatusIntern = 0;
compList = new String[3];
}
StudentPlacement(StudentPlacement obj) {
super(obj);
StatusPlacement = obj.StatusPlacement;
StatusIntern = obj.StatusIntern;
compList = obj.compList;
}
StudentPlacement(long RegNo, String fname, short sem, float gpa, float cgpa, String BranchName,String compList[], int StatusPlacement,int StatusIntern) {
super(RegNo, fname, sem, gpa, cgpa, BranchName);
this.compList = compList;
this.StatusPlacement = StatusPlacement;
this.StatusIntern = StatusIntern;
}
}
Here is the XCompanyShortlist.java file code:
import java.util.Scanner;
public class XCompanyShortlist {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number Of Students: ");
int n = sc.nextInt();
StudentPlacement obj[] = new StudentPlacement[n];
for(int i = 0; i < n; i++) {
obj[i] = new StudentPlacement();
}
System.out.println("Please Enter The Student Details: ");
for(int i = 0; i < n; i++) {
System.out.print("Please Enter The Reg. No. :");
long RegNo = sc.nextLong();
sc.nextLine();
System.out.print("Please Enter The Full Name: ");
String fname = sc.nextLine();
System.out.print("Please Enter The Semester: ");
short sem = sc.nextShort();
System.out.print("Please Enter The GPA: ");
float gpa = sc.nextFloat();
System.out.print("Please Enter The CGPA: ");
float cgpa = sc.nextFloat();
System.out.print("Please Enter Branch Name:");
String branchName = sc.nextLine();
sc.nextLine();
System.out.println("Please Enter 3 Preferred Choice: ");
String compList[] = new String[3];
for(int x = 0; x < 3; x++) {
compList[x] = sc.nextLine();
}
System.out.print("Please Enter The Status Of Placement(0/1): ");
int statusPlacement = sc.nextInt();
System.out.print("Please Enter Status Of Internship(0/1): ");
int statusIntern = sc.nextInt();
obj[i] = new StudentPlacement(RegNo,fname,sem,gpa,cgpa,branchName,compList,statusPlacement,statusIntern);
System.out.println();
}
for(int i = 0; i < n; i++) {
obj[i].display();
}
sc.close();
}
}
The problem I am facing is that all the student details from the StudentDemo superclass is being dislayed but the subclass BranchStudent is not printing the BranchName. I am unable to find the problem in my code.
OUTPUT:
Please Enter The Number Of Students:
1
Please Enter The Student Details:
Please Enter The Reg. No. :159101046
Please Enter The Full Name: Bitan Basak
Please Enter The Semester: 3
Please Enter The GPA: 8.86
Please Enter The CGPA: 8.64
Please Enter Branch Name:CSE
Please Enter 3 Preferred Choice:
HP
Dell
Microsoft
Please Enter The Status Of Placement(0/1): 0
Please Enter Status Of Internship(0/1): 0
------------------------------------------
Registration No. :159101046
Full Name: Bitan Basak
Semester: 3
GPA: 8.86
CGPA: 8.64
------------------------------------------
Student Branch:
This is the output given by my program. As you can see the Student Branch is not being printed. I am unable to understand why.
From what I can tell the issue has nothing to do with inheritance but rather that you are feeding an empty line to the constructor.
This means something is wrong with the usage of the Scanner.nextLine() method. If I change your code to this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number Of Students: ");
int n = sc.nextInt();
StudentPlacement obj[] = new StudentPlacement[n];
for(int i = 0; i < n; i++) {
obj[i] = new StudentPlacement();
}
System.out.println("Please Enter The Student Details: ");
for(int i = 0; i < n; i++) {
System.out.print("Please Enter The Reg. No. :");
long RegNo = sc.nextLong();
sc.nextLine();
System.out.print("Please Enter The Full Name: ");
String fname = sc.nextLine();
System.out.print("Please Enter The Semester: ");
short sem = sc.nextShort();
System.out.print("Please Enter The GPA: ");
float gpa = sc.nextFloat();
System.out.print("Please Enter The CGPA: ");
float cgpa = sc.nextFloat();
sc.nextLine();
System.out.print("Please Enter Branch Name:");
String branchName = sc.nextLine();
System.out.println("Please Enter 3 Preferred Choice: ");
String compList[] = new String[3];
for(int x = 0; x < 3; x++) {
compList[x] = sc.nextLine();
}
System.out.print("Please Enter The Status Of Placement(0/1): ");
int statusPlacement = sc.nextInt();
System.out.print("Please Enter Status Of Internship(0/1): ");
int statusIntern = sc.nextInt();
obj[i] = new StudentPlacement(RegNo,fname,sem,gpa,cgpa,branchName,compList,statusPlacement,statusIntern);
System.out.println();
}
for(int i = 0; i < n; i++) {
obj[i].display();
}
sc.close();
}
I.e. move the sc.nextLine() before the Branch Name input the scanner picks up the correct value from the console.
Hope that helps.
Greetings
in void display() method you are calling super display() method so the super display() method is calling not that branch display method and add this.branchname

Assigning and returning objects in java

I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information

Categories