How to make Exception handling Loop (Unlimited amount of times) - java

Responses to previous question , my initial answer to that question had been solved, but I had another problem when it came down to looping which was later solved by simply using a for loop.
However, my problem is I do not want the user to constantly have to restart the program after an exception is handled, rather I want it to loop the same beginning questions to the user. I've tried placing print statements after the return statements, and also tried completely copying the logic code after the try catch, however, realizing that that would not cause the user to loop unlimited times for the exception. Also, on a side note yes my previous question had good answers, however, no one managed to answer my more recurring problem, which is why no one got the check mark towards their answer.
import java.io.*;
import java.text.DecimalFormat;
public class Test
{
public static void main(String[] args) throws IOException
{
double x;
x = circlemethods(0.0, 0.0, 0.0, 1.0);
}
public static double circlemethods(double volume, double surfacearea,
double area, double radius) throws IOException
{
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
String numInput;
String reqInput;
String amountStr;
double numInt = 0;
double num = 0;
double answer = 0;
double amount = 0;
double answer2 = 0;
double answer3 = 0;
double answer4 = 0;
for (double i = 0; i < 999; i++)
;
try
{
// for (double i = 0; i < 999; i++);
// while (numInt != 999) {
System.out.println("This program will ask for a given user radius, then proceed to calculate the user input");
System.out.println("The program will use four methods to achieve this, all calling back to the main method");
System.out.println("Press any key to continue");
numInput = myInput.readLine();
System.out.println("First, what would you like to calculate?");
System.out.println("Enter '1' for Circumference, '2' for area, '3' for volume, or '4' for surface area");
reqInput = myInput.readLine();
numInt = Double.parseDouble(reqInput);
System.out.println("Now enter the radius of the required shape(Half of diameter)");
numInput = myInput.readLine();
num = Double.parseDouble(numInput);
DecimalFormat nextAmount = new DecimalFormat("0.00");
amountStr = nextAmount.format(amount);
if (numInt == 1)
{
System.out.println("You chose to calculate circumference, given the radius :" + num);
answer = (3.14) * (2) * (num);
System.out.print("The circumference of that sphere is :");
System.out.println(answer + "cm³");
return answer;
}
else if (numInt == 2)
{
System.out.println("You chose to calculate area, given the radius :" + num);
answer2 = (3.14) * 2;
System.out.print("The area of the circle is :");
System.out.println(answer2 + "cm²");
return answer2;
}
else if (numInt == 3)
{
System.out.println("You chose to calculate volume, given the radius :" + num);
answer3 = 4 / 3 * (3.14) * (num) * (3) * (3) * (3);
System.out.print("The volume of that sphere is : cm³");
System.out.println(answer3 + "cm³");
return answer3;
}
else
// if (numInt == 4)
{
System.out.println("You chose to calculate surface area, given the radius :" + num);
answer4 = 4 * (3.14) * (num) * (2) * (2);
System.out.print("The Surface area of that sphere is :");
System.out.println(answer4 + "cm²");
return answer4;
}
} catch (Exception e)
{
System.out.println("Please do not enter any string values, next time input enter a number ");
return 0;
// how to loop this untill the user inputs a number????
}
}
}

First, you use a while(true) loop instead of looping for 999 times. (That loop doesn't actually do anything considering there is a semicolon right after it.)
Then, you remove the return 0; from your catch block.
So it would be
while(true) {
try {
.... //your code
}
catch {...}
} //while loop end bracket
This way, the loop will only end if it reaches one of your return statements.

You need to loop until you get a valid value. One way to do that is loop until a boolean value is set to true. Try something similar to this:
boolean inputIsValid = false;
while (!inputIsValid) { ...
Then when you have determined you have a valid input, add the line:
inputIsValid = true;
Your loop will continue until inputIsValid becomes true.
You could also create an endless while loop. Then when you receive a valid input, break out of the loop:
while(true) {
//when valid input is received
break;
}

Related

Storing a value created from user input inside a loop for use in other iterations of the loop

I'm trying to create a program that simulates driving a car. In my program, I have the following loop to allow the user to "drive" however many miles they wish:
public void run() {
do {
System.out.println("How many miles would you like to drive?");
int userInput = scanner.nextInt();
if (userInput > 360) {
System.out.println("You don't have enough fuel to drive that far! Please try again.");
run();
}
System.out.println("You are driving: " + userInput + " miles.");
try {
for(int c = 0; c < parts.size(); c++){
parts.get(c).function(userInput);
}
} catch (BreakdownException e) {
}
} while (getBoolean("Keep driving?"));
I would like to take the userInput variable and save it so that I can keep track of how many miles are in the gas tank. This is the code I currently have for that:
public void function(int milesDriven) throws BreakdownException {
int mpg = 30;
int gallons = 12;
int totalMiles = gallons * mpg;
int milesLeft = totalMiles - milesDriven;
if(milesLeft <= 0) {
throw new BreakdownException("You ran out of fuel!");
} else if (milesLeft <= (totalMiles / 4)) {
if (getBoolean("You are low on fuel! Refuel?")) {
milesLeft = gallons * mpg;
System.out.println("You now have enough fuel to travel " + totalMiles + " miles.");
}
} else {
System.out.println("You now have enough fuel to travel " + milesLeft + " miles.");
}
}
Currently, each time the loop in the first code block runs, the value for milesDriven in the second code block resets. Thus, every time the user "drives", their gas tank automatically refills. Is there a way I can store the userInput value so that it retains between loops?
Thanks!
If you don't want to change things up too much, one easy way would be to simply accumulate the user input with another variable, and pass that value into the function method instead of the user input that updates on each loop. So for example, outside of the do-while loop you would have:
int milesDriven = 0;
Then, each time the user gives a new input, add that value to the miles driven:
int userInput = scanner.nextInt();
milesDriven += userInput;
And finally pass that value into the function method instead of the user input:
parts.get(c).function(milesDriven);

BMI Calculator with name, weight, height, BMI and text using Array and for cycle

I would like to ask how do I do that when the cycle starts and go over again, the string variable name will increase by 1. This program is supposed to ask you how many patients are you going to write. If you write for ex. 10, then the cycle will go for 10 times and it will ask all those information I want and then add them to the array which I have already created called BMI. This whole program is supposed to print you a table which contains Name, Height in meters, weight in Kg, your calculated BMI and then text in what state of BMI are you ATM. The problem is how do I do it? I just started learning arrays and stuff like that and my teacher gave me this homework. I don't think that this homework is hard but just hard to understand what to do.
Things I already tried is creating a for cycle with String called name something like this: String name(); but that obviously did not work.
import java.util.Scanner;
class Pacient {
public static void main(String args[]){
int pole;
Scanner input = new Scanner(System.in);
String pacient;
System.out.print("Zadej kolik bude pacientu: "); //How many patients do you want? For ex. 10
pacient = input.nextLine();
input.nextLine();
pole = Integer.parseInt(pacient);
String[][] bmi = new String[4][pole]; //This is supposed to make an array with my patients.
double vaha; //weight
double vyska; //height
String jmeno; //name
double telo1, telo2; //body for calc.
String vysledek; //result
int i,x=0,j, pa=0, k=0; //some variables
bmi[0][0] = "Jmeno"; //First line of final table NAME
bmi[0][1] = "Vaha"; // WEIGHT
bmi[0][2] = "Vyska"; //HEIGHT
bmi[0][3] = "BMI"; //BMI based on calc.
bmi[0][4] = "Text"; //Final result
for(int y=1;y<pole;y++){
pa++;
x++;
System.out.print("Zadej svoje krestni jmeno: ");
jmeno = input.nextLine();
System.out.print("Zadej svoji vahu v Kg: ");
vaha = input.nextDouble();
System.out.print("Zadej svoji vysku v m: ");
vyska = input.nextDouble();
System.out.println("Vase informace byly uspesne ulozeny! ");
bmi[1][0] = jmeno; //These values should somehow increase but idk
how atm and be assign with the patient which
will be printed at the end.
bmi[1][1] = vaha2;
bmi[1][2] = vyska2;
bmi[1][3] = telo3;
bmi[1][4] = vysledek;
}
// System.out.println("Tisknu tabulku");
// telo1 = vyska * vyska; //Some calc. of BMI
// telo2 = vaha / telo1;
// if (telo2 < 18.5) { //Adding text to the result variable
// vysledek = "mate podvahu";
// } else if (telo2 < 25) {
// vysledek = "Jste v normach";
// } else if (telo2 < 30) {
// vysledek = "Nadvaha";
// } else {
// vysledek = "Obezita";
// }
// String telo3 = String.valueOf(telo2); //Converting to strings
// String vyska2 = String.valueOf(vyska);
// String vaha2 = String.valueOf(vaha);
System.out.println("--------------------------------------------------");
for(i=0;i<pole;i++) {
for(j = 0; j<5; j++) System.out.print(bmi[i][j] + " ");
System.out.println();
}
System.out.println("--------------------------------------------------");
}
}
Atm the program is just printing most of the time NULL NULL NULL NULL, and it does not match with the patient number. How do add all this code to for cycle and make it automatic convert int and double to strings and then print them correctly and assign them to the BMI Array. If you have any further questing, feel free to ask.
I have corrected the issues in code. Everything is explained step-by-step in comments. I have converted variable name in English for my understanding. If you have questions. Please ask.
import java.util.Scanner;
class Pacient {
private static Scanner input;
public static void main(String args[]) {
int numberOfPatients; // Variables that saves number of patient
// Asking user the number of patients
input = new Scanner(System.in);
System.out.print("How many patients do you want?: ");
// I have change this to nextInt
// From javadoc "Scans the next token of the input as an int"
// It is essentially next() + parseInt()
numberOfPatients = input.nextInt();
// nextInt() does not move cursor to next line
// using nextLine() here would move it to next line and close
// previous line otherwise it creates issue when you will use next/nextLine again
input.nextLine();
// String[][] array = new String[Rows][Columns];
// For each patient there is a row. Since in the code there is header
// as well that's why we need numberOfPatients + 1
String[][] bmi = new String[numberOfPatients + 1][5];
// All corresponding columns
bmi[0][0] = "Name"; // First line of final table NAME
bmi[0][1] = "Weight"; // WEIGHT
bmi[0][2] = "Height"; // HEIGHT
bmi[0][3] = "BMI"; // BMI based on calc.
bmi[0][4] = "Result"; // Final result
// Starting from 1. Skipping header
for (int y = 1; y <= numberOfPatients; y++) {
// Using y instead of an int. This way the loop will
// automatically move to next row
// Instead of saving it to variable and then to array
// I am saving it directly
System.out.print("Enter your first name: ");
bmi[y][0] = input.nextLine();
System.out.print("Enter your weight in Kg: ");
bmi[y][1] = input.nextLine();
System.out.print("Enter your height in m: ");
bmi[y][2] = input.nextLine();
// Using the information from above to calculate BMI
// Basically I am storing and calculating at the same time
// parseDouble converts String into double
// Math.pow(a,b) is powber function. a is base and b is exponent
double weight = Double.parseDouble(bmi[y][1]);
double heightSquare = Math.pow(Double.parseDouble(bmi[y][2]), 2);
double bmiCalculated = weight / heightSquare;
// Based on BMI assigning result in result column
bmi[y][3] = bmiCalculated + "";
if (bmiCalculated < 18.5) {
bmi[y][4] = "You are underweight";
} else if (bmiCalculated > 18.5 && bmiCalculated < 25) {
bmi[y][4] = "You are normal";
} else if (bmiCalculated > 25 && bmiCalculated < 30) {
bmi[y][4] = "You are overweight";
} else {
bmi[y][4] = "You are obese";
}
System.out.println("Your information has been saved successfully!");
}
System.out.println("--------------------------------------------------");
// In java 2D arrays are multiple 1D array stacked on each other
// bmi.length gives the number of rows
// Basically you iterate through each row and print each individual row
// like 1D array
for (int i = 0; i < bmi.length; i++) {
// bmi[i] gives ith row. Which is 1D array. So you can print it like normal array
for (int j = 0; j < bmi[i].length; j++)
System.out.print(bmi[i][j] + " ");
System.out.println();
}
System.out.println("--------------------------------------------------");
}
}
Your declaration of array and implementation is conflicting. You've fixed the first dimension and kept the second, variable. But you're using as if the first one is variable and second is fixed.
You should declare your array like
String[][] bmi = new String[pole+1][4];
pole+1 because you're using first row for table headings
Your first loop should look like this
for(int y = 1; y < pole+1; y++){
for(int z = 0; z < 4; z++){
String data="ask user for data";
bmi[y][z] = data; //similar for all
}
}
Your output for loop will also look like above.

Variable value not correctly increasing

In my code I have a variable, points, that increments based on the consanants and vowels in strings inputted. The method parseSentence is supposed to increase points per word but also ignore spaces.
I've tried running a debugger to see where the problem is but the debugger dies when it reaches the for loop in parseSentence. The method makes the point variable's value the word's point value instead of adding it to the variable. What could be causing this?
import java.util.*;
public class WordGolf1 {
public static int points = 1;
public static void main(String[] args) {
String Input;
System.out.println("Enter word: ");
Scanner sc = new Scanner(System.in);
Input = sc.nextLine();
System.out.println("Not enough points. " + (100 - points) + " needed.");
while (points < 100) {
System.out.println("Enter word: ");
Input = sc.nextLine();
parseSentence(Input);
System.out.println(points + ": points");
System.out.println("Not enough points. " + (100 - points) + " needed.");
}
boolean overshot = true;
Loop:
while (overshot = true) {
if (points == 100) {
overshot = false;
break Loop;
}
points = 100 - (points - 100);
System.out.println("Overshot by " + (points - 100) + " points.");
Input = sc.nextLine();
parseSentence(Input);
}
System.out.println("Congratulations you win!");
sc.close();
}
public static int parseSentence(String input) {
String[] pieces = input.split("\\s+");
for (int y = 0; y < pieces.length; y++) {
if (pieces.length > 1) {
if (y == 0) {
parseWord(input);
} else {
parseWord(input, y);
}
} else {
parseWord(input);
}
}
return points;
}
public static int parseWord(String input) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[0].length(); x++) {
if (charList.indexOf(pieces[0].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[0].charAt(x))
!= -1) {
pointsTemp++;
}
}
points = pointsTemp;
return points;
}
public static int parseWord(String input, int number) {
String[] pieces = input.split("\\s+");
String charList = "aeiouyAEIOUY";
String consanantList
= "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
int pointsTemp = 1;
for (int x = 0; x < pieces[number].length(); x++) {
if (charList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp *= 2;
} else if (consanantList.indexOf(pieces[number].charAt(x)) != -1) {
pointsTemp++;
}
}
points += pointsTemp;
return points;
}
}
You are not using the value returned by the parseSentence method.
Edit: I tried to rewrite this to be as close your original code with making the changes I feel where necessary.
Now Obviously your teacher has requirements and we can't go against that, but some points of interest you should keep in mind.
Multi Splitting
In your example you split the text to get the amount of words. Then instead of looping the already split text. You are sending the original input and then splitting it again. The "Double" splitting is why you needed "three" methods. If you don't double split you can simply loop the length from the single split and just use a single ParseWord method.
Deducting Values
In your example you take away 100 if the player overshot. The problem with this is let's say the person received a score like 200. Then it would loop twice to lower the value submitting the "You overshot message" twice. However let's say by some magical way a score of 100,000,000 was received. Then as you can see we would loop 1 million times to deduct this value essentially creating an not infinite but might as well be infinite loop.
To resolve this problem we simply do the below.
Value = Value % 100.
This will give us the remainder of our Value between 0 and 99. I.e. 167 will equal 67 and 12384 will be equal 84.
Using String (IndexOf)
What this does is takes the Character you provided and loop iterates over the String you provided. The worst case is 12 loops. There's also a lot of other stuff String and IndexOf do that is extra work and I recommend staying away from it if you can.
The alternative solution which I did is take the character and use " | 32" on it. I'm not going to go deep into how bits work, but basically these characters are 8 bit values but we only use 7 of it's bits ranging from 32 to 127. The amount of bits is like the power of 2. so 2^7 = 128 and 2^8 = 256. When we perform the "|" we are turning a bit on so if it's already on it won't change the value.
So in our example let's say we have the value 64.
This is bit 6 turned on. Now we want to turn on bit 5 "32" so the value becomes 96, but if we already had the value 96 and we turn bit 32 on it will still be 32.
Full List of ASCII Characters..
https://www.ascii-code.com/
The Game Loop
In your example you created "TWO" game loops the first one is when you start off, but once you overshot your score you enter the second loop and forget the first one. The problem is now your "Enter Words" and "You Undershot" code are never used anymore. So all someone will see is the line to enter text with no information on what to do or what occurred unless they overshot then they get the overshot message.
To fix this I made a single Game Loop which processes until the code ends via the SCORE == 100. You can see in the code that we begin every game loop with "Enter Words: " and parse the sentence. Then we add up our score and compare. If we undershot we simply restart the loop and try again. If we overshot we reduce the score and try again. If we succeeded we prompt the user if they would like to play again or end the game. Playing again will set the SCORE to 0 and start over the loop. Ending the game will "BREAK" the loop and cause it to end.
The Full Working Code With Recommended Changes
Feel free to comment if you need additional assistance.
import java.util.*;
public class WordGolf1
{
private static int SCORE = 0;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (true)
{
System.out.print("\n\nEnter word: ");
ParseSentence(sc.nextLine());
if (SCORE == 100)
{
System.out.print("\nYou Won! Would you like to play again: Y/N?");
if ((sc.nextLine().charAt(0) | 32) == 'y')
{
SCORE = 0;
System.out.print("\nResetting Game...");
} else {
break;
}
}
else
{
if (SCORE > 100)
{
int overshot = SCORE - 100;
SCORE = SCORE % 100;
System.out.print("\nYou Overshot By " + overshot + " Points. You now have " + SCORE + " points.");
} else {
System.out.print("\nYou currently have " + SCORE + " points you need " + (100 - SCORE) + " more.");
}
}
}
}
private static int ParseSentence(String input)
{
String[] split = input.split(" ");
for (Strng s : input)
SCORE += ParseWord(s);
}
private static int ParseWord(String word)
{
int value = 1;
for (int i = 0; i < word.length(); ++i)
{
int c = (int)word.charAt(i) | 32;
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
value *= 2;
} else {
value += 1;
}
}
return value;
}
}

How can I get this loop to accept a positive integer for two entries?

To be more clear, please assist me with menuChoice == 2.
I've gotten to the point where if you enter negative values, it prompts you to enter again until it's positive and then the calculations come out fine. However, when I enter just positive values now, it doesn't calculate anything. I've been trying for a while but I just can't figure it out.
What do I need to do?
package finalExam;
//this is required for JOptionPane to work
import javax.swing.JOptionPane;
public class Geometry {
public static void main(String[] args) {
boolean valid = false;
int menuChoice;
do {
// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) Calculate the area of a circle\n"
+ "2) Calculate the area of a rectangle\n"
+ "3) Calculate the area of a triangle\n"
+ "4) Quit\n"
+ "Please enter your choice: (1, 2, 3, or 4)";
menuChoice = Integer.parseInt(JOptionPane.showInputDialog(menu));
if(menuChoice == 1)
{
String unknownRadius = JOptionPane.showInputDialog("What is the radius of the circle?");
if(Double.parseDouble(unknownRadius) < 0){
do{
JOptionPane.showMessageDialog(null, "Please enter positive numbers only.");
unknownRadius = JOptionPane.showInputDialog("What is the radius of the circle?");
}
while(Double.parseDouble(unknownRadius) < 0);
double knownRadius = Double.parseDouble(unknownRadius);
double circleArea = Math.pow(knownRadius, 2) * 3.14159;
JOptionPane.showMessageDialog(null, "The area of the circle is " + circleArea);
}
else if(Double.parseDouble(unknownRadius) > 0) {
double knownRadius = Double.parseDouble(unknownRadius);
double circleArea = Math.pow(knownRadius, 2) * 3.14159;
JOptionPane.showMessageDialog(null, "The area of the circle is " + circleArea);
valid = true;
}
} else if(menuChoice == 2){
String unknownLength = JOptionPane.showInputDialog("What is the length of the rectangle?");
if(Double.parseDouble(unknownLength) < 0){
do{
JOptionPane.showMessageDialog(null, "Please enter positive numbers only.");
unknownLength = JOptionPane.showInputDialog("What is the length of the rectangle?");
}
while(Double.parseDouble(unknownLength) < 0);
double knownLength = Double.parseDouble(unknownLength);
String unknownWidth = JOptionPane.showInputDialog("What is the width of the rectangle?");
if(Double.parseDouble(unknownWidth) < 0){
do{
JOptionPane.showMessageDialog(null, "Please enter positive numbers only.");
unknownWidth = JOptionPane.showInputDialog("What is the width of the rectangle?");
}
while(Double.parseDouble(unknownWidth) < 0);
double knownWidth = Double.parseDouble(unknownWidth);
double rectangleArea = knownLength * knownWidth;
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + rectangleArea);
}
else if(Double.parseDouble(unknownLength) > 0){
knownLength = Double.parseDouble(unknownLength);
unknownWidth = JOptionPane.showInputDialog("What is the width of the rectangle?");
if(Double.parseDouble(unknownWidth) > 0) {
double knownWidth = Double.parseDouble(unknownWidth);
double rectangleArea = knownLength * knownWidth;
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + rectangleArea);
valid = true;
}
}
}
} else if(menuChoice == 3){
String unknownBase = JOptionPane.showInputDialog("What is the base length of the triangle?");
if(Double.parseDouble(unknownBase) > 0){
double knownBase = Double.parseDouble(unknownBase);
String unknownHeight = JOptionPane.showInputDialog("What is the height of the triangle?");
if(Double.parseDouble(unknownHeight) > 0){
double knownHeight = Double.parseDouble(unknownHeight);
double triangleArea = (knownBase / 2) * knownHeight;
JOptionPane.showMessageDialog(null, "The area of the triangle is " + triangleArea);
valid = true;
}
else { JOptionPane.showMessageDialog(null, "Please enter a positive number");
JOptionPane.showInputDialog("What is the base length of the triangle?");
}
}
else { JOptionPane.showMessageDialog(null, "Please enter a positive number");
JOptionPane.showInputDialog("What is the height of the triangle?");
}
}else if(menuChoice == 4){
System.exit(0);
} else
JOptionPane.showMessageDialog(null, "Please select from the options given (1-4)!");
}
while(!valid || menuChoice != 4);
}
}
On line 48, your statement if(Double.parseDouble(unknownLength) < 0){ has the matching closing brace is on line 76, just before the } else if(menuChoice == 3){.
So, logically your code is only running the menuChoice == 2 section when a negative number is entered. You should instead close the if after the first do-while loop completes, since at that point the number will have been (corrected to) positive.
You should also try to work on formatting your code. It will make it more readable and you can easily see that the braces don't line up where they should have after using a beautifier tool, such as Tutorial Point Online Java Formatter.
You've made things too complicated for yourself by having two different blocks of code depending on whether the first length is negative or positive. Basically, your code looks like:
If the length is negative then {
Ask for a new length until it's positive
Now input the width, reject negative values, do the computation,
and output it
} else { // the length is positive
Input the width, reject negative values, do the computation,
and output it
}
The whole part about handling the width occurs twice in your code, which makes the code needlessly complex, and makes it more prone to errors such as getting the curly braces in the wrong place (which I think is why the code isn't behaving). You can make life a lot simpler for yourself by reorganizing the code like this:
If the length is negative then {
Ask for a new length until it's positive
}
// When we get here, the length will be positive. It doesn't matter
// whether we got here because the original length was positive, or whether
// it was negative and the user entered a new value. We're going to
// continue in the same way, either way.
Input the width, reject negative values, do the computation,
and output it
(By the way, I don't know what you want to do if the user enters 0. You really aren't handling that case.)
As far as I could understand, if I have to just achieve what you are asking in the question ,I could simply do like.
(I am giving just an alternate code here in JAVA , you can modify your Japplet accordingly)
int a=-1,b=-1;
a=sc.nextInt();
b=sc.nextInt();
if(a>=0 && b>=0){
...
//do the task
}
else{
while(a<0 || b<0){
System.out.println("negative value not allowed, enter +ve value ");
a=sc.nextInt();
b=sc.nextInt();
}
// while exited only if value both a and b are positive
//+ve value
//perform task
}

Counter won't work to end loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on an assignment and it is working well so far. But several aspects aren't working. For starters, my counters for int total and int counter won't work. Also my if statements don't seem to be working. I have been scratching my head for several days now.
The assignment calls for a program to input the order number and will loop based on how many orders the customer has. It also calls for customer name, sign type(wood or plastic), the number of characters,and color of characters.
Some more information:
The base price for all signs is $20.
If sign is wood, add $10. If it is plastic add $5.
The first 5 letters/numbers are included in base price, and $2 for each additional character.
Black or white characters are included in base price, there is an additional $8 for colored letters.
If the total charge is more than $100 give 25% discount on total price.
Here is my code right now:
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
System.out.println("Enter your order number");
orderNumber = sc.nextInt();
counter=orderNumber;
counter--;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
do{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
if(signType == "wood") {
i+=10;
}
if(signType == "plastic") {
i+=5;
}
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
if(color != "white" || color != "black") {
i += 8;
}
total= i;
System.out.println("Total is: $" + total);
if( total > 100 ) {
total = (total * 0.25);
System.out.println("The total is " + total );
}
}
while(counter <= orderNumber);
}
}
I added comments to guide you through the changes I made. Also, remember to call the sc.NextLine() function after you get user input so that they can input something different next time (this is called 'flushing' the buffer).
import java.util.Scanner;
public class Carpenter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int orderNumber;
String custName;
String signType;
int numOfCharacters;
String color;
int i = 20;
double total;
int counter;
//I changed the phrasing just because it is a little confusing
System.out.println("Enter your number of orders");
orderNumber = sc.nextInt();
counter = orderNumber;
sc.nextLine();
System.out.println("Enter customer name");
custName = sc.next();
sc.nextLine();
//When you know how many times you want to repeat something (like when a user tells you how many) I prefer using a for-loop, a do while loop works as well though
for(int x=0; x<counter;x++)
{
System.out.println("Enter the sign type (wood or plastic)");
signType = sc.next();
//When comparing Strings, there is a function that you can use to compare them rather than using '=='
// It is also good to use the 'equalsIgnoreCase()' function to be more user friendly and robust
if(signType.equalsIgnoreCase("wood")) {
i+=10;
}
if(signType.equalsIgnoreCase("plastic")) {
i+=5;
}
//Flush the buffer (I haven't tested if this is necessary or not, it is good practice though)
sc.nextLine();
System.out.println("Enter the number of characters");
numOfCharacters = sc.nextInt();
if(numOfCharacters > 5) {
i += 2*(numOfCharacters-5);
}
System.out.println("Enter the color of characters");
color = sc.next();
//Same concept as above, the differene is the ! before the function to test if it is false or not
if(!color.equalsIgnoreCase("white") || !color.equalsIgnoreCase("black")) {
i += 8;
}
}
total = i;
//You will not want to print this out until the end due to the possibility of it being over $100
// System.out.println("Total is: $" + total);
if( total > 100 ) {
//Mathematically speaking, you are making your total a quarter of what the original is, rather than taking a quarter off. You want 75% rather than 25%
// total = (total * 0.25);
total = (total * 0.75);
}
System.out.println("Total is: $" + total);
}
}
You should set counter to the correct starting value (which is presumably 1 in your case):
orderNumber = sc.nextInt();
counter=1;
//counter=orderNumber;
//counter--;
Then at the end of the loop, you should increment your counter:
do{
//code
counter++;
}
while(counter <= orderNumber);

Categories

Resources