Issues with Looping - java

I am very new to Java. So I've created a script to receive input of a score, and then give a mark as output based on this score. My issue is I want the code to repeat to allow for entry of multiple scores, but I can't get it to work.
Edit: I have tried using the methods in the answers but I can't get it right. would it be possible for someone to do implement the loop into my code for me?
Here's my code:
import java.util.Scanner;
public class week4
{
public static void main(String[] args)
{
{
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
}
}

First, let's refactor the main logic into another method called calcGrade():
public void calcGrade() {
String studentname;
int mark = 100; // listing maximum mark
Scanner inText = new Scanner(System.in);
System.out.print("Please enter the name of the student >> ");
studentname = inText.nextLine();
Scanner inNumber = new Scanner(System.in);
System.out.print("Please enter mark for student " + studentname + " out of 100 >> ");
mark = inText.nextInt();
if(mark <50) System.out.print("The grade for " + studentname + " is F " );
else if(mark <65) System.out.print("The grade for " + studentname + " is P " );
else if(mark <75) System.out.print("The grade for " + studentname + " is C " );
else if(mark <85) System.out.print("The grade for " + studentname + " is D " );
else System.out.print("The grade for " + studentname + " is HD2" );
}
If we invoke this method, it will load a new student name & score from System.in, calculate the grade then print it.
Okay, the next part will be the loop.
There are 3 types of loop in Java, for/while/do-while.
You can use "for" when you know exactly what times you want to loop.
E.g. You know there is only 10 students in your class, then you can write such codes:
for (int i = 0; i < 10; i++) {
calcGrade();
}
If you don't know the times, but you know there is an exact condition to end the loop, you can use while or do-while. The difference between while and do-while is while can do the condition check first then do the inner logic, and do-while always do the inner logic for once time then check the condition.
E.g. You want to continue the loop when you acquire a String "YES" from the System.in.
System.out.println("Please input the first student info, YES or NO?");
Scanner inText = new Scanner(System.in);
while ("YES".equals(inText.nextLine()) {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
}
Also, you can use the do-while, if you know there are at least one people in the class.
Scanner inText = new Scanner(System.in);
do {
calcGrade();
System.out.println("Continue input the next student info, YES or NO?");
} while ("YES".equals(inText.nextLine());
Hopes it's clear for you ;)

Easiest wway I can think of is to create a class called student and have variables for name, subjects, scores etc. Have setters and getters if you want or just have a constructor which takes in those inputs. Next have a method like computeGrade(). Creates instances of this student class every time you want some thing.
puclic class Student{
public String mName;
public String mSub1;
.
public int m_scoreSub1;
.
.
public computeScore(int m_score){
* your logic goes here ( the if else one)
}
}
Now just instantiate the class !!!

Related

While loops on Java

Not sure what I am doing wrong here or not understanding and I believe I am thrown off as far as the yes and no answer to my program I get the success the first time but when it calculates the answer it runs over itself and loops infinite
import java.util.Scanner;
public class patrickmahoney_assignment3 {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in); //Setup Scanner
System.out.println("This program will calculate a students grade for the marking period.");
System.out.println(" ");
System.out.println("Do you want to calculate a student's overall grade? yes/no ");
String response = scan1.nextLine();
do {
System.out.println("Great! Let's get started.");
System.out.println(" ");
System.out.println("Please enter student's name: ");
// user inputs students name
String student = scan1.nextLine();
System.out.println("Please enter grades separated by a space... A1 A2 Ex P: ");
//Assignment 1 input by user
int A1 = scan1.nextInt();
//Assignment 2 input by user
int A2 = scan1.nextInt();
//Exercise input by user
int Ex = scan1.nextInt();
//Participation input by user
int P = scan1.nextInt();
//Print out user entered information and overall grade calculation
System.out.println("Student: " + student);
System.out.println("Grades: " + "\nA1= " + A1 + " " + "\nA2= " + A2 + " " + "\nEx= " + Ex + " " + "\nP= " + P);
System.out.println("Overall grade: " + (A1 * 0.25 + A2 * 0.25 + Ex * 0.4 + P * 0.1));
} while ("Yes".equalsIgnoreCase(response));
do {
System.out.println("Thanks for using the grade calculation program. ");
} while ("No".equalsIgnoreCase(response));
scan1.close();
}
}
If you want to exit the loop then you need to change the value of response which is used in the while condition while ("Yes".equalsIgnoreCase(response)), for example System.out.println("Type exit to finish or yes to continue"); followed by response = scan1.nextLine();
For example:
System.out.println("This program will calculate a students grade for the marking period.");
System.out.println(" ");
//Set this to yes so the code enters the while loop the first time
String response = "yes";
do {
//Get the input to see if the user wants to continue
System.out.println("Do you want to calculate a student's overall grade? yes/no ");
response = scan1.nextLine();
//Check if the response was "yes"
if(response.equalsIgnoreCase("yes")){
//Your code here .......
//Removed for clarity
}
//If the response was anything other than "yes" then it will exit the while loop on the next cycle
} while ("Yes".equalsIgnoreCase(response));
System.out.println("Finished, the while loop was exited");

How to add more variables inside of loops java

Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}

for loop class assignment gone wrong

I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}

How to use loops and average in Java [duplicate]

This question already has answers here:
How to get average from given values
(3 answers)
Closed 9 years ago.
My program is supposed to find the average of female, male, and total average GPA of students. And also total female, male, and total students. First it asks if the student is male or female. If you choose male it does the loop, but after it ends. I want my program to go straight into the next choice. Example if you choose male the you'll input female and visa versa.
import java.util.Scanner;
public class practice {
public static void main(String [] args) {
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
System.out.println("Enter GPA");
GPA = keyboard.nextDouble();
if (student.equals("M")) {
while (GPA >=0) {
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
}
if (student.equals("F")) {
while (GPA >=0) {
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
}
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
allAverage = mTotal + fTotal;
totalStudents = maleCount + femaleCount;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total MALE Average GPA: " + mAverage);
System.out.println("Total average: " + allAverage);
}
}
How to use loops and average in Java?
Well, pretty much as in the code in your question, I'd say. Just add a loop around the part that needs a loop, and figure out how you are going to end the looping.
The other problems that leap out at me are:
You seem to be accepting the input in a strange order.
You are calculating allAverage incorrectly. Just look at the code again. The problem should be obvious.
Actually, one of the difficulties with answering this Question is that it is not at all clear how the program as written is supposed to behave. And we can't infer that from what you've shown us. 'Cos what you've written obviously doesn't work ... from a usability perspective.
If you don't understand and can't explain the requirements properly, there is not much chance that you will be able to implement them correctly.
Fixed my code sorry for it being unclear.
import java.util.Scanner;
public class practice
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents, count = 0;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
do{
System.out.println("Enter GPA " + student);
GPA = keyboard.nextDouble();
if (student.equals("M"))
{
while (GPA >=0)
{
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
student = "F";
}
else if (student.equals("F"))
{
while (GPA >=0)
{
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
student = "M";
}
}
while (++count < 2);
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
totalStudents = maleCount + femaleCount;
allAverage = (mTotal + fTotal)/totalStudents;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total average: " + allAverage);
}

Java: coding that uses a variable to specify array length?

I am working on a student scores application that accepts the last name, first name and score for one or more students and stores the results in an array. Then it prints the students and their scores in alphabetical order by last name. We do not know how many students there are, but there will be fewer than 100.
We have to display the class average at the end of the student information and display a message after each student whose grade is more than 10 points below the class average.
My first issue is that I have created a do/while loop to ask if the user would like to enter another but it will not work!?!?
Second, I can not figure out how to display the "10 points below" message on individual students.
public class Student implements Comparable
{
String firstName;
String lastName;
int score;
//stores last name, first name and score for each student
public Student(String lastName,String firstName,int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.score = score;
}
//implement the comparable interface so students can be sorted by name
public int compareTo(Object o)
{
Student otherStudent = (Student)o;
if(otherStudent.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(otherStudent.firstName);
}
else
{
return lastName.compareToIgnoreCase(otherStudent.lastName);
}
}
public String toString()
{
return lastName + ", " + firstName + ": " + score;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class StudentApp
{
static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
Student [] studentArray;
String lastName;
String firstName;
int score = 0;
double average = 0;
System.out.println("Welcome to the Student Scores Application.");
System.out.println();
do{
//code that uses variable to specify the array length
int nStudent = 100; //array size not set unit run time
studentArray = new Student[nStudent];
for (int i=0; i<nStudent; i++)
{
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
studentArray[i] = new Student(lastName, firstName, score);
double sum = 0.0;
sum += score;
average = sum/nStudent;
}
}while (getAnotherStudent());
Arrays.sort(studentArray);
System.out.println();
for (Student aStudent: studentArray)
{
System.out.println(aStudent);
if (score<= (average-10))
{
System.out.println ("Score 10 points under average");
}
}
System.out.println("Student Average:" +average);
}
public static boolean getAnotherStudent()
{
System.out.print("Another student? (y/n): " );
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
}
}
There are a few problems here:
Every time through the do...while, you reinstantiate studentArray and sum. This means that all of your previously iterated over data is nuked when getAnotherStudent() is true - you want to instantiate the array and sum only once.
You don't stop if you have more than 100 students. You need an ending condition around nStudent as well in your loop.
You should make a few adjustments to getAnotherStudent() so that you can block on data, and wait when valid data is input - by using a loop:
public static boolean getAnotherStudent() {
Scanner sc = new Scanner(System.in);
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) {
String choice = sc.next();
// blocks here - ignores all input that isn't "y" or "n"
while(!((choice.equalsIgnoreCase("Y") || choice.equalsIgnoreCase("N")))) {
if (choice.equalsIgnoreCase("Y")) {
return true;
}
System.out.print("Another student? (y/n): " );
choice = sc.next();
}
}
return false; // obligatory
Your code is close there are just a couple of problems. The reason why your do while loop is not working is that you have a for loop inside of it. This means that you will ask for 100 students before you ask if they want to add another one. Your sum is being created inside this loop so it will be reset each time.
Finally you do not know how many Students will be added but your code assumes there will be 100 Students. This means you cannot use the for each loop to go through the array as some could be null. Just use a regular for loop going up to the last index of a student you added. Here are the changes:
Student[] student = new Student[nStudent];
int studentCount = 0; //declear the counter outside the loop
double sum = 0.0; //declear the sum outside the loop
do {
System.out.println();
lastName = Validator.getRequiredString(sc,
"Student " + (i+1) + " last name: ");
firstName = Validator.getRequiredString(sc,
"Student " + " first name: ");
score = Validator.getInt(sc,
"Student " + " score: ",
-1, 101);
student[studentCount] = new Student(lastName, firstName, score);
sum += score; //increase the sum
studentCount++; //increment the counter
} while (studentCount < nStudent && getAnotherStudent()); //stop if the user says 'n' or we hit the maximum ammount
average = sum / studentCount; //work out the average outside the loop
System.out.println();
for (int i= 0; i< studentCount; i++ ) {
System.out.println(aStudent);
if (score <= (average - 10)) {
System.out.println("Score 10 points under average");
}
}
System.out.println("Student Average:" + average);
}
Your getAnotherStudent() method should read:
System.out.print("Another student? (y/n): " );
if (sc.hasNext()) { // blocks until user entered something
String choice = sc.next();
if (choice.equalsIgnoreCase("Y"))
return true;
else
return false;
} else {
// won't come here
return false;
}

Categories