How to set a limit in a for loop? - java

I have to create a program to calculate the average of each students' scores. I managed to do that but how can I limit the score to be only between 0 to 100? I've searched other questions and many shows to put while statement. The problem is that I don't know where to add the while. So here's the code:
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
If there is any other ways please do state. Thanks in advance.

import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
double Input = 0; **//Add this in your variable**
boolean Valid = false; **//Add this in your variable**
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
//validation of your input from 0 to 100
if(Input>=0&&Input<=100)
{
Valid = true;
}
//enter while loop if not valid
while(!Valid)
{
System.out.println("");
System.out.print("Please enter a valid score " + (g + 1) + ": ");
Input = new Scanner(System.in).nextInt();
if(Input>=0&&Input<=100)
{
Valid = true;
}
}
Valid = false; //reset validation;
Total += Input;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}

An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid:
Scanner scanner = new Scanner(System.in);
int score;
while (true) {
System.out.print("Please enter score " + (g + 1) + ": ");
score = scanner.nextInt();
if (score >= 0 && score <= 100) {
break;
}
System.out.println("Please enter a valid score between 0 and 100!");
}
Total += score;
Remember to close your Scanners to avoid memory leaks!

Related

I want to print how many number is greater than the average

I already print the total and average. However I can't print how many numbers is greater than average.
I think the problem is the number>= average, it seems like only adding the last input.
public static void main(String[] args) {
int i;
int number = 0;
double total=0;
double average=0;
int aboveaverage=0;
Scanner read = new Scanner (System.in);
for(i=1;i<9;i++){
System.out.print("Enter number " + i +": ");
number=read.nextInt();
if(number<0){
System.out.println("Invalid Input");
break;
}
total+=number;
}
if(number>=average){
aboveaverage+=1;
System.out.println("Greater than average is :" + aboveaverage);
}
average=total/8;
System.out.println("Print total : "+ total);
System.out.println("Print Average : " +average );
}
}
You will need to collect all numbers (by placing them in an int array), and iterate over all numbers, for example inside a for loop.
public static void main(String[] args) {
int i;
int number = 0;
int numberCount = 8;
int[] numberArray = new int[numberCount];
double total = 0;
double average = 0;
int aboveAverage = 0;
Scanner read = new Scanner (System.in);
for(i = 0; i < numberCount; i++){
System.out.print("Enter number " + (i + 1) + ": ");
number = read.nextInt();
if(number < 0){
System.out.println("Invalid input");
continue;
}
numberArray[i] = number;
total += number;
}
average = total / numberCount;
for(i = 0; i < numberCount; i++){
if(numberArray[i] > average) {
aboveAverage++;
}
}
System.out.println("Count of numbers greater than average: " + aboveAverage);
System.out.println("Print total: " + total);
System.out.println("Print average: " + average);
}

Trying to keep new ending balance if while loop repeats

I have to create a game that prompts the user to put in a starting balance and then place a bet. Then they win or lose and their balance is added or subtracted accordingly. My problem is that I don't know how to make the program remember the final balance before starting over in the while loop if the player wants to play again. My balance stays as the original first balance entered when the user is prompted. I'm sorry if this is a repeat, but I couldn't find a question like this and I've been searching for over an hour. Thanks in advance.
import static java.lang.Math.*;
import java.util.Scanner;
public class BetGame
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int die1, die2;
boolean looping = true;
System.out.println("Please enter your starting balance in whole dollars:");
double balance = in.nextDouble();
System.out.println("Your beginning balance is " + balance + ", good luck!!");
int guess = 0;
double bet2 = 0;
double endingBalance = 0;
while(looping) {
while (guess < 3) {//to allow the user to do this only 3 times
System.out.println("Enter a valid bet:");
double bet = in.nextDouble();
if (bet >= balance || bet >= endingBalance){
System.out.println("That is more than your balance.");
}
else if (bet < balance || bet < endingBalance) {
bet2 = 0 + bet;
break;
}
guess++;
if (guess == 3) {
looping = false;
System.out.println("You have entered three invalid bets in a row. Please leave the casino.");
}
}
die1 = RollDie();
die2 = RollDie();
int sum = die1 + die2;
if (2 <= sum && sum <= 6) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!");
endingBalance = balance + bet2;
}
else if (7 <= sum && sum <= 12) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!");
endingBalance = balance - bet2;
}
System.out.println("Your balance is " + endingBalance);
System.out.println("Do you want to roll again?");
String answer = in.next();
if ((answer.equals("n")) || (answer.equals("N"))) {
looping = false;
}
}
System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!");
}
static int RollDie()
{
int min = 1;
int max = 6;
return myRandomInteger(min, max);
}
static int myRandomInteger(int min, int max)
{
double range = max - min + 1.0;
int randomNum = (int)(range * Math.random()) + min;
return randomNum;
}
}
You can store the balance in a variable
double balance = in.nextDouble();
double originalBalance = balance;

Java Change Prompt Order

I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.

Guidance needed for Invalid input error and collaborative class statistics for Grade Calculator

I am building a grade calculator in Java, I am having trouble adding a couple features to it, and it appears that I keep mucking it up too while I try to make changes. I have been working on it all week, and started over in the book and the powerpoint slides, and I just feel like there are just some pieces I am still not getting.
I need to make sure the invalid scores, reenter error shows up everytime a negative score is inputted. And then I need to calculate the class statistics of Average, Lowest and Highest scores. So basically a collaboration of how ever much data was inputted which could be any number of exams or students.
Here is my code, please let me know if you need more info. I am really new to this so I apologize that it is not the greatest.
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args){
double examAverage = 0, scoresEntered = 0, examSum = 0;
double totalExamSum = 0, allScoresEntered = 0;
//variables for input
Scanner GC = new Scanner(System.in);
//Scanner for integer inputs
System.out.println("Welcome to Grade Calculator!" +"\n");
System.out.println("Please enter the number of students:");
int numberStudents = GC.nextInt();
//number of students input
System.out.println("Please enter the number of exams:");
int numberOfExams = GC.nextInt();
//number of exams input
for (int i = 1; i <= numberStudents; i++) {
Scanner name = new Scanner(System.in);
//scanner for student name input
//Scanner for name input
System.out.println("\n--------------------------------------");
System.out.print("Enter student " + i + "'s name : " );
String studentname = name.nextLine();
//student name input
System.out.print("Enter exam scores : ");
for (int j = 0; j < numberOfExams; j++) {
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);}
//score input and sum of all input scores
do{
System.out.println("Invalid exam scores, reenter: ");
scoresEntered =GC.nextDouble();
} while(scoresEntered<0);
//my attempt at the Invalid exam score error
examAverage = (examSum/numberOfExams);
//examaverage calculator
System.out.println("\n--------------------------------------");
System.out.println("Grade Statistics for " + name);
System.out.println(" Average : " + examAverage);
//Conditions and print outputs below for grade averages
if(examAverage <= 100 & examAverage >=90){
System.out.println(" Letter Grade: A");
System.out.println(" " + name + " gets 4 stars! ****");
examAverage = 0;
examSum = 0;}
else if(examAverage <=89.99 & examAverage >=80){
System.out.println(" Letter Grade: B");
System.out.println(" " + name + " " + " gets 3 stars! ***");
examAverage = 0;
examSum = 0;}
else if(examAverage <=79.99 & examAverage >=70){
System.out.println(" Letter Grade: C");
System.out.println(" " + name + " " + " gets 2 stars! **");
examAverage = 0;
examSum = 0;}
else if(examAverage <=69.99 & examAverage >=60){
System.out.println(" Letter Grade: D");
System.out.println(" " + name + " " + " gets 1 stars! *");
examAverage = 0;
examSum = 0;}
else if(examAverage <=59.99 & examAverage >=50){
System.out.println(" Letter Grade: F");
System.out.println(" " + name + " " + " gets 0 stars!");
examAverage = 0;
examSum = 0;}
//still need class statistics as well as help with the invalid exam scores, reenter error.
}
}
}
What jumps out at me is the looping around your score input:
for (int j = 0; j < numberOfExams; j++)
{
scoresEntered = GC.nextDouble();
examSum = (examSum + scoresEntered);
}
//score input and sum of all input scores
do
{
System.out.println("Invalid exam score, reenter: ");
scoresEntered = GC.nextDouble();
} while(scoresEntered < 0);
I've deliberately reformatted what you posted to try to make the problem more obvious. What you appear to be doing is reading in all the scores. Then, regardless of what was entered, you tell the user the exam scores are invalid and ask them to re-enter. Remember, a do...while loop always executes at least once. If the first re-entered score is above zero, that is all you'll read as the while condition is then satisfied.
If you are trying to validate each score before it is added to examSum, you need something more like this:
for (int j = 0; j < numberOfExams; j++)
{
while ((scoresEntered = GC.nextDouble()) < 0)
System.out.println("Invalid exam scores, reenter: ");
examSum = (examSum + scoresEntered);
}

How to get my program to start over when the user hits "y" on

So I've used System.out.print("Enter more test scores? (y/n): "); yet when I run it and all the scores are summarizes the user isn't given the chance to do it again here is my code. Do you guys think I may have put it in the wrong place.
public class TestScoreApp
{
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
outerLoop:
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
if (setNumber == counter)
{
break outerLoop;
}
//End of test scores while loop
}
userAnswer = sc.next();
}
}// end of do loop
while(userAnswer.compareTo("y") == 0 );
System.out.print("Enter more test scores? (y/n): ");
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
}
I dont know what exactly you want to do, if you want to ask if the user want to add more scores after the default scores (that user set on beggining) so this is the answer:
import java.text.NumberFormat;
import java.util.Scanner;
public class TestScoreApp {
public static void main(String[] args) {
// display operational messages
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
// declarations
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
// outerLoop:
// do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999) {
do { // put the loop condition below
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100) {
scoreCount += 1;
scoreTotal += testScore;
setNumber--;
} // Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
// if (setNumber == counter) {
// break outerLoop;
// }
if (setNumber == counter) { // test if the counter reached zero
System.out.print("Enter more test scores? (y/n): "); // ask if the user want to add more
userAnswer = new Scanner(System.in).next(); // read the input
if (userAnswer.toCharArray()[0] == 'y') { // if yes, do
setNumber += 1; // add +1 to setNumber, so user can add more one score
}
}
} while (setNumber > 0);
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n" + "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n" + "Average score: "
+ averageScore + "\n"
// Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n" + "Min score: " + min + "\n";
System.out.println(message);
}
}
There are several modifications to be done in the program.
When you are asking user to enter the choice for inputting more, you should accept his/her choice in your userAnswer variable before closing off the do-while loop SO THAT THE USER CHOICE CAN BE CHECKED AFTER EACH ITERATION!
There is no need to break the OUTER-LOOP without checking user's input!
scoreCount & scoreTotal need to be initialised with 0 again in the beginning of the do-while loop.
The corrected program along with the imports needed :-
import java.text.NumberFormat;
import java.util.Scanner;
public class JavaApplication7 {
public static void main(String[] args) {
System.out.println("Please enter the number of test scores to be entered");
System.out.println("To end the program enter 999.");
System.out.println(); // print a blank line
int scoreCount = 0,scoreTotal = 0;
int testScore = 0;
int min = 100;
int max = 0;
int counter = 0;
int setNumber = 0;
String userAnswer = "n";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
do {
// user enters number of test scores to be entered
System.out.print("Enter the number of test scores to be entered: ");
setNumber = sc.nextInt();
if (setNumber > 0 && setNumber != 999)
{
scoreCount=0;
scoreTotal=0;
while (setNumber > 0)
{
// user enters test scores
System.out.print("Enter score: ");
testScore = sc.nextInt();
if (testScore <= 100)
{
scoreCount += 1;
scoreTotal += testScore;
setNumber --;
} //Added for Exercise 2-2, #4 modified if statement
else if (testScore > 100 || testScore < 0) {
System.out.println("Invalid entry, score not counted");
} else if (testScore == 999) {
System.out.println("Average test score complete");
}
if (testScore > max && testScore <= 100) {
max = testScore;
}
if (testScore < min && testScore >= 0) {
min = testScore;
}
}
// display the score count, score total, and average score
// Added casting from int ot double Exercise 3-2 #5
double averageScore = (double) scoreTotal / (double) scoreCount;
// Added number formatting ( 1 decimal place)
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
String message = "\n"
+ "Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n"
//Added for Exercise 3-2 #4 add min/max
+ "Max score: " + max + "\n"
+ "Min score: " + min + "\n";
System.out.println(message);
}
System.out.print("Enter more test scores? (y/n): ");
userAnswer=sc.next(); // Single Error----Only corrected piece of code.
}while(userAnswer.compareTo("y") == 0 );
// end of do loop
}
}
You are asking the user:
System.out.print("Enter more test scores? (y/n): ");
after you exit from the while loop. This won't work. Just put this line exactly before:
userAnswer = sc.next();

Categories

Resources