I have a problem with my restaurant assignment - I'm required to
Create a while loop with a required quantity that user purchases to be between 1 and 15. User has 3 attempts and if after the third time he doesn't put the right quantity 1
Using a do- while loop user has to answer if he wants to run a program again. If he answers 'Y' (for yes) it runs again, if the answer is 'N' (for no ) it terminates.
I keep getting errors: the while loop does only 2 attempts, and the do while doesn't work at all.
import java.text.DecimalFormat;
import java.util.Scanner;
public class newone {
public static void main (String[] args){
char repeat;
// To hold 'y' or 'n'
String input;
DecimalFormat df = new DecimalFormat("$0.00");
//to use: df.format(doubleVariable)
//Display any welcome message at the top of the output screen
System.out.println("Welcome!");
double price = 5.0;
System.out.println("Burger is " + df.format(price));
Scanner keyboard = new Scanner(System.in);
int attempts = 0;
int maxAttempts = 3;
int quantity;
System.out.print("Enter amount of burgers: ");
quantity = keyboard.nextInt();
//LESS THAN OR EQUAL TO 3...
while(quantity <1 || quantity >=15 && attempts<=maxAttempts){
if(quantity < 1 || quantity >= 15){
System.out.println("That is an invalid amount, please try again");
quantity= keyboard.nextInt();
++attempts;
}
else if(quantity>1 && quantity<15){
//user entered a valid amount
System.out.println("The amount is valid. You ordered: "+ quantity);
double subTotal = quantity * price;
}
while (attempts>=maxAttempts){
System.out.println("Too many attempts, you can't order");
break;
}
}
do{
System.out.println("Would you like to run the program again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.nextLine(); // Read a line.
repeat = input.charAt(0); // Get the first char.
}
//it gives me an error Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
while (repeat == 'Y' || repeat == 'y');
}
}}
Below line causes the error:
repeat = input.charAt(0);
Perhaps user is not providing any inputs (i.e. user just hits enter when program asks for any input) and hence, string doesn't have any character. Extracting first character from blank string throws this error.
The solution will be to check for empty string (using length() method) before executing charAt(0).
You have lots of problems here.
Here's how I'd do it. It's never too early to learn about decomposition and writing clean, readable code:
/**
* Created by Michael
* Creation date 3/4/2016.
* #link https://stackoverflow.com/questions/35806509/java-while-do-while-loop-with-users-decision-to-run-program-again/35806638?noredirect=1#comment59284245_35806638
*/
import java.text.NumberFormat;
import java.util.Scanner;
public class BurgerKing {
public static final int MAX_ATTEMPTS = 3;
public static final int MIN_QUANTITY = 1;
public static final int MAX_QUANTITY = 15;
public static final NumberFormat PRICE_FORMAT = NumberFormat.getCurrencyInstance();
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
String answer;
do {
System.out.println("Welcome! Please place your order");
int quantity = getBurgerQuantity(keyboard);
double price = getBurgerPrice(keyboard);
System.out.println(String.format("Your total is: %s", PRICE_FORMAT.format(quantity*price)));
System.out.print("Another order? [Y/N]: ");
answer = keyboard.nextLine();
} while ("Y".equalsIgnoreCase(answer));
}
public static boolean isValidQuantity(int quantity) {
return (quantity >= MIN_QUANTITY && quantity =< MAX_QUANTITY);
}
public static int getBurgerQuantity(Scanner scanner) {
int numBurgers;
int attempts = 0;
do {
System.out.print("How many burgers would you like? ");
numBurgers = Integer.parseInt(scanner.nextLine());
} while (!isValidQuantity(numBurgers) && (++attempts < MAX_ATTEMPTS));
if (attempts == MAX_ATTEMPTS) throw new IllegalArgumentException(String.format("%d attempts is too many", attempts));
return numBurgers;
}
public static double getBurgerPrice(Scanner scanner) {
String price;
System.out.print("Name your burger price: ");
price = scanner.nextLine();
return Double.parseDouble(price);
}
}
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
This question already has answers here:
Variables in a do while loop
(5 answers)
Closed 1 year ago.
I am putting all my code into a do-while statement so it keeps looping until the user enters 3 to quit. For some reason when I close the do statement it doesn't see the variable userInput. I've tried changing so many things around and none of it works. So the issue is at while (userInput !=3); it throws userInput cannot be resolved to a variable
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
do {
Scanner in = new Scanner (System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
int userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger <= secondInteger) {
System.out.print(firstInteger + " ");
firstInteger++;
}
}else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
}
} while (userInput != 3);
}
}
userInput must be declared outside the loop for the while condition to see it.
Try this:
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
int userInput;
do {
Scanner in = new Scanner(System.in);
System.out.print("Please choose your choice from the following menu");
System.out.print("\n1) Print through all integer numbers between two given integers");
System.out.print("\n2) Display a right triangular pattern of stars");
System.out.println("\n3) Quit");
userInput = in.nextInt();
if (userInput == 1) {
System.out.print("Enter the start number: ");
int firstInteger = in.nextInt();
System.out.print("Enter the second number: ");
int secondInteger = in.nextInt();
while (firstInteger <= secondInteger) {
System.out.print(firstInteger + " ");
firstInteger++;
}
} else if (userInput == 2) {
System.out.print("Enter the height: ");
int triangleHeight = in.nextInt();
}
} while (userInput != 3);
}
}
userInput is defined inside the loop's block, so it's not accessible from outside it, including the loop's condition. One solution is to move the declaration out of it:
int userInput = -1;
do {
// code...
userInput = in.nextInt();
// more code...
} while (userInput != 3);
I am trying to make a sort of ATM. I want the program to do the following: If a user enters a number, the number gets multiplied by 12.
I already have the following code:
import java.util.Scanner;
public class DisplayMultiples {
public static void main(String args[]) {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
keyboardInput.nextLine();
int b = 12;
if() {
for (int i = 1; i < b; i++) {
System.out.println(i*b);
}
else {
System.out.println("Error, this value is never used");
}
}
}
Convert the input to a number.
If the input is not a number, show error message, and exit.
If the input is a number, multiply it by 12, show result, and exit.
The easiest way is to get an int from the Scanner and then check if it's between 1 and 12, and if so, multiply it by 12.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
int number = keyboardInput.nextInt();
if (number > 0 && number < 13) {
System.out.println(number * 12);
} else {
System.out.println("Error, this value is never used");
}
Note that as you are likely a beginner, entering anything but an int in the console will result in an error but I assume that's not entirely necessary for you. If it is, read up on try...catch.
This way will avoid exceptions when entering non numbers.
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Enter a number between 1 and 12 ");
String inpStr = keyboardInput.nextLine();
int b = 12;
int inpVal = -1;
try {
inpVal = Integer.parseInt(inpStr);
} catch (NumberFormatException nfe) {
}
if (inpVal >= 1 && inpVal <= 12) {
System.out.println(inpVal * b);
} else {
System.out.println("Error, this value is never used");
}
I'm trying to create a method that uses a while loop that includes a look ahead method to handle wrong user input: input out of 1-10 range or input a string. I am trying to do this with out throwing exceptions or using try{}catch{}; if possible. I haven't found a post that does not use these and all my attempts have failed so far. A basic idea will work.
will not stop if input is correct
import java.util.*;
public class UserErrors{
public static Scanner console = new Scanner(System.in);
public static void main(String[]args){
String s = "Enter a integer between 1-10: ";
get(s);
}
public static int get(String prompt){
System.out.print(prompt);
while(console.hasNext()){
while(!console.hasNextInt()){
console.next();
System.out.println("Invalid data type");
System.out.print(prompt);
}
if(console.nextInt() > 10 || console.nextInt() <1){
System.out.println("not in range");
System.out.print(prompt);
}
}
return console.nextInt();
}
}
requires the right answer to be imputed 3 times before it stops
import java.util.*;
public class UserErrors{
public static Scanner console = new Scanner(System.in);
public static void main(String[]args){
String s = "Enter a integer between 1-10: ";
get(s);
}
public static int get(String prompt){
System.out.print(prompt);
boolean b = false;
while(!b){
if(!console.hasNextInt()){
console.next();
System.out.println("Invalid data type");
System.out.print(prompt);
console.nextInt();
}
else if(console.nextInt() < 10 && console.nextInt() >1){
b = true;
}
else{
System.out.println("not in range");
System.out.print(prompt);
console.nextInt();
}
}
return console.nextInt();
}
}
I deleted some other failed attempts too. What do I need to fix (basic idea will do)?
There's an error:
if(console.nextInt() > 10 || console.nextInt() <1){ ... }
change this line to:
int i = console.nextInt();
if(i > 10 || i <1){ ... }
You can not reuse console.next...() just like that :)
Each nextInt call is a blocking call and it waits for user input.
For your code when you write below line:
if(console.nextInt() < 10 && console.nextInt() >1)
Essentially the console waits for first user input, checks it against 10 and then waits for next input which could be any (which you type second), not necessarily the same, waits for that and then finally enters the if condition.
The console input should always be taken upfront and assigned to our local variable and then it needs to be checked for your conditions like below:
int userInput = console.nextInt();
then the checking goes below with the userInput variable:
if(userInput < 10 && userInput >1)
The method nextInt() of the Scanner class read the standard exit
import java.util.*;
public class UserErrors{
public static Scanner console = new Scanner(System.in);
public static void main(String[]args){
String s = "Enter a integer between 1-10: ";
get(s);
}
public static int get(String prompt){
boolean b = false;
int number;
while(!b){
System.out.print(prompt);
if(!console.hasNextInt()){
console.next();
System.out.println("Invalid data type");
System.out.print(prompt);
console.nextInt();
}else {
number = console.nextInt();
if(nb<1 || nb>10){
System.out.println("not in range");
}else{
b=true;
}
}
}
return nb;
}
}
I'm having trouble with an assignment that I'm working on. Here is the prompt:
Create a DigitExtractor application that prompts the user for an integer (in the range: 0-999) and then displays either the ones, tens, or hundreds digit of the number. The user will select from a menu which digit they wish to display.
This program needs to be written as a class. The menu will be your driver program that you submit with the class so your instructor can use it to test the class.
Here is my code for it:
import java.io.*;
import java.util.*;
public class TestingMenu
{
public int number;
public int units;
public int tens;
public int hundreds;
public TestingMenu(int input)
{
number = input;
units = number%10;
tens = number%10;
hundreds = number%10;
}
public int return_units()
{
return units;
}
public int return_tens()
{
return tens;
}
public int return_hundreds()
{
return hundreds;
}
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
TestingMenu num;
int choice;
int input;
do
{
System.out.print("Enter a number(0-999): ");
input = kbReader.nextInt();
System.out.println("");
System.out.println("Options");
System.out.println("1) Units");
System.out.println("2) Tens");
System.out.println("3) Hundreds");
System.out.println("4) Quit");
num = new TestingMenu(input);
System.out.print("Enter your choice: ");
choice = kbReader.nextInt();
switch(choice)
{
case 1:
System.out.println("The units digit is: " + num.return_units());
break;
case 2:
System.out.println("The tens digit is: " + num.return_tens());
break;
case 3: System.out.println("The hundreds digit is: " + num.return_hundreds());
break;
case 4:
System.exit(4);
break;
default:
System.out.print("Invalid. Select a number from the given options.");
choice = kbReader.nextInt();
}
}
while(choice != 4);
}
}
I think I've almost got it, but I'm having issues whenever I test it. When I input a number such as 987 and I run all the options from 1-3, I keep getting 7 for the ones, tens, and hundreds. 4 exits the program and works okay, but I've tested this numerous times. Overall, it seems to only print the last digit.
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 1
The units digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 2
The tens digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 3
The hundreds digit is: 7
Enter a number(0-999): 987
Options
1) Units
2) Tens
3) Hundreds
4) Quit
Enter your choice: 4
Could someone help me identify the error? I don't really know what went wrong with this program despite working on it for a few hours. Thanks in advance. All the help and feedback is greatly appreciated.
You had a few issues, I would suggest you review this very carefully -
// Why make them public?
private int units = 0;
private int tens = 0;
private int hundreds = 0;
public TestingMenu(int input) {
// Convert it to a String.
String str = String.valueOf(input);
if (str.length() == 1) {
// ones and only ones.
units = Integer.parseInt(str);
} else if (str.length() == 2) {
// tens and ones.
tens = Integer.parseInt(str.substring(0, 1));
units = Integer.parseInt(str.substring(1, 2));
} else if (str.length() == 3) {
// hundreds, tens and ones.
hundreds = Integer.parseInt(str.substring(0, 1));
tens = Integer.parseInt(str.substring(1, 2));
units = Integer.parseInt(str.substring(2, 3));
}
}
// Just use get, PLEASE!
public int getUnits() {
return units;
}
public int getTens() {
return tens;
}
public int getHundreds() {
return hundreds;
}
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
try {
TestingMenu num;
int choice;
do {
System.out.print("Enter a number(0-999): ");
num = new TestingMenu(kbReader.nextInt());
System.out.println("");
System.out.println("Options");
System.out.println("1) Units");
System.out.println("2) Tens");
System.out.println("3) Hundreds");
System.out.println("4) Quit");
System.out.print("Enter your choice: ");
choice = kbReader.nextInt();
if (choice == 1) {
System.out.println("The units digit is: "
+ num.getUnits());
} else if (choice == 2) {
System.out.println("The tens digit is: "
+ num.getTens());
} else if (choice == 3) {
System.out.println("The hundreds digit is: "
+ num.getHundreds());
} else if (choice != 4) {
// We want 4 to fall through and terminate the loop.
System.out.print("Invalid. Select a number "
+ "from the given options.");
choice = kbReader.nextInt();
}
} while (choice != 4);
} finally {
// close the Scanner.
kbReader.close();
}
}
What I would do is I would is I would use your Scanner to take input as a string so you can use .length() to get the length and .charAt() to display them...remember that charAt is like arrays in that the indexes start from 0, length does not. If you need them to be ints you can use Integer.parseInt() (be sure to check it is a number before trying this cause it will throw an exception but with a boolean and a try catch you can continue to ask users for input until they get it right like this
boolean notComplete = true;
while(notComplete = true){
try{ userinput = //get input somehow
Integer.parseInt(userinput);
//do whatever
boolean complete = true;
}catch(NumberFormatException e){
//get input and repeat it will keep trying until the boolean is updated
}})
But for this I don't think it matters how you keep it as long as you display it. You could also add an array of Strings that have indexs that correspond to what they are...meaning something like this:
String[] s = {"ones", "tens", "hundreds"};
so that when the user says 1, 2 or 3 to pick what should be displayed you can subtract one call .charAt on the string to display the number and print the index of the array s at the same index to tell the user what it is.