loop issue at end of program, can't exit - loops

Ok, thanks, I have figured out the exit loop.
Now my problem is that I'm trying to test the int newScore to ensure its value is between 1 and 100. The loop halfway works. If I enter a value outside the parameters it loops and asks for it again. However, when I enter a value within the parameters it's not breaking the loop and continuing to the next part of the program (either asking for the next test score, or calculating the average if there are no more scores) This is the code I updated to try this loop:
do {
while (scoreValid) {
while (tv) {
try {
System.out.println("Please enter test score # " + counter);
newScore = Integer.parseInt(scan.nextLine());
if (newScore >= 1 && newScore <= 100) {
scoreValid = true;
tv = false;
counter++;
totalScore = totalScore + newScore;
break;
} else {
System.out.println("Sorry, you must enter a number between 1 and 100.");
tv = true;
continue;
}
} catch (Exception e) {
System.out.println("Sorry, I didn't catch that");
continue;
}
}
}
} while (counter <= numberTests);
Here is the original code....
/**
* This app will average test scores and tell you what letter grade you received.
*
* #jordan.hawkes
* #1.0
*/
import java.util.Scanner;
public class TestScoreCalculator {
public static void main(String[] args) {
String first; // First Name entered by user
String last; // Last Name entered by user
String newTestAnswer; // answer for entering another test score
String redoAnswer; // answer to rerun program
int avg; // Average test score
int totalScore = 0; // Total Running Test Score
int newScore; // Test Score Entered by User
int counter = 1; // Number of Scores Entered
int testNumber; // Test # counter
int numberTests = 0; // Number of Tests entered by user
boolean scoreValid = false; // boolean to validate score
boolean newTest = false; // boolean to validate entering another test
boolean redo = false; // boolean to rerun program
boolean numberTestsValid = false; // boolean to validate number of tests
boolean test = false; // test boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
System.out.print("Please enter your first name: ");
first = scan.nextLine();
System.out.print("Hello, " + first + ", please enter your last name: ");
last = scan.nextLine();
while (redo = true) {
while (numberTestsValid = true) {
try {
System.out.println("Thanks, " + first + ", how many test scores would you like to enter? ");
numberTests = Integer.parseInt(scan.nextLine());
numberTestsValid = true;
break;
} catch (Exception e) {
System.out.println("Sorry, I didn't catch that");
continue;
}
}
do {
while (scoreValid = true) {
try {
System.out.println("Great, please enter test score # " + counter);
newScore = Integer.parseInt(scan.nextLine());
scoreValid = true;
counter++;
totalScore = totalScore + newScore;
break;
} catch (Exception e) {
System.out.println("Sorry, I didn't catch that");
continue;
}
}
} while (counter <= numberTests);
testNumber = counter - 1;
avg = (totalScore / testNumber);
switch (avg / 10) {
case 10:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got an A+!");
break;
case 9:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got an A!");
break;
case 8:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got a B!");
break;
case 7:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got a C!");
break;
case 6:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got a D!");
break;
default:
System.out.println("Congratulations " + first.charAt(0) + ". " + last + ", you got an F!");
}
while (test = true) {
System.out.println("type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
test = false;
totalScore = 0;
counter = 1;
redo = true;
break;
} else if (redoAnswer.equals("q")) {
test = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that. Please type r to restart or q to quit");
continue;
}
}
}
} //end main
} //end class

Classic bug:
while (redo = true)
assigns true to redo and is always true, it doesn't test it.
change it to either
while (redo == true)
or far better:
while (redo)
Same goes for other loop conditions.

Related

Looping or printing a receipt

All right, so I have this program based where I want to print a receipt from a dentists office. As it is right now, you enter a number and the cost will print accordingly. However, I would like to able to enter multiple numbers in the program and when I type "-1" I want the program to stop and print the total cost. Take a look:
import java.util.Scanner;
public class DentistReception{
public static void main(String[] args) {
double cost = 0;
int treatment = 0;
final double checkUp = 60.00;
final double cleaning = 30.00;
final double cavity = 150.00;
Scanner input = new Scanner(System.in);
System.out.println("What service(s) will be done?: ");
System.out.println("Checkup: 1");
System.out.println("Cleaning: 2");
System.out.println("Cavity: 3");
System.out.println("Exit: -1");
treatment = input.nextInt();
{
if (treatment == 1) {
cost = cost + checkUp;
}
else {
if (treatment == 2) {
cost = cost + cleaning;
}
else {
if (treatment == 3) {
cost = cost + cavity;
}
else {
while (treatment < 0) break;
}
}
}
}
System.out.println("Total cost it:"+cost);
}
}
I want it to loop until i enter "-1", but the break doesn't seem like it wants to. Whenever I put the while or break somewhere else I get the message "break without loop" or something like that.
Use while and capture the option with a boolean variable
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
double cost = 0;
int treatment = 0;
final double checkUp = 60.00;
final double cleaning = 30.00;
final double cavity = 150.00;
boolean repeat = true;
while (repeat) {
Scanner input = new Scanner(System.in);
System.out.println("What service(s) will be done?: ");
System.out.println("Checkup: 1");
System.out.println("Cleaning: 2");
System.out.println("Cavity: 3");
System.out.println("Exit: -1");
treatment = input.nextInt();
input.nextLine();
switch (treatment) {
case 1:
cost = cost + checkUp;
break;
case 2:
cost = cost + cleaning;
break;
case 3:
cost = cost + cavity;
break;
default:
System.out.println("do you want to break out the loop?");
String ans = input.nextLine();
if (ans.equals("y")){
System.out.println("exiting...");
repeat = false;
}
break;
}
// if (treatment == 1) {
// cost = cost + checkUp;
// } else {
// if (treatment == 2) {
// cost = cost + cleaning;
// } else {
// if (treatment == 3) {
// cost = cost + cavity;
// } else {
// while (treatment < 0)
// break;
// }
// }
// }
}
System.out.println("Total cost it:" + cost);
}
}

Reading text files into array

I'm trying to store girl and boy names into an array.
I got most of the code except the storing the files into an array.
This is what girls.txt looks like
Emma 125125
Elaina 415545
Kim 545454
Boys.txt:
Devan 45645
Tom 4545
Chris 4879797
i need help storing the names and numbers from files into array boynames array and girlnames array. I show where i need help with comments in code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1Names {
public static void main(String[] args) {
Scanner inputStream = null;
String[][] boynames = new String[1000][2];
String[][] girlnames = new String[1000][2];
String line = null;
boolean isFoundB = false;
boolean isFoundG = false;
try {
inputStream = new Scanner(new FileInputStream("boys.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file boys.txt");
System.exit(0);
}
Scanner inputStreamGirls = null;
try {
inputStreamGirls = new Scanner(new FileInputStream("girls.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file girls.txt");
System.exit(0);
}
int count = 0;
while (count < 1000){
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
count++;
}
count = 0;
while (count < 1000 ){
inputStreamGirls = girlnames[count][0]; //here
inputStreamGirls = girlnames[count][1]; //here
count++;
}
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first name that you would like to find the popularity of.\n Be sure to capitalize the first letter of the name.\n");
String answer = keyboard.next();
count = 0;
while(count < 1000){
if (boynames[count][0] == answer){
System.out.println(boynames[count][0] + " is ranked " + count + " among boys with " + boynames[count][1] + " namings");
isFoundB = true;
}
if (girlnames[count][0] == answer){
System.out.println(girlnames[count][0] + " is ranked " + count + " among girls with " + girlnames[count][1] + " namings");
isFoundG = true;
}
count++;
}
if(isFoundB == false){
System.out.println(answer + " is not ranked among the top 1000 boy names.");
}
if(isFoundG == false){
System.out.println(answer + " is not ranked among the top 1000 girl names.");
}
inputStreamGirls.close();
inputStream.close();
keyboard.close();
}
}
You will need to call the scanner methods to actually read from the input file.
scanner.next() reads one string token from the input.
So instead of this part:
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
You would do:
boynames[count][0] = inputStream.next();
boynames[count][1] = inputStream.next();

Loop wont stop, even with limit set (count++)

I just cannot seem to get this to stop looping after the count (5) is reached. IT just keeps asking away. IS there something I'm not seeing?
Any help is greatly appreciated.
Scanner keyboard = new Scanner(System.in);
int count = 0;
double answer = 0;
int randomInt1;
int randomInt2;
randomInt1 = (int)(1 + Math.random() * 10 - 1 +1);
randomInt2 = (int)(1 + Math.random() * 10 - 1 +1);
//System.out.println("Please answer the following problem: ");
//System.out.println(randomInt1 + "+" + randomInt2 + "=");
//answer = keyboard.nextDouble();
count=1;
while(count < 5)
{
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if(answer != (randomInt1 + randomInt2))
{
System.out.println("Sorry, that is not correct.");
count++;
break;
}
if(answer == (randomInt1 + randomInt2))
{
System.out.println("Nice!");
count++;
break;
}
}
return answer;
}
}
****UPDATED
count=0;
while(count < 5)
{
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if(answer != (randomInt1 + randomInt2))
{
System.out.println("Sorry, that is not correct.");
}
else if(answer == (randomInt1 + randomInt2))
{
System.out.println("Nice!");
}
count++;
break;
}
return answer;
Avoid using break on your code. Use else instead of the second if statement. Also, you should better indent your code. It helps reading.
If you want to count 5 times, you should do:
count = 0;
while(count < 5) {
...(your code here)
}
Why don't you increase count outside the if condition.
count = 0;
while(count < 5) {
if(condition1){
// ...
}
else{
// ...
}
count++;
}
Update:
Below is the complete code, which may be like what you want.
import java.util.Scanner;
class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
double answer = 0;
int randomInt1;
int randomInt2;
randomInt1 = (int) (1 + Math.random() * 10 - 1 + 1);
randomInt2 = (int) (1 + Math.random() * 10 - 1 + 1);
while (count < 5) {
System.out.println("Please answer the following problem: ");
System.out.println(randomInt1 + "+" + randomInt2 + "=");
answer = keyboard.nextDouble();
if (answer != (randomInt1 + randomInt2)) {
System.out.println("Sorry, that is not correct.");
} else if (answer == (randomInt1 + randomInt2)) {
System.out.println("Nice!");
break;
}
count++;
}
}
}

Searching for an int in an array

I am trying to search for an int value in an array that has random numbers
this is what I have so far:
String names[]={"Peter","John","Rudy"};
int number[]=new int[3];
for(int z=0;z<3;z++)
{
number[z]=(int)(1+Math.random()*200);
}
int option=Integer.parseInt(JOptionPane.showInputDialog("choose and option:\n1.names\n2.sorting according to alphabet\n3.search number\n4.J"));
switch(option)
{
case 1:
{
for(int l=0;l<names.length;l++)
{
jTextArea1.append(""+names[l]+"\t"+number[l]+"\n");
}
}
break;
case 2:
{
String temp="";
for(int ii=0;ii<names.length;ii++)
{
for(int j=0;j<names.length;j++)
{
if(names[ii].compareToIgnoreCase(names[j])<0)
{
temp=names[ii];
names[ii]=names[j];
names[j]=temp;
}
}
}
for(int x=0;x<names.length;x++)
{
jTextArea1.append(""+names[x]+"\n");
}
}
break;
case 3:
{
boolean found=false;
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
for(int i=0;i<number.length;i++)
{
if(number[i]==searchvalue)
{
found=true;
}
}
if(found==true)
{
jTextArea1.append("number is found"+"\n");
}
else
{
jTextArea1.append("number is not found"+"\n");
}
}
break;
case 4:
{
for(int q=0;q<names.length;q++)
{
if(names[q].startsWith("J"))
{
jTextArea1.append(names[q]);
}
}
}
}
Even when I type the correct answer it gives me the "number is not found" message.I'm dumbfounded on what to do.Any help will be greatly appreciated.
Try something like this. I am not sure if this is exactly what you are looking for...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean found = false;
int searchvalue;
int[] lottoNumber = new int[6];
lottoNumber[0] = (int) ((56 * Math.random()) + 1);
lottoNumber[1] = (int) ((56 * Math.random()) + 1);
lottoNumber[2] = (int) ((56 * Math.random()) + 1);
lottoNumber[3] = (int) ((56 * Math.random()) + 1);
lottoNumber[4] = (int) ((56 * Math.random()) + 1);
lottoNumber[5] = (5);
System.out.print("number?");
searchvalue = input.nextInt();
for (int i = 0; i < lottoNumber.length; i++) {
if (lottoNumber[i] == searchvalue) {
found = true;
}
}
if (found == true) {
System.out.print("number is found" + "\n");
} else {
System.out.print("number is not found" + "\n");
}
}
}
This does not have GUI imports in this by the way.What exactly are you trying to do with this? Can you add the whole code?
Well the answer above works for me! So the answer is your :
int searchvalue=Integer.parseInt(JOptionPane.showInputDialog("number?"));
That line is probably causing the problem.
Try adding:
System.out.println("The number entered was:"+searchvalue);
and then compare it to the number you entered.

Working with private static boolean - java

Seeing as this is for a university assignment, I'm not sure how much detail I can give.
However I'll share what I believe I can.
In my main method I have this code;
System.out.println ("Please enter a year?");
int yearMenu = scan.nextInt();
System.out.println ("Please enter number of questions?");
int questionMenu = scan.nextInt();
confirmSessionDetails(yearMenu, questionMenu);
and this is my private static boolean 'confirmSessionDetails'
private static boolean confirmSessionDetails(int year, int questions)
{
String yearName = " ";
switch (year) {
case 1: yearName = "Year 1"; break;
case 2: yearName = "Year 2"; break;
default: yearName = "error"; break;
}
String questionNumber = " ";
switch (questions) {
case 1: questionNumber = "10"; break;
case 2: questionNumber = "20"; break;
default: questionNumber = "error"; break;
}
System.out.print ("You are a " + yearName + " student and want to do " + questionNumber + " questions. Is this correct (Y/N)?");
correctDetail = scan.next();
if (correctDetail.equalsIgnoreCase ("y"))
{
return true;
}
else
{
return false;
}
So what I want to know is how to get the return value and use it in my main method.
If return value is true it should move on to 'private static void displayQuestions()'
and if the return value is false it should loop back to asking the year and number of questions.
try something like this:
bool myVariable = confirmSessionDetails(yearMenu, questionMenu);
That will assign the returned value of the function confirmSessionDetails(yearMenu, questionMenu) and then you can use myVariable later on in your code.
I would do like :
Main
int yearMenu, questionMenu;
do{
System.out.println ("Please enter a year?");
yearMenu = scan.nextInt();
System.out.println ("Please enter number of questions?");
questionMenu = scan.nextInt();
} while (confirmSessionDetails(yearMenu, questionMenu);
displayQuestions();
Hope it helps.

Resources