This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
I have added a for loop in size of 3 it should scan for 3 times but it is scanning for 4 time.for size of 4 its scanning for 6 times help me out.
public class Control {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Student> studs = new ArrayList<Student>();
for (int i = 1;i < 3;i++) { //Here the for loop
System.out.println("Enter age and name :");
Student stu1 = new Student(sc.nextInt(),sc.nextLine());
System.out.println("Enter age and name :");
Student stu2 = new Student(sc.nextInt(),sc.nextLine());
studs.add(stu1);
studs.add(stu2);
Collections.sort(studs,new StudAge());
}
for(Student stud : studs) {
System.out.println(stud);
}
}
}
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Student> studs = new ArrayList<Student>();
for (int i = 1;i < 3;i++) { //Here the for loop
System.out.println("Enter age and name :");
int age = sc.nextInt();
//nextInt does not account for the enter that you press when you submit the int so you have to catch the unused enter keystroke
sc.nextLine();
String name = sc.nextLine();
Student stu1 = new Student(age, name);
age = sc.nextInt();
sc.nextLine();
name = sc.nextLine();
System.out.println("Enter age and name :");
Student stu2 = new Student(age, name);
studs.add(stu1);
studs.add(stu2);
Collections.sort(studs,new StudAge());
}
for(Student stud : studs) {
System.out.println(stud);
}
}
}
nextInt does not account for the enter that you press when you submit the int so you have to catch the unused enter keystroke
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am learning about Arrays and had gotten this assignment. Whenever I run the code, the value which is supposed to go into String array goes into Int. It skips over the name[i]=sc.nextLine(); completely.
Any Help will be appreciated.
import java.util.*;
public class Marks_Remarks {
public static void main(String []Args){
Scanner sc= new Scanner (System.in);
System.out.println("Enter how many students");
int n= sc.nextInt();
String name[]= new String[n];
int roll[]= new int[n];
int sub1[]= new int[n];
int sub2[]= new int[n];
int sub3[]= new int[n];
for (int i=0;i<n;i++){
System.out.println("Enter Name");
name[i]= sc.nextLine();
System.out.println("Enter Roll No.");
roll[i]= sc.nextInt();
System.out.println("Enter marks in Three Subjects");
sub1[i]= sc.nextInt();
sub2[i]= sc.nextInt();
sub3[i]= sc.nextInt();
}
int avg; String remark;
for (int k=0;k<n;k++){
avg= (sub1[k]+ sub2[k]+ sub3[k])/3;
if (avg>=85)
remark= "Excellent";
else if(avg>=75 && avg<=84)
remark= "Distinction";
else if(avg>=60 && avg<=74)
remark= "First Class";
else if(avg>=40 && avg<=59)
remark="Pass";
else
remark="Poor";
System.out.println("Name: "+ name[k]+ "\tRoll No.: "+ roll[k]+ " \tAverage: "+ avg+ " \tRemark: " + remark);
avg=0;
}
}
}
Use name[i]=sc.next(); instead of : name[i]=sc.nextLine();
It may help you.
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());
}
}
}
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];
}
}
}
I am currently working on a program that takes a user input of the number of students in a class, then, (in a while loop), takes a user input of a student number and their average grade, then, after calculation, prints the highest mark, lowest mark, and average mark of the class.
This is what I have done so far:
import java.util.Scanner;
public class ClassMarks {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students in class: ");
int students = input.nextInt();
int x = students;
while (x > 0) {
System.out.println("Enter student number: ");
double studentNumber = input.nextDouble();
System.out.println("Enter student grade: ");
double studentGrade = input.nextDouble();
x = x - 1;
}
}
}
I am looking for a way to get the program to create a new variable for me that stores each new user input student grade inside the while loop.
ex) studentGrade1, studentGrade2, studentGrade3 ...
Before the while loop, create variables highest/lowest grades
double highestGrade = Double.MIN_VALUE, lowestGrade = Double.MAX_VALUE;
double gradeSum = 0;
Then as you loop through the values, adjust the variables appropriately, e.g.
if (studentGrade > highestGrade)
highestGrade = studentGrade;
if (studentGrade < lowestGrade)
lowestGrade = studentGrade;
gradeSum += studentGrade;
And then after the loop finishes, get the average like this
double averageGrade = gradeSum / students;
How about using a List.
List<Student> students = new ArrayList<>()
and in while loop
create a student update its fields then add it to the list
Student myNewStudent = new Student();
// update fields
students.add(myNewStudent);
To iterate the list you can use a for loop.
for (Student s : students) {
// Get student info
}
Adapting this into your code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ClassMarks {
// Create an inner class Student
public static class Student {
public double studentNumber;
public double studentGrade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students in class: ");
int students = input.nextInt();
int x = students;
// Create a list to hold your students
List<Student> studentsList = new ArrayList<>();
while (x > 0) {
Student myNewStudent = new Student();
System.out.println("Enter student number: ");
myNewStudent.studentNumber = input.nextDouble();
System.out.println("Enter student grade: ");
myNewStudent.studentGrade = input.nextDouble();
// update fields
studentsList.add(myNewStudent);
x = x - 1;
}
// Loop your student List
for (Student s : studentsList) {
// Get student info
System.out.println("Student number is: "+s.studentNumber+" grade is : "+s.studentGrade);
}
}
}
When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}