Looping or printing a receipt - loops

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);
}
}

Related

try catch blocks not able to figure out catch java

SORRY ABOUT FORMATTING. i am trying to determine if the grade is a passing, failing, or invalid grade. however i can't figure out how to catch the error.
EDIT: 70-100 OR "s" or "S" = pass; 0-69 OR u or U = retake; everything else = invalid.
This is my code:
import java.util.*;
public class Demo
{
public static void main(String [] args)
{
Scanner kb = new Scanner(System.in);
String total="";
System.out.println("enter grade");
total = kb.nextLine();
System.out.println(evaluateGrade(total));
}
public static String evaluateGrade(String expr)
{
String result ="";
boolean invalid = false;
int grade = Integer.parseInt(expr);
try{
if((grade <100 && grade >=70) || (expr.equalsIgnoreCase("s"))
{
result ="pass";
}
else if((grade <70 && grade >0)|| expr.equalsIgnoreCase("u"))
{
result ="retake";
}
else
{result="invalid";
}
} catch (Exception e)
{
}
return result;
}
}
This is my code:
import java.util.*;
class Demo{
public static void main(String [] args){
Scanner kb = new Scanner(System.in);
System.out.println("enter grade");
System.out.println(evaluateGrade(kb.next()));
kb.close(); // You need to ".close" your stuff
}
public static String evaluateGrade(String expr){
String result ="";
// boolean invalid = false; <--- This is not necessary
if(expr.equalsIgnoreCase("s")){
return "pass";
}
if(expr.equalsIgnoreCase("u")){
return "retake";
}
try{ // Try to get a Integer on "grade"
Integer grade = Integer.valueOf(expr);
if( (grade <= 100 && grade >=70)){ // 70 <= grade <= 100, and you forgot the ')'
result ="pass";
}
else if((grade <70 && grade >=0)){ // 0 <= grade < 70
result ="retake";
}
else{
result="invalid";
}
}
catch(NumberFormatException e){ // If "grade" is not a number, then you have this line
System.err.println("Your grade must be a NUMBER between 0 and 100.");
return "invalid"; // Return something to keep going with your code
}
return result;
}
}
If you're not understanding what is happening with your code, write it down on the paper.
Have a good day!

loop issue at end of program, can't exit

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.

Putting array with unknown variables into another array

The purpose of this code is is to define the root of the sum of the squares.
I cant figure out how to put i into j. Please help.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int input, som, i=0;
int j = 0;
double answer;
Boolean gaDoor= true;
int [] array = new int [24];
while (gaDoor)
{
Console.Write("Specify a positive integer");
input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
gaDoor = false;
}
else
{
if (input >= 0)
{
array[i] = input;
i++;
}
else
{
Console.WriteLine("Specify a positive integer ");
}
}
}
while (j<i)
{
sum = array [j] ^ 2;
answer = Math.Sqrt(sum);
Console.Write(answer);
}
Console.ReadKey();
}
}
}
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] invoer = new int[24];
double[] resultaat = new double[24];
double totaal = 0;
double wortel = 0;
int commando = 0;
int teller = -1;
try {
// Keep going until a negative integer is entered (or a 0)
while ((commando = Convert.ToInt32 (Console.ReadLine ())) > 0) {
teller++;
invoer [teller] = commando;
}
} catch (FormatException) {
// Not a number at all.
}
teller = -1;
foreach (int i in invoer) {
teller++;
resultaat [teller] = Math.Pow (invoer [teller], 2);
totaal += resultaat [teller];
if (invoer [teller] > 0) {
Console.WriteLine ("Invoer: {0}, Resultaat: {1}", invoer [teller], resultaat [teller]);
}
}
wortel = Math.Sqrt (totaal);
Console.WriteLine ("Totaal: {0}, Wortel: {1}", totaal, wortel);
}
}
}

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.

Can't get keyListener to work while Timer is running

Hello people of stack overflow, my program has a driver class Frogger(), a JPanel class that calculates everything, pulls together all the necessary panels, and implements keyListener called FroggerPanel(), and another JPanel class that draws everything based on the elements in FroggerPanel() called FroggerDisplayPanel().
Here's a pastebin with the full code: http://pastebin.com/Axrbjej6.
The keyListener works exactly as it should when the Timer isn't started, but as soon as it starts it wont respond at all!
This is where the keyListener is added and focused on in the Frogger() class:
public static void main(String[]args) throws IOException
{
frame = new JFrame("CS125 Frogger");
Frogger startPanel = new Frogger();
FroggerPanel panel = new FroggerPanel();
frame.addKeyListener(panel);
frame.setFocusable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
This is the stepGame() method in FroggerPanel() that is called when the timer delay expires, its mostly concerned with moving all the cars; the Frog Rectangle in the setLocations() method is what I need to respond to the keyListener:
private int current_x_step = 0;
private int lane_bounds = 0;
private int new_pos = 0;
private void stepGame() {
for (int i = 0; i < laneAmt; i++) {
if(i == 0 || i % 2 == 0){
current_x_step = X_STEP_SIZE;
lane_bounds = display.getWidth()+rUnit;
new_pos = -rUnit;
}else if((i-1) == 0 || (i-1) % 2 == 0){
current_x_step = -X_STEP_SIZE;
lane_bounds = -rUnit;
new_pos = DISPLAY_DIM + rUnit;
}
for(int j = 0; j < cars.get(i).size(); j++){
cars.get(i).get(j).x += current_x_step;
if (cars.get(i).get(j).x == lane_bounds) {
cars.get(i).get(j).x = new_pos;
}
if(cars.get(i).get(j).intersects(Frog)){
timer.stop();
startPause.setText("Retry?");
break;
}
}
}
display.setLocations(cars, Frog);
if(Frog.y == 0){
stepLevel();
}
}
This is the keyListener code thats in the FroggerPanel() class:
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_W: Frog.y -= rUnit; break;
case KeyEvent.VK_S: Frog.y += rUnit; break;
case KeyEvent.VK_A: Frog.x -= rUnit; break;
case KeyEvent.VK_D: Frog.x += rUnit; break;
}
display.setLocations(cars, Frog);
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_W: Frog.y -= rUnit; break;
case KeyEvent.VK_S: Frog.y += rUnit; break;
case KeyEvent.VK_A: Frog.x -= rUnit; break;
case KeyEvent.VK_D: Frog.x += rUnit; break;
}
display.setLocations(cars, Frog);
}
Any suggestions are appreciated, thanks for the help!

Resources