How can I exit java for-loop if user enters 999? - java

I need to write a program that allows a student to enter up to 10 quiz scores, computes the average score, and then displays the letter grade based on the average. However, if the user enters 999 during the input of quiz scores, the program will terminate. This is the code block I wanted to insert a break statement into but I'm struggling to correctly incorporate grade[i] = 999 into my code without getting an error message. I think the issue may be that the 999 is an integer array value and is unrelated to the int i counter in the for loop.
for (i = 0; i < 10; i++) {
//prompts user to enter grade + displays counter value
System.out.print("Enter grade " + (i + 1) + " or enter 999 to quit: ");
//allows user input to be stored in variable grade
grade[i] = scanner.nextInt();
//adds new grade input to total grade to update variable gradeTotal
gradeTotal = gradeTotal + grade[i];

Assign the inputted value to a temporary variable, and then if it is 999 break the loop, else assign it the the array.
for (i = 0; i < 10; i++) {
System.out.print("Enter grade " + (i + 1) + " or enter 999 to quit: ");
int temp = scanner.nextInt();
if (temp == 999) {
break;
}
grade[i] = temp;
...

Related

Java averaging calculator with defined number of entries

I've seen several average calculators but none with this specific function.
Basically, I want it to ask "How many numbers would you like to average?" then "Enter your number" and continue to prompt "Enter your number" after each entry until the "How many numbers..." quantity is fulfilled. I know it's a count-loop (sorry if my jargon is off...I'm only in my second semester of computer programming) but I don't know how to set it up. Thanks in advance for your answers. Here's what I have so far:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Test Average Calculator!");
System.out.println(); // print a blank line
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal;
int scoreCount;
int testScore;
Scanner sc = new Scanner(System.in);
// perform calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the number of grades to be averaged from the user
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.print("Would you like to average more grades? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Your approach is near about right except some mistakes. You want to take input until 'n' is pressed and then the average would be shown. That means the average calculation must be done outside the loop, when taking input ends.
If you want to take input with a predefined number from input instead of 'y'/'n' approach, you can reuse your while loop:
int numOfInput = sc.nextInt(); // how many number will be entered
while(numOfInput > 0) {
// take every input and add to total
--numOfInput;
}
// average calculation
Also, a little logical mistake in input validation check.
if (testScore <= 100) // for less or equal 100
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100) // for greater or equal 100
System.out.println("Invalid entry, not counted");
Both condition checks whether the number is equal to 100, which is not expected. If you allow only number less than 100, then you could write:
if (testScore < 100) {
scoreTotal += testScore;
}
else {
System.out.println("Invalid entry, not counted");
}
So you want to average scoreCount items, or keep averaging until the user has input "n" ?
If it's the first case (As you've described in your question) and you want to average for scoreCount times, you need to change the condition on your while loop.
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
scoreTotal = 0;
for(int i=0; i<scoreCount; i++){
scoreTotal += sc.nextInt();
System.out.print("Okay please enter next...");
}
System.out.print("Average is " + scoreTotal/scoreCount);
If you want to do it with a while, just keep an index, int index=0;, increment the index on each iteration and check if you've exceeded the index.
while (index < scoreCount)
scoreTotal += sc.nextInt();
index++;
System.out.print("Average is " + scoreTotal/scoreCount);
That is what you need:
for( int i = 0; i < scoreCount; i++){
System.out.print("Enter score: ");
testScore = sc.nextInt();
}
The for loop creates integer i to hold its looping index
int i;
And each loop asks is i bigger than scoreCount and if not loop again.
i < scoreCount;
And after each loop it adds one to i.
i++

how to display if the number is half-prime when the count reaches 3

This is the question that is asked..
Write a java program that asks the user to enter a list of numbers between 1 and 100. The user needs to enter a 0 in order to end the list of input data. The program displays if each number is half-prime or not.
N is half-prime where the count of all divisors is equal three. For example 25 is half-prime, the divisors of 25 are 1, 5 and 25.
Here is my progress....
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 1 and 100: (0 to exit): ");
int num = input.nextInt();
int count =0;
while(num!=0 ){
if(count<=3){
if (num % 2 == 1 ) {
count++;
System.out.println(num + " is half-prime ");
}
else {
System.out.println(num + " is not half-prime ");
}
}
System.out.print("Enter a number between 1 and 100: (0 to exit): ");
num = input.nextInt();
}
I think I've written the count part wrong ! Can someone help me !!

Scanned input inside a do-while loop doesn't reset properly on the next iteration

My program is meant to add up all the even integers between 2 and an input number which is between 20 and 60. The logic for that is correct and will work, but it's supposed to be able to run again if the user wishes, and when it runs again, the input only changes if you input a new integer higher than the previous iteration. If you enter one lower, it just uses the same integer input as before. Here is the code:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number
for no): ");
restart = scan.nextInt();
} while (restart == 1);
}
}
So for example, if I enter 20 as the input, the program outputs:
Sum of even numbers between 2 and 20 is: 110
Enter a new value? (1 for yes, any other number for no):
and then I enter 30 (same run of the program):
Sum of even numbers between 2 and 30 is: 240
Enter a new value? (1 for yes, any other number for no):
and then I try to enter 20 again:
Sum of even numbers between 2 and 20 is: 240
Enter a new value? (1 for yes, any other number for no):
(Should clearly be 110, not 240)
My initial thought was that it wasn't actually scanning for a new input on the second iteration, but because it will work if I keep giving it inputs of greater value I know that is not true.
Use this code inside main()
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
i = 2;
sum = 0;
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number for no): ");
restart = scan.nextInt();
} while (restart == 1);

Run loop an extra time if one of the inputs is bad

I have a for-loop which asks for scores between 0 and 10. It asks a certain amount depending on the number of judges.
Here's the code:
System.out.println("Number of judges: ");
int numOfJudges = IO.readInt();
int sum = 0;
for (int i=0; i<numOfJudges; i++) {
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
} else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
System.out.println(sum);
I want to make is so if a number is entered that's not between 0 and 10, it won't count that as one of the conditions as i < numOfJudges.
For example if I have 3 judges and I enter 2 wrong inputs, it will still only run the loop 3 times (and only take the good input into account) while I really want it to run 5 times to make up for the two incorrect inputs.
Increment numOfJudges in case of ELSE condition so that your FOR loop would run until you have desired number of correct inputs.
This is shortest and cleanest solution.
else {
System.out.println("Incorrect number, must be between 0 and 10.");
numOfJudges++;
}
You can use a while loop inside of the for-loop, instead of adjusting the for-loop:
for (int i=0; i<numOfJudges; i++) {
while(true){
System.out.print("Enter judge's score: ");
int score = IO.readInt();
if (score >= 0 && score <= 10) {
sum += score;
break; //jump out of while-loop
}else {
System.out.println("Incorrect number, must be between 0 and 10.");
}
}
}
System.out.println(sum);

Why am I getting this "Out of Bounds" error?

I am getting an out of bonds error when I use this coding to get user input. The user input for noOfJudges is how long the array will be. For each judge a score is entered and tested to see if it is between 1 and 10.
Code:
double [] scores = new double [noOfJudges];
System.out.print("Please enter the next score: ");
for(scoreEntry = 0; scoreEntry < scores.length; scoreEntry++)
scores[scoreEntry]=console.nextDouble();
System.out.println();
while((scores[scoreEntry] < MIN_SCORE)||(scores[scoreEntry] > MAX_SCORE))
{
System.out.print("Please reenter the score (must be between 1.0 and 10.0, in .5 increments): ");
scores[scoreEntry] = console.nextDouble();
System.out.println();
}
If anyone wants to be totally great, is there a way to check to see if a number is between 1 and 10 and only in .5 increments?
You should use a local variable to the for loop or reset scoreEntry, because at the end of the for loop scoreEntry is equal to the length of the array, which is not a valid index...
After the for loop ends,
do a System.out.println(scoreEntry);
Therein lies your answer :)
Best,
Ankit
You must forgot a pair of {}
double[] scores = new double[noOfJudges];
System.out.print("Please enter the next score: ");
for(scoreEntry = 0; scoreEntry < scores.length; scoreEntry++) {
scores[scoreEntry] = console.nextDouble();
System.out.println();
while((scores[scoreEntry] < MIN_SCORE) || (scores[scoreEntry] > MAX_SCORE)){
System.out.print("Please reenter the score " +
"(must be between 1.0 and 10.0, in .5 increments): ");
scores[scoreEntry] = console.nextDouble();
System.out.println();
}
}

Categories

Resources