Counter won't work to end loop [closed] - java

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

Related

How to set integer range in Scanner? [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 1 year ago.
Improve this question
I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.
Below is the code, I have tried: -
package com.company;
import java.util.*;
public class CbseCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of Physics");
float physics = sc.nextFloat();
System.out.println("Enter marks obtained of Chemistry");
float chemistry = sc.nextFloat();
System.out.println("Enter marks obtained of Math");
float math = sc.nextFloat();
System.out.println("Enter marks obtained of English");
float english = sc.nextFloat();
System.out.println("Enter marks obtained of Computer Science");
float computer = sc.nextFloat();
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained/total)*100;
System.out.println("The percentage obtained is: "+percentage);
sc.close();
}
}
It is not a good idea to try to get Scanner to do that1.
Instead, you should use Scanner to read an int and then test the result that it gives you to check that it is in the correct range. Something like this:
int number;
if (myScanner.hasNextInt()) {
number = myScanner.nextInt();
if (number < 0 || number > 100) {
// handle case where the number is out of range
}
} else {
// handle case where the input is not an integer
}
I will leave it to you to figure out how to map the above onto your application's requirements.
1 - The standard Scanner class doesn't provide a method that reads a number in a given range (and rejects numbers outside of that range). You could conceivably extend the Scanner class with this functionality, but it would be difficult. There are simpler solutions.
I would suggest you to write a function to get a valid input as below :-
public int getValidInput(Scanner in, int range) {
while (in.hasNext()) {
if (in.hasNextInt()) {
int val = in.nextInt();
if (val >= 0 && val < range) { // <-- from "0" to "range".
return val;
}
} else {
in.next();
}
}
return -1;
}
This function is ensuring that the input is given as an integer only and it lies in the range o to range. You can change it as per your requirement.
Consider this method:
static int getMark(String course){
int mark = 0;
boolean valid = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of " + course + ": ");
while(valid){
mark = sc.nextInt();
if(mark < 0 || mark > 100){
System.out.println("Mark must be between 0-100");
} else {
valid = true;
}
}
sc.close();
return mark;
}
This way you can get two birds with one stone, leaving the resulting code as this:
public static void main(String[] args){
int physics = getMark("Physics");
int chemistry = getMark("Chemistry");
int math = getMark("Math");
int english = getMark("English");
int computer = getMark("Computer Science");
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained / total) * 100;
System.out.println("The percentage obtained is: " + percentage);
}

How do I convert my while loop to a for loop?

I am a beginner coder using Netbeans Java. I have created a code that initially asks how many gallons are in your gas tank. Then, it will have a while loop asking how many miles you will be traveling for this first run and how fast are you traveling. This will repeat with a while loop until you input '0' to stop adding trips. I am stumped on how to convert this while loop into only using For loops. I would greatly appreciate the assistance. Here is my code that has while loops.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tank;
double miles;
double speed;
double totalMiles = 0.0;
int choice;
double time;
double totalTime = 0.0;
double fuelConsumption;
System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
tank = input.nextInt();
System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");
System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
choice = input.nextInt();
while (choice == 1)
{
System.out.print("How many miles are you traveling? "); // miles
miles = input.nextFloat();
System.out.print("What is your speed for this run (MPH)? "); // speed
speed = input.nextInt();
System.out.print("\n");
totalMiles = totalMiles + miles;
time = (miles/speed);
totalTime += (time*60);
fuelConsumption = (20*(tank/totalMiles));
System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? "); // asking another leg
choice = input.nextInt();
if (choice == 0)
{
System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
+ "You traveled a total of about ", totalMiles , " miles.");
System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");
if (fuelConsumption >= 2)
{
System.out.println("Your car has enough gas to return.");
break;
}
else
{
System.out.println("Your car will need more gas to return.");
break;
}
}
}
}
}
That is not a use case for a for loop, where we iterate over a known number of elements for do a known number of iterations. Like, repeat 10 times or such.
Technically it can be solved with a for loop, but that is abusing the concept a bit. The while loop is a perfect fit for that task.
This is not a place to use a for-loop, you use a for loop for something like this:
printAmount = 10;
for (int i = 0; i < printAmount; i++) {
System.out.println("Hello World");
}
Here you are using the for loop to print "Hi" for the amount in printAmount.
Your case is different: You want the while-loop to repeat while the input is "1" so you use a WHILE-loop.

my program doesn't run completely [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 7 years ago.
Improve this question
For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.
import java.util.Scanner;
public class GradeCalculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner grade = new Scanner (System.in);
// A new scanner must be created. The scanner is essential to this program performing properly.
double A = 90-100;
double B = 80-89;
double C = 70-79;
double D = 60-69;
double F = 0-59;
String LetterGrade;
String yes;
String no;
double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
double knownWeight;
double PercentageWeights;
// As always, the variables must be declared at the beginning of the program.
System.out.print(
"Grading Scale:\n"+
"A = 90-100 \n"+
"B = 80-89 \n"+
"C = 70-79 \n"+
"D = 60-69 \n"+
"F = 00-59 \n");
System.out.println("What letter grade do you want to achieve in this course?");
LetterGrade = grade.next();
// The user will type the letter grade that it wants in this part.
System.out.println("\nEnter Percentage Weights: \t");
String input = grade.nextLine();
// The string above is needed when the user enters the exam grades and averages.
System.out.print("\n\nExam 1: \t");
Exam1 = grade.nextShort();
System.out.print("\nExam 2: \t");
Exam2 = grade.nextShort();
System.out.print("\nFinal Exam: \t");
finalExam = grade.nextShort();
System.out.print("\nLabs: \t");
Labs = grade.nextShort();
System.out.print("\nProjects: \t");
Projects = grade.nextShort();
System.out.print("\nAttendance: \t");
Attendance = grade.nextShort();
System.out.print("\nQuizzes: \t");
Quizzes = grade.nextShort();
PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);
// The equation above will provide the sum of the percentage weights. Since the variables in the equation were
// originally declared as doubles, I had to put "int" before the actual equation.
if (PercentageWeights > 100 || PercentageWeights < 100) {
System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
System.exit(0);
}
else {
System.out.println("\nEnter your scores out of a 100: \t");
}
// The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100,
// the program will continue to run. If the sum is greater than or less than 100, the program will terminate.
System.out.print("\nDo you know your Exam 1 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 1: ");
Exam1Grade = grade.nextDouble();
}
else{
Exam1Grade = 0;
}
System.out.print("\nDo you know your Exam 2 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 2: ");
Exam2Grade = grade.nextDouble();
}
else{
Exam2Grade = 0;
}
System.out.print("\nDo you know your final exam score?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nScore received on final exam: ");
finalExamGrade = grade.nextDouble();
}
else{
finalExamGrade = 0;
}
System.out.print("\nDo you know your lab average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage lab grade: ");
LabAverage = grade.nextDouble();
}
else{
LabAverage = 0;
}
System.out.print("\nDo you know your project average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage project grade: ");
ProjectsAverage = grade.nextDouble();
}
else{
ProjectsAverage = 0;
}
System.out.print("\nDo you know your quiz average?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nAverage quiz grade: ");
QuizzesAverage = grade.nextDouble();
}
else{
QuizzesAverage = 0;
}
System.out.print("\nDo you know your attendance average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage Attendance Grade: ");
AttendanceAverage = grade.nextDouble();
}
else{
AttendanceAverage = 0;
}
// The user has finished answering the questions. Now the program will automatically calculate the data based on
// what the user typed into the program.
double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade;
// The doubles above need to be declared in order for the equations below to work properly.
WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));
CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));
knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);
if (grade.equals(A)){
finalOverallGrade = 90;
}
else if (grade.equals(B)){
finalOverallGrade = 80;
}
else if (grade.equals(C)){
finalOverallGrade = 70;
}
else if (grade.equals(D)){
finalOverallGrade = 60;
}
else
finalOverallGrade = F;
avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));
// The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade.
// If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.
if (finalOverallGrade >= 90){
System.out.print("Congratulations! You got an A in the class! Hooray!");
}
else if (finalOverallGrade >=80 && finalOverallGrade < 90){
System.out.print("Good job. You got a B in the class!");
}
else if (finalOverallGrade >=70 && finalOverallGrade < 80){
System.out.print("You got a C in the class.");
}
else if (finalOverallGrade >=60 && finalOverallGrade < 70){
System.out.print("You got a D in the class.");
}
else
System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
}
}
There are quite a lot of things wrong with this code.
Doing double A=90-100; will set A equal to -10;
However, for your current question:
You do String input = grade.nextLine();
You never change input, and so if input isn't "yes", it will just skip getting the grades for each piece.
(You might want to also consult Using scanner.nextLine() for other pitfalls with using scanner.nextLine() intermixed with scanner.nextInt or similar [in summary: if you do scanner.nextInt, this doesn't consume the newline, so scanner.nextLine() will just get that newline and not the next line after that you might be expecting to get])
input = grade.nextLine() reads the remainder of the line with the user's "percentage weights" input on it. So unless the user had a priori knowledge to enter "yes", input will be empty.
I.e., you need to update input with user input before if (input.equalsIgnoreCase("yes")) {....

Java Tip Calculator for newbie

I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;

How do I make my program continue only if the user enters certain values?

My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, e.g. 0.82 the program still runs. How do I get it to only accept one of my options?
import java.util.Scanner;
public class VendingMachine
{
public static void main (String[] args)
{
double price;
Scanner keyboard = new Scanner(System.in);
System.out.println("Choose your price. Your options are: ");
double i;
for (i=0.25; i<=1.25; i+=0.25)
System.out.printf("$%.2f\n", i );
System.out.println("Enter your selection now: ");
price=keyboard.nextDouble();
System.out.printf("You chose the $%.2f option. ",price);
double deposit;
if (price<=1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit=1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit=2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit-price;
System.out.printf("Your change is $%.2f\n",change);
}
}
I tried something like this but it doesn't work. What is the best way to do this.
if (price==i)
System.out.println("You entered " + price);
else {
System.out.println("Invalide choice. Please try again.")
System.exit(0);
}
Here is an image if you find it easier to read.
You can use some sort of loop (while, do-while, for), which will continue to excecute the code until a condition is (or isn't) met.
Here is an example:
do {
code line 1;
code line 2;
code line 3;
...
} while(yourCondition);
If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false). yourCondition could be any expression that returns a true/false result (boolean), such as 2+2==4.
If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition).
Now, if you understood how that works, you can easily apply it to your code.
If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.
//given you an open scanner
boolean isCorrectPrice = false;
System.out.println("enter price");
price = in.nextDouble();
while(!isCorrectPrice)
{
if(price%0.25==0 && price<=1.25 && price>0)
{
System.out.println("you entered "+price);
IsCorrectPrice = true;
continue;
}
System.out.println("incorrect price, re-enter ");
price = in.nextDouble();
}
//your code after user enters correct price
That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.
Use BigDecimal (instead of double) to work with money. Its exact -- double isn't.
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
I would write a function to get the user input. It would not return until the
user had entered an allowed value.
Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.
import java.util.Scanner;
public class VendingMachine {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose your price. Your options are: ");
for (double i = 0.25; i <= 1.25; i += 0.25) {
System.out.printf("$%.2f\n", i);
}
double price = checkMultipleValues(0.25,1.25, 0.25);
System.out.printf("You chose the $%.2f option. ", price);
double deposit;
if (price <= 1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit = 1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit = 2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit - price;
System.out.printf("Your change is $%.2f\n", change);
}
private static double checkMultipleValues(double initial,double last,double step) {
System.out.println("Enter your selection now: ");
double price = keyboard.nextDouble();
for (double i = initial; i <= last; i += step) {
if (price == i) {
return price;
}
}
return checkMultipleValues( initial, last, step);
}
}
ADDENDUM
Since you like #Sello answer why don't you combine it with #MrD and have something like
do {
System.out.println("enter price");
price = in.nextDouble();
// System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));

Categories

Resources