Getting a very strange error. When I add
{
while {
System.out.println( "Enter homework grades, Enter -1 when done" );
homeworkGrades += input.nextInt();
}
}
I get about 19 errors. If i remove it, then no errors. I've spent quite a few minutes changing it up, but I can't seem to get it to work. The program simply asks if you want to Average grades or Quit, then asks for your name. Now I want it to allow a user to enter in the Homework grades to average, then it will ask for quiz grades to average, then lastly test grades. Then it will take those 3 averages and average those.
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int homeworkGrades;
int quizGrades;
int testGrades;
int choice;
int total;
double average;
String name;
total = 0;
System.out.println("Enter 1 or 2: \n 1 - Average grades \n 2 - Quit");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Enter the students name");
name = input.next();
System.out.println("Grades will be entered in this order: \n 1) Homework Grades \n 2) Quiz Grades \n 3) Test Grades ");
//here
{
while {
System.out.println( "Enter homework grades, Enter -1 when done" );
homeworkGrades += input.nextInt();
}
}
}
if (choice == 2) {
System.out.println("Exiting program");
}
else {
System.out.println("Invalid response, exiting program.");
}
}
}
You need to give the while loop a condition, such as:
while (homeworkGrades != something) {
}
You need to tell your while loop when to exit. Without this information, it can not know when to stop. It is also not correct coding to skip the condition.
Based on what you have written, this will give you what you are most likely looking for:
int grade = 0;
while (grade >= 0)
{
homeworkGrades += grade;
System.out.println( "Enter homework grades, Enter -1 when done" );
int grade = input.nextInt();
}
I hope i have helped you to understand this more clearly. :)
Related
I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.
I am really struggling on getting my java code to work. I have coded a program which determines what grade each score will get once entered in by the user and also finds the largest and smallest score. The program successfully figures out which score belongs in which grade but once I implement the piece of code which tries to find the largest number out of the scores it doesn't seem to work and I'm not sure what it is!
here is the code...
import java.util.Scanner;
public class Grade
{
public static void main(String[] args)
{
int Agrade=0; //different variables used throughout the code
int Bgrade=0;
int Cgrade=0;
int Dgrade=0;
int Fgrade=0;
int count=0;
Scanner in = new Scanner(System.in); //name of Scanner
System.out.println("Please enter the exam grades one after the other ");
System.out.println("Please enter a negative number at the end of the grade list to control the flow and then press enter :");
int score = in.nextInt(); //stores numbers inputted
System.out.println("Please enter the grades again for the largest number: ");
double largest = in.nextDouble();
while (in.hasNextDouble()){
double input = in.nextDouble();
if (input > largest) {
largest = input;
}
}
while(score>0) //start while loop
{
count++;
if(score>=70 && score<=100)
Agrade++;
else if(score>=60 && score<=69)
Bgrade++;
else if(score>=50 && score<=59)
Cgrade++;
else if(score>=40 && score<=49)
Dgrade++;
else if(score>=0 && score<=39)
Fgrade++;
score = in.nextInt();
} //end while
System.out.println("Total number of grades :"+ count);
System.out.println("The largest number :"+ largest);
System.out.println("The number of As :"+ Agrade);
System.out.println("The number of Bs :"+ Bgrade);
System.out.println("The number of Cs :"+ Cgrade);
System.out.println("The number of Ds :"+ Dgrade);
System.out.println("The number of Fs :"+ Fgrade);
} // end main
} // end class
Thank you!
That's probably an exercise so will give just the idea.
Your while loop seems to be fine, just declare two variables before it.
one for holding the max grade initialized with lowest number and another for min grade with highest number.
score = in.nextInt(); do
if ( score > highest ) { highest = score;}
if ( score < lowest ) { lowest = score }
good luck.
The problem is likely that you are declaring the variable input every time the while loop runs. Instead, declare the variable like this:
double input;
and do it before the while loop. Then in the while loop replace that line with:
input = in.nextDouble();
If this isn't the problem, it might be how you've laid out the code. The second while loop, which begins with while (score>0) should be where you have the line int score = in.nextInt() Putting this after the first while loop means that it's executed after that while loop.
As a side note, common variables like Agrade should be written in camelCase, in which the first letter is lowercase and the letter of the next word is uppercase. This would make your variables
int aGrade = 0;
int bGrade = 0;
and so on. This is just proper form and shouldn't effect your program. Also, you should probably declare score and input at the top of your program since you use them in loops. This is also good form and organization. It would look like this:
int score;
double input;
Check comments on code to understanding.
MainClass:
import java.util.Scanner;
public class Grade
{
public static void main ( String [ ] args )
{
/**
* This gradesCount represent the A,B,C,D,E,F counts
*/
int[] gradesCount = {0,0,0,0,0,0};
double inputScore = 0;
double bestScore = 0;
int total = 0;
#SuppressWarnings ( "resource" )
Scanner in = new Scanner(System.in);
System.out.println ( "If you want to end, enter a negative number" );
System.out.print("Enter score: ");
do
{
inputScore = in.nextDouble ( );
//validation for the first iteration
if(inputScore < 0 || inputScore > 100) break;
System.out.print("Enter score: ");
//Add to corresponding grade count
if(inputScore>=70 && inputScore<=100) gradesCount[0]++;
if(inputScore>=60 && inputScore<=69) gradesCount[1]++;
if(inputScore>=50 && inputScore<=59) gradesCount[2]++;
if(inputScore>=40 && inputScore<=49) gradesCount[3]++;
if(inputScore>=0 && inputScore<=39) gradesCount[4]++;
//Add one to total
total++;
//check best score
if(inputScore > bestScore) bestScore = inputScore;
}//This pattern check if its number between 0-100
while ( in.hasNext ( "[0-9][0-9]?|100" ) );
System.out.println ( "Negative number or not valid input. Exited." );
System.out.println("Total number of grades :"+ total);
System.out.println("The best score :"+ bestScore);
System.out.println("The number of As :"+ gradesCount[0]);
System.out.println("The number of Bs :"+ gradesCount[1]);
System.out.println("The number of Cs :"+ gradesCount[2]);
System.out.println("The number of Ds :"+ gradesCount[3]);
System.out.println("The number of Fs :"+ gradesCount[4]);
}
}
Input/Output:
If you want to end, enter a negative number
Enter score: 5
Enter score: 10
Enter score: 15
Enter score: 20
Enter score: 33
Enter score: 99
Enter score: 100
Enter score: 44
Enter score: -3
Negative number or not valid input. Exited.
Total number of grades :8
The best score :100.0
The number of As :2
The number of Bs :0
The number of Cs :0
The number of Ds :1
The number of Fs :5
Documentation:
Scanner
The while and do-while statements (used for iteration)
Pattern (used in do-while)
So I've written a test class to test a program that will allow me to take in number of courses, letter grades, and course credits and then calculate total weighted points, total credits, and GPA within a loop designed for 3 courses max.
However, I need to validate the number of courses and prove that it will run after both an invalid and valid input have been entered.
I've gotten it so that will prompt the user for a valid number of courses after an invalid response, but once the valid response is input the program just stops instead of running like it is supposed to. Can anyone tell me why?
Here's my code:
import java.util.*;
import java.lang.*;
public class ComputeGpa
{
public static void main(String [] args)
{
Gpa grades1 = new Gpa();
Scanner in = new Scanner (System.in);
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
if(courses > 0)
{
int i = 0;
while(i < 3)
{
System.out.println("Please enter a letter grade.");
String letter = in.next();
char result = letter.charAt(0);
System.out.println("How many credits was this class worth?");
int credits = in.nextInt();
grades1.addToTotals(result, credits);
i++;
}
System.out.printf("GPA: %.2f", grades1.calcGpa());
}
else
{
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
}
}
The output for that is as follows:
Enter number of courses:
-2
Number of courses must be greater than 0. Please enter a valid number of courses.
3
And then the program stops running. Where Am I going wrong? I thought the in.next() on the letter String would fix this problem but apparently I was wrong. Any ideas?
Your flow is currently if/else.
int foo = ...;
if(foo > 0) {
//your grade stuff
}
else {
//ask for reinput
}
What ends up happening is you catch the problem input once, but never give your flow the opportunity to check it again.
Instead, use a while loop over an if/else layout, to force re-entry until you get the exact information you want, then continue.
System.out.println("Enter number of courses: ");
int courses = in.nextInt();
while(courses < 0) {
System.out.println("Number of courses must be greater than 0. Please enter a valid number of courses.");
courses = in.nextInt();
}
int i = 0;
//...
I am fairly new to programming Java. I want to make a lotto program. Here is the code:
package me.nutella;
import java.util.Scanner;
public class Lotto {
#SuppressWarnings("resource")
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A Number Between 1-20!");
int choice = scanner.nextInt();
if (choice > 20)
System.out.print("Please Only Pick Numbers Between 1-20!");
int b = (int) (Math.random() * 20) +1;
if (choice == b)
System.out.print("You Win!");
else
System.out.print("You Lost! The correct answer was " + b);
}
catch(Exception E) {
System.out.print("Your Answer Must Be Numeric!");
}
}
}
Now, this part if what I am mainly concerned about:
if (choice > 20)
System.out.print("Please Only Pick Numbers Between 1-20!");
I want to make it so if someone puts the number over 20, it will print that message. Now this part does work, but when I put the number over 20, it still plays the lotto game. I want to make it so if they put their number higher than 20, it will not play the game and enter that message.
How can this be done?
Can be most elegantly done using a do {...} while(); loop. At the beginning, the user must always enter a number, so the loop MUST execute at least once. This is where a do {...} while(); loop comes in handy. You can display your message at the beginning of the loop, then read in the users input. If it is in an acceptable range, the loop never re-executes, and the code moves on. But, if it is not acceptable, we re-execute the loop until we get an acceptable value.
Below is how I would approach this problem:
Scanner scanner = new Scanner(System.in);
int choice = 0;
do {
System.out.print("Please Pick A Number Between 1-20!");
choice = scanner.nextInt();
} while(choice > 20 || choice < 1);
It is also worth noting that your message states that "Number between 1-20", but your code only checks that choice < 20, so if a user enter anything LESS THAN 20, it would be accepted. This includes 0, negatives, and of course the valid number range. I added the || choice < 1 check in my example.
What you need is a loop to keep getting inputs if input is not valid:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter A Number Between 1-20!");
int choice = scanner.nextInt();
boolean validInput=false;
while(!validInput) {
int choice = scanner.nextInt();
if (choice > 20) {
System.out.print("Please Only Pick Numbers Between 1-20!");
} else {
validInput=true;
}
}
int b = (int) (Math.random() * 20) +1;
if (choice == b)
System.out.print("You Win!");
else
System.out.print("You Lost! The correct answer was " + b);
I was wondering how you can the scanner can pick up all the different numbers on the same line. my assignment has requires us to compute grade averages and he wants it to be like:
Enter the number of grades: 5
Enter 5 grades: 95.6 98.25 89.5 90.75 91.56
The average of the grades is 93.13
I think for the scanner to get those number it requires an array? but we haven't learned those. Any help would be awesome! So far I have:
// number of grades input
do {
System.out.println("Enter number of grades");
// read user input and assign it to variable
if (input.hasNextInt()) {
numGrade = input.nextInt();
// if user enters a negative grade will loop again
if (numGrade <= 0) {
System.out.println("Your number of grades needs to positive! Try again");
continue;
// if grade number > 0 set loop to false and continue
} else {
cont = false;
}
// if user does not enter a number will loop again
} else {
System.out.println("You did not enter a number! Try again");
// get the next input
input.next();
continue;
}
// only not loop when boolean is false
} while (cont);
// user input of grades
do {
// prompt user to enter the grades
System.out.println("Enter the " + numGrade + " grades");
// assign to input
if (input.hasNextDouble()) {
grades = input.nextDouble();
// check if a grade is a negative number
if (grades <= 0) {
// report error to user and loop
System.out.println("Your grades needs to positive! Try again");
continue;
// if user enter acceptable grades then break loop
} else {
cont2 = false;
}
// check if user entered a number
} else {
// if user did not enter number report error
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
// only not loop when boolean2 is false
} while (cont2);
// average calculation
average = grades / numGrade;
System.out.println(average);
}
I would suggest this
// separates the line you send by spaces if you send the next line
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this
// {"95.6","98.25", "89.5","90.75", "91.56"}
String []grades = input.nextLine().split(' ');
double total=0;
for(int i=0;i<grades.length;i++){
//parse each value to double and adds it to total
total+=Double.parseDouble(grades[i]);
}
double average= total/grades.length;
I think in your assignment the separate spaces means that you should have each number stored in a specific location or variable.
For example:
Enter three number : 1 2 3
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
now Scanner will read by nextInt() method. if it read space then will finished saving value in that variable.
Another Example that read array elements:
Enter three number: 1 2 3
int[] myArray = new int[3];
for(int i = 0; i < myArray.length; i++){
myArray[i] = input.nextInt();
}
Note that the loop will run 3 times as the length of the array.
Also note in the code that input reference for Scanner class but I didn't declare it.