How to use loops and average in Java [duplicate] - java

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

Related

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
*/
}

Enter name and grades from user input to get average grade

I am working on a code where you have a students name and his grades and it prints his name total scores and his average scores. I want to make it more functional in allowing the user to input there name and scores and get all that info back. I may try to further this into a class average where it allows to input multiple individual names, scores, and average, print each one separately then showing the class average. This is a second thought though, as I need to have user input of grades and names first.
This is what I have so far.
I have a separate class to make some things simpler.
public class Student {
private String name;
private int numOfQuizzes;
private int totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
totalScore = totalScore + score;
numOfQuizzes++;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then i have the main method:
public static void main(String[] args) {
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Student student = new Student(name);
student.addQuiz(96);
student.addQuiz(94);
student.addQuiz(93);
student.addQuiz(92);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
This is what it prints out currently:
What is your name? Tom
Students Name: Tom
Total Quiz Scores: 375
Average Quiz Score: 93.75
UPDATE:
This is what i have done so far. i added a loop and trying to use my student class but it doesn't seem to work with the array.
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
Since you are only learning the language just yet, I'll give you a few suggestions to send you on your way. You might want to use a while-loop to consistently ask the user for a new grade until they've given you an empty line or something. You can reuse your scanner to read the new grades and they can be converted to integers using Integer.parseInt. Hopefully this'll allow you to write your code further, it's already looking great :).
EDIT
There are several points which can be improved upon in your edited code. The following shows some of them (using import java.io.Console;):
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());

Issues with Looping

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 !!!

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

My scanner skips over my next double and next integer? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
Whenever I'm running my scanner it skips over the height(double) loop after weight. It also skips over the level(int) loop after age.
Here's my scanner class.
import java.util.Scanner;
public class HowHealthy
{
public static void main(String[] args)
{
String aGender = "";
//New healthy objec tis created
Healthy person = new Healthy();
//Scanner object is created
Scanner in = new Scanner(System.in);
String name = "";
while(!person.setName(name))
{
System.out.print("Person's name: ");
name = in.nextLine();
if(!person.setName(name))
{
System.out.println("Invalid name - must be at least one character!");
}
}
char gender = '\0';
while(!person.setGender(gender))
{
System.out.print(name + ", are you male of female (M/F): ");
gender = in.nextLine().toUpperCase().charAt(0);
if(!person.setGender(gender))
{
System.out.println("Invalid gender - must be M or F (upper or lower case)":
}
}
double weight = 0;
while(!person.setWeight(weight))
{
System.out.print(name + "'s weight (pounds): ");
weight = in.nextDouble();
in.nextLine();
if(!person.setWeight(weight))
{
System.out.println("Invalid weight - must be at least 100 pounds!");
}
}
double height = 0;
while(!person.setHeight(height))
{
System.out.print(name + "'s height (inches): ");
height = in.nextDouble();
if(!person.setHeight(height))
{
System.out.println("Invalid height - must be 60..84, inclusively!");
}
}
int age = 0;
while(!person.setAge(age))
{
System.out.print(name + "'s age (years): ");
age = in.nextInt();
in.nextLine();
if(!person.setAge(age))
{
System.out.println("Invalid age - must be at least 18!");
}
}
System.out.println();
System.out.println("Activity Level: Use these categories:");
System.out.println("\t1 - Sedentary (little or no exercise, desk job)");
System.out.println("\t2 - Lightly active (little exercise / sports 3-5 days/wk");
System.out.println("\t3 - Moderately active(moderate exercise / sports 3-5
System.out.println("\t4 - Very active (hard exercise / sports 6 -7 day/wk)");
System.out.println("\t5 - Extra active (hard daily exercise / sports \n\t physica2X)
int level = 0;
while(!person.setLevel(level))
{
System.out.print("How active are you? ");
level = in.nextInt();
if(!person.setLevel(level))
{
System.out.println("Invalid acitvity level - must be 1..5, inclusively!");
}
}
System.out.println();
//Creates a new Healthy object and prints values based on user's input
System.out.println(person.getName()+ "'s information");
System.out.printf("Weight: %.1f %s \n", person.getWeight(), "pounds");
System.out.printf("Height: %.1f %s \n", person.getHeight(), "inches");
System.out.println("Age: " + person.getAge() + " years");
if (gender == 'M')
{
aGender = "male";
}
else
{
aGender = "female";
}
System.out.println("These are for a " + aGender);
System.out.println();
//Calculates the person's BMR, BMI and TDEE based on user input
System.out.printf("BMR is %.2f \n", person.calcBMR());
System.out.printf("BMI is %.2f \n", person.calcBMI());
System.out.printf("TDEE is %.2f \n", person.calcTDEE());
//Determines person's weight status based on BMI calculated
double BMI = person.calcBMI();
//Displays person's weight status
System.out.println("Your BMI classifies you as " + person.calcWeightStatus());
}
}
Here is my scanner class.
In both cases, you're missing in.nextLine() after you do in.nextInt(). If all of the other lines of code are working using things like in.nextDouble() followed by in.nextLine() my guess is that's what's missing.
Since it is skipping over the loops completely, there is something wrong with your methods for setHeight() and setLevel().
while(!person.setHeight(height))
If it is skipping this loop, it must mean that setHeight(height) is returning true when it should be returning false, or you need to get rid of the '!'

Categories