How do you stop a conditional loop from running. For example if I write an if statement that accepts values from 0 to 100. How do stop the program if a user enters a number less then 0 or above 100.
import java.util.Scanner;
public class TestScores {
public static void main(String[]args) {
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++) {
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100) {
try {
throw new InvalidTestScore();
}
catch (InvalidTestScore e) {
e.printStackTrace();
}
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
You use the
break;
keyword. This breaks out of a loop.
You may want to use break
for(int i=0; i<100; i++)
{
if(user entered invalid value)
break; // breaks out of the for loop
}
Here's a hint, since this looks like homework to me: you can either use the break keyword, or use this condition:
if (grade[index] < 0 || grade[index]> 100)
{
// invalid grade...
}
as part of the loop condition.
Related
I am trying to prompt the user to enter 5 integers but it won't loop more than once. I don't know why this is happening and couldn't resolve the error by myself
Code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}
If you follow your code, you can see that when inputOK is true, there is no loop to get back to. It looks like you had some counter in mind, but you ended up not using it. The following code does what I think you intended with your code:
Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
System.out.println("Please enter an integer.");
// Skip over non-integers.
while(!sc.hasNextInt()) {
System.out.println("Invalid input: " + sc.next());
}
// Read and store the integer if it is valid.
int nextInt = sc.nextInt();
if(nextInt < -10 || nextInt > 10) {
// Make the for loop repeat this iteration.
System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
i--;
continue;
}
data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
System.out.println("data[" + i + "] = " + data[i]);
}
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double score = 0, avg, sum = 0;
int index = 0, count = 0, num = 0;
readInput(keyboard, num);
double Test[] = new double[num];
System.out.print("\n");
while(count < Test.length)
{
System.out.printf("Enter your test score #%d:", count + 1);
try
{
score = keyboard.nextDouble();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value, please try again\n");
keyboard.next();
continue;
}
if (score >= 0)
{
Test[count] = score;
sum = sum + score;
}
else
{
System.out.print("You have entered an invalid grade, please try again\n");
continue;
}
count++;
}
double maxValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] > maxValue)
{
maxValue = Test[i];
}
}
double minValue = Test[0];
for (int i = 1; i < Test.length; i++)
{
if (Test[i] < minValue)
{
minValue = Test[i];
index = i;
}
}
System.out.print("\nThe highest value is: " + maxValue + "\n");
System.out.print("The lowest value is: " + minValue + "\n");
avg = sum / Test.length;
System.out.printf("Your grade average is: %.1f \n\n", avg);
System.out.print("Would you like to drop the lowest grade: Y or N:");
char choice = keyboard.next().charAt(0);
if (choice == 'Y' || choice == 'y')
{
double newSum = sum - minValue;
double newAvg = newSum / (Test.length - 1);
System.out.print("\nYour old scores were: ");
System.out.print(Test[0]);
for (int i = 1; i < Test.length; i++)
{
System.out.print(", " + Test[i]);
}
System.out.print("\n\nYour new scores are: ");
for (int i = 0; i < Test.length; i++)
{
if (index != 0 && i != index)
{
if (i >= 1)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
else if (i != index)
{
if (i >= 2)
{
System.out.print(", ");
}
System.out.print(Test[i]);
}
}
System.out.printf("\n\nYour new average is: %.1f\n", newAvg);
}
else if (choice == 'N' || choice == 'n')
{
System.out.print("Your average has stayed the same.\n");
return;
}
else
{
System.out.print("You have entered an invalid response. Bye.\n");
return;
}
}
public static int readInput(Scanner keyboard, int num)
{
System.out.print("How many scores would you like to enter:");
try
{
num = keyboard.nextInt();
}
catch(java.util.InputMismatchException e)
{
System.out.print("You have entered a non-numerical value.\n");
readInput(keyboard, num);
}
if (num < 0)
{
System.out.print("You have entered a negative value.\n");
readInput(keyboard, num);
}
else if (num == 0)
{
System.out.print("If you have no test grades then you do not need this program.\n");
readInput(keyboard, num);
}
return num;
}
}
The program keeps failing and telling me I'm returning the value wrong. num needs to put into the array around line 10 but I'm having trouble getting the value to return. I need to protect against user input error which is why I'm using the Input Mismatch Exception but in order to return them to the beginning if they mess up I was told I needed to use a separate function. However, this sometimes results in an infinite loop of the function. If anyone can help with a new way of doing this or how to fix what I am currently doing that would be a huge help.
I have this java code that basically just prints a christmas tree of X height.However, the program ask for the number, then print the tree and then just end.I would like it to loop until I enter 0,wich would end the program,and also I would like to make it print only if the number entered is from 1-40(not over 40).Im begining in the java world and I dont know how to do that.Heres my code for now:
public class xtree {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
Thank you, im a beginner to java so please be lenient ;)
Well, I would separate the method out into two:
A printChristmasTree method, which accepts the height as a parameter
Your main method, which just deals with taking user input and calling printChristmasTree or exiting
Most of your current main method would go into the printChristmasTree, and main would be a loop. Something like:
public static void main(String[] args) {
Scanner scan = new Scanner(in);
while (true) {
System.out.print("Please enter a number (0-40): ");
int height = scan.nextInt();
if (height == 0) {
// Exit the program
return;
} else if (height >= 1 && height <= 40) {
printChristmasTree(height);
} else {
System.out.println("Invalid input.");
}
}
}
There are other approaches you could use instead of returning from a while (true) loop, but this looks the simplest to me.
The separation of the "taking input" from the "printing the Christmas tree" aspects leads to much more readable code than keeping them combined, in my view - and it's more flexible in terms of things like writing a different program to print all valid Christmas trees.
Use a while loop:
Scanner scan = new Scanner(System.in);
System.out.print("please enter a number: ");
int temp = scan.nextInt();
while (temp>0) {
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
System.out.print(" ");
}
for(int k = 0; k<z; k++)
{
System.out.print("*");
}
System.out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
System.out.print(" ");
}
System.out.println("*");
temp = scan.nextInt();
}
Here's the code for doing that:
public class xtree {
public static void main(String[] args)
{
int temp;
do{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
temp = scan.nextInt();
if(temp >= 1 && temp <= 40){ //don't display a tree higher than 40
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp-1; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}else if(temp != 0){
out.print("Please enter a number between 1 and 40!");
}
}while(temp != 0);
}
}
I did everything as far as concepts. I made my class, and my client class. The assignment is to make a program that allows the user to input 10 grades into a gradebook, and get the max, min, and average grade of class.
My only problem is I want to make sure the user cannot put anything in the program that is not an integer; do I put instructions like that in my class or client java doc?
This is my class:
import java.util.Arrays;
public class ExamBook{
int grades[];
int classSize;
int MIN = 0;
int MAX = 100;
public ExamBook(int[] gradeBook)
{
classSize = 10;
//instantiate array with same length as parameter
grades = new int[gradeBook.length];
for ( int i = 0; i <= gradeBook.length-1; i++ )
{
grades[i] = gradeBook[i];
}
Arrays.sort(grades);
}
//setter, or mutator
public void setClassSize( int newClass )
{
classSize = newClass;
}
//get return method
public int getClassSize()
{
return classSize;
}
//calculate highest grade
public int calculateMaxGrade()
{
int max = grades[0]; //assuming that the first index is the highest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] > max )
max = grades[i]; //save the new maximum
}
return max;
}
//calculate lowest grade
public int calculateMinGrade()
{
int min = grades[0]; //assuming that the first element is the lowest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] < min)
min = grades[i]; //save the new minimum
}
return min;
}
//calculate average
public double calculateAverageGrades()
{
double total = 0;
double average = 0;
for ( int i = 0; i < grades.length; i++ )
{
total += grades[i];
}
average = total/grades.length;
return average;
}
//return an assorted array
public int[] assortedGrades()
{
Arrays.sort(grades);
return grades;
}
//return printable version of grades
#Override
public String toString()
{
String returnString = "The assorted grades of the class in ascending order is this: " + "\t";
for ( int i = 0; i <= grades.length - 1; i++ )
{
returnString += grades[i] + "\t";
}
returnString += " \nThe class average is a/an " + calculateAverageGrades() + "." + "\nThe highest grade in the class is " + calculateMaxGrade() + "." + "\nThe lowest grade in the class is " + calculateMinGrade() + ".";
returnString += "\n";
return returnString;
}
}
**This is my client:**
import java.util.Scanner;
import java.util.Arrays;
public class ExamBookClient
{
public static ExamBook classRoom1;
public static void main( String[] args)
{
int MAX = 100;
int MIN = 0;
Scanner scan = new Scanner(System.in);
//create array for testing class
int[] grading = new int [10];
System.out.println("Please enter 10 grades to go into the exam book.");
if(scan.hasNextInt())
{
for (int i = 0; i < grading.length; i++)
{
int x = scan.nextInt();
if( x>MIN && x<MAX)
{
grading[i] = x;
}
}
}
classRoom1 = new ExamBook (grading);
System.out.println("The classroom size is " + classRoom1.getClassSize() + "."
+ "\n" + classRoom1.toString() + ".");
}
}
Prompt for scan.hasNextInt() in your for loop of your client instead of outside the for loop. Like this:
boolean failed = false;
for (int i = 0; i < grading.length; i++)
{
if (failed)
scan.nextLine();
failed = false;
if (scan.hasNextInt()) {
int x = scan.nextInt();
if(x >= MIN && x <= MAX)
{
grading[i] = x;
} else {
System.out.println("Grade must be from 0-100!");
i--;
continue;
}
} else {
// jump back to the start of this iteration of the loop and re-prompt
i--;
System.out.println("Number must be an int!");
failed = true;
continue;
}
}
You might want to do this in two parts - your API should specify that it works with only integers - perhaps the method which processes the grades will accept Integer arguments only. The parser of the String can specify in its Javadocs what it does when the argument passed to it is not an integer. You client should also validate that the input is an integer (maybe within the valid range). If the user input is incorrect, then maybe it can display a usage manual.
You can check using the below code. If you pass other than number it would throw NumberFormatException
public static boolean checkIfNumber(String input) {
try {
Integer in = new Integer(input);
} catch (NumberFormatException e) {
return false;
}
return true;
}
You can change this part as follows. This way the user can enter non-integers but in those cases you will print out warnings and you will ignore them.
System.out.println("Please enter 10 grades to go into the exam book.");
int i = 0;
int x = -1;
while (scan.hasNext() && i < 9) {
String sx = scan.next();
try {
x = Integer.parseInt(sx);
i++;
if (x > MIN && x < MAX) {
grading[i] = x;
}
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
classRoom1 = new ExamBook(grading);
Chech this link, it has the solution.
You must use the method hasNextInt() of Scanner.
If you do not want to use exceptions you can always use a Regex match to check that what you have in the string is a number valid for you.
Bearing in mind that your valid numbers are between 0 and 100, and 0 and 100 are not included seeing you code, the reg ex will be:
s.matches("[1-9][0-9]{0,1}")
Basically what this means is that you are going to have a character that is a number between 1 and 9 as first char, and then you could have one between 0 and 9, this way you do not allow 0 at the beginning (01 is not valid) and 0 by it self is also not valid. 100 has 3 chars so is not valid neither.
When i run my program and choose a number between 0 and 100, it prints my answer wrong.
Java console
----jGRASP exec: java TestScores
How many tests do you have? 3
Enter grade for Test 1: 80
Enter grade for Test 2: 80
Enter grade for Test 3: 80
The average is: 26.666666666666668The average is: 53.333333333333336The average is: 80.0
----jGRASP: operation complete.
import java.util.Scanner;
public class TestScores {
public static void main(String[] args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index] > 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++) {
totGrades += grade[index];
average = totGrades / grade.length;
System.out.print("The average is: " + average);
}
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You print the average inside the loop that calculates the average.
Print it only outside the loop.
You should calculate sum in loop and then (after the loop) divide it by the number of elements.
I move the statement which calculates the sum from inside the loop to the outside, that works.
My new code is.
import java.util.Scanner;
public class TestScores
{
public static void main(String[]args)
{
int numTests = 0;
double[] grade = new double[numTests];
double totGrades = 0;
double average;
int check = 1;
Scanner keyboard = new Scanner(System.in);
System.out.print("How many tests do you have? ");
numTests = keyboard.nextInt();
grade = new double[(int) numTests];
for (int index = 0; index < grade.length; index++)
{
System.out.print("Enter grade for Test " + (index + 1) + ": ");
grade[index] = keyboard.nextDouble();
if (grade[index] < 0 || grade[index]> 100)
{
try
{
throw new InvalidTestScore();
}
catch (InvalidTestScore e)
{
e.printStackTrace();
}
break;
}
}
for (int index = 0; index < grade.length; index++)
{
totGrades += grade[index];
}
average = totGrades/grade.length;
System.out.print("The average is: " + average);
}
}
public class InvalidTestScore extends Exception
{
public InvalidTestScore()
{
super(" Error: Enter a number between 0 and 100");
}
}
You can close my post.