Reset Values in ArrayList Nested in While Loop - java

I wrote code to store the values of user-inputted dollar amounts. Whenever the program prompts the user, "would you like to input items - y/n?" the user can then put in values stored in an ArrayList.
The initial prompt is below. It seems to work as I am able to put in values with no visible errors.
System.out.print("Would you like to input item/s - y/n: ");
String response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
But when I go to put in values a second time, I notice the program doesn't clear out the values from my first entry. The code I wrote to prompt the user for another cluster of values is identical to the code I wrote for the initial prompt. I nested these second prompt in a while loop triggered by the user selecting "y" to the initial prompt.
while ((response.equalsIgnoreCase("y")))
{
System.out.print("Please enter an item price, or -1 to exit: $");
double values = numberReader.nextDouble();
while ((values > (-1)))
{
cartItems.add(values);
System.out.print("Please enter another item price, or -1 to exit: $");
values = numberReader.nextDouble();
}
System.out.println();
System.out.println("********** Here are your items **********");
// I omitted the code here to make this more concise.
// prompt the user to input a second round of values
System.out.print("Would you like to input item/s - y/n: ");
response = textReader.nextLine();
System.out.println();
// create while loop to restrict responses to single characters
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
}
My output is below. When I am prompted a second time, I select 'y' to add more items. However, my newly added item $3.00, gets added to the list from the first prompt. Is there anyway to refresh or erase the ArrayList so that it is brand new each time the user wants to input new values?

cartItems.clear();
put it at the end of the loop, after the results are printed to the console.
It will refresh the list and remove all the elements within it.

In no place you are resetting the ArrayList.
You can call cartItems.clear() when you are done with your processing and you are looping for a next round (at the bottom of the outter while).
...
while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n")))
{
System.out.print("Sorry - we need a y/n: ");
response = textReader.nextLine();
System.out.println();
}
cartItems.clear();
}

Create instance of list in the while loop
List<Double> cartList = new ArrayList<Double>();
So now everytime user selects yes, the program enters in the while loop and then a new instance of list is created without any values. If you want to store the values in the previous list, write it to a persistence storage like file or database before creating a new instance of list.
Alternatively, you can also use
cartList.clear();
But, i don't recommend doing so.It can give you junk values and takes more amount of time. The clear method basically iterates over all the elements of list and does them null like this.
for(int i = 0; i < cartList.size(); i++){
cartList.get(i) = null;
}

Related

Issue with some simple exception handling using .hasNextInt() in Java?

I'm creating an array list for a menu of food items which correspond to a number on a menu. Most of that is left out: my main issue is that the error message does not display for the first time the user does not enter an integer value. Nothing will show on the console after I press enter, but if I again enter something that isn't an integer it will work like it should and display the error message.
Edit: something else I should note is that earlier in the code I use the same scanner object so use .next() to clear it of the previous value it had.
orderArray = new String[length];
menuDisplay();
int item; //the item number that user must enter
for(int i=1; i<=length;i++)
{
System.out.println("Please choose item #"+ i+": ");
scan.next();
while(!scan.hasNextInt()) //this while loop checks that an integer value has been entered
{
System.out.println("Please enter an integer value from the above menu.");
scan.next();
}
}
The hasNextInt check the next token, not the token just received, so always call hasNextXxx() before calling nextXxx().
You'd also want to actually get the integer value and assign it to item.
Rearrange your code like this:
System.out.println("Please choose item #"+ i+": ");
while (!scan.hasNextInt()) //this while loop checks that an integer value has been entered
{
System.out.println("Please enter an integer value from the above menu.");
scan.next(); // skip bad token
}
item = scan.nextInt();

I need to get my Java program to start back at the beginning after an invalid input

I'm currently working on an assignment for school and I am almost done but I just have one large problem I need to fix before I can add the final bit.
I need to create a program that prompts you to enter either 1 or 2, Afterwards it asks you to enter three words/names and saves them into an array.
Then, depending on whether you picked 1 or 2, it prints them in alphabetical order or flips around the lowercase and uppercase letters. I didn't add that part yet because I'm trying to fix a problem related to the very first input.
When you input a number other than 1 or 2, I am instructed to display an error message and ask for input again. I am pretty sure what I need to do is get the entire program to go back to the beginning because copy/pasting the entire program again would be bad, lol
A big problem is probably that I'm using if/else statements with for loops inside when I might need to put the entire thing inside a loop? But I'm not sure what condition I would use to start the loop if I put the entire code in it. I must be missing something here.
With what I have now, it gets stuck saying invalid input even if you put in a 1 or 2.
import java.util.Scanner;
public class IsabellaPiantoniLab5 {
public static void main (String[]args) {
//Ask for input
Scanner input = new Scanner(System.in);
System.out.print("Please choose either a number 1 or number 2.");
int numChoice = input.nextInt();
//if choice is 1 or 2
if (numChoice == 1 || numChoice == 2) {
System.out.println("Please enter three names: ");
String nameInput[] = new String[4];
//input loop
for (int i= 0; i < nameInput.length; i++) {
nameInput[i] = input.nextLine();
}
System.out.println("Values are:");
//display values if 1
if (numChoice == 1) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
//display values if 2
else if (numChoice == 2) {
for (int i=1; i<4; i++) {
System.out.println(nameInput[i]);
}
}
}
//retry if invalid------i restart from the beginning if this happens
else if (numChoice != 1 || numChoice != 2) {
System.out.println("Invalid value. Please try again.");
//continue;
}
}
}
System.exit(0);
This will terminate the app, thus you can start it again using command line ( START [your app path])
Or
RunTime.getRuntime().exec(“Your app”);
System.exit(0);
Edit I misunderstood the question, I thought you wanted to restart the whole app
After discussing the approach with #csm_dev
It is way either to ask for the user input one more time by emptying the field and showing a message “please enter a valid input” with a clarification message

user input within while loop

I was asked to run a loop that asks for user input, applies the change using the adjustPrice() method, print the new information after adjusting the price. and then finishes the loop when the user enters 0.
Right now it does all of the above, just doesn't ask for the user input again and ends with the printed new information. please help!
boolean done = false;
while (!done) {
System.out.print("Enter adjustment to price in percent (0 to quit): ");
double adjustment = in.nextDouble();
if (adjustment == 0) {
done = true;
}else{
swag.adjustPrice(adjustment);
System.out.println(swag.toString());
in.next();
}
}
You have in.next() at the end. This expects the user to input something before the loop will reset to the System.out line. Take out that line.
to allow user input using the end
else {
swag.adjustPrice(adjustment);
System.out.println(swag.toString());
in.next();
}
but beware that this method does not take keys as enter or space to
take into account these keys use.
else {
swag.adjustPrice(adjustment);
System.out.println(swag.toString());
System.in.read();
}

Breaking up a single user input and storing it in two different variables. (Java)

I'm very new to programming, especially Java. I need to create a program that counts how many orders each entry at a restaurant gets ordered. The restaurant carries 3 entries, hamburgers, salad, and special.
I need to set up my program so that the user inputs, say, "hamburger 3", it would keep track of the number and add it up at the end. If the user inputs "quit", the program would quit.
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
I'm thinking about using a while loop, setting it so if the user input != to "quit", then it would run.
What's difficult for me is I don't know how to make my program take into account the two different parts of the user input, "hamburger 3" and sum up the number part at the end.
At the end, I want it to say something like "You sold X hamburgers, Y salads, and Z specials today."
Help would be appreciated.
You'll probably want three int variables to use as a running tally of the number of orders been made:
public class Restaurant {
private int specials = 0;
private int salads = 0;
private int hamburger = 0;
You could then use a do-while loop to request information from the user...
String input = null;
do {
//...
} while ("quite".equalsIgnoreCase(input));
Now, you need some way to ask the user for input. You can use a java.util.Scanner easily enough for this. See the Scanning tutorial
Scanner scanner = new Scanner(System.in);
//...
do {
System.out.println("Enter the type (special, salad, or hamburger) of entrée followed by the number, or quit to exit the program.");
input = scanner.nextLine();
Now you have the input from the user, you need to make some decisions. You need to know if they entered valid input (an entree and an amount) as well as if they entered an available option...
// Break the input apart at the spaces...
String[] parts = input.split(" ");
// We only care if there are two parts...
if (parts.length == 2) {
// Process the parts...
} else if (parts.length == 0 || !"quite".equalsIgnoreCase(parts[0])) {
System.out.println("Your selection is invalid");
}
Okay, so we can now determine if the user input meets or first requirement or not ([text][space][text]), now we need to determine if the values are actually valid...
First, lets check the quantity...
if (parts.length == 2) {
// We user another Scanner, as this can determine if the String
// is an `int` value (or at least starts with one)
Scanner test = new Scanner(parts[1]);
if (test.hasInt()) {
int quantity = test.nextInt();
// continue processing...
} else {
System.out.println(parts[1] + " is not a valid quantity");
}
Now we want to check if the actually entered a valid entree...
if (test.hasInt()) {
int quantity = test.nextInt();
// We could use a case statement here, but for simplicity...
if ("special".equalsIgnoreCase(parts[0])) {
specials += quantity;
} else if ("salad".equalsIgnoreCase(parts[0])) {
salads += quantity;
} else if ("hamburger".equalsIgnoreCase(parts[0])) {
hamburger += quantity;
} else {
System.out.println(parts[0] + " is not a valid entree");
}
Take a look at The if-then and if-then-else Statements and The while and do-while Statements for more details.
You may also find Learning the Java Language of some help. Also, keep a copy of the JavaDocs at hand, it will make it eaiser to find references to the classes within the API
These two methods should be what you're looking for.
For splitting: String.split(String regex)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
For parsing String into an Interger: Integer.parseInt(String s)
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
You can split your strings using input.split(" "). This method gives you two strings - two parts of the main string. The character you splitted with (" ") won't be found in the string anymore.
To then get an integer out of your string, you can use the static method Integer.parseInt(inputPartWithCount).
I hope this helps!

Creating a simple sales calculator in Java code

I'm trying to figure out how to write this?
Write a Java program that will serve as a basic sales calculator. The program should present the user with a choice of four different products of your choosing in a simple menu. After the user selects a product by entering a character corresponding to a product, the program should prompt the user for the quantity and then calculate the Subtotal, Sales Tax Amount, and Total Sale Amount. The calculations should be performed as follows:
Subtotal = (Price * Quantity)
Sales Tax Amount = Subtotal * Sales Tax Percentage (use 6.5% for the sales tax percentage)
Total Sale Amount = Subtotal + Sales Tax Amount
Be sure to use variables to store temporary values. The program should output the product sold, quantity sold, and the calculated values for Subtotal, Sales Tax Amount, and Total Sale Amount. Your assignment submittal should include your java code which is properly commented, and the class file..
this is what i have so far and not sure if I am on the right track?
import java.util.scanner;
public class Sales //Defines the class
Public static void main (String args[]){
System.out.println("Welcome to Super Shopper");
System.out.println("1) Star Wars DVD");
System.out.println("2) X-box 360 ");
System.out.println("3) I-Pad 3");
System.out.println(“4) 2 liter Soda”);
System.out.println("5) Quit");
Scanner sc = new Scanner (System.in);
System.out.print("Please select item :");
int choice = keyword.nextInt();
Scanner number = new scanner (System.in);
System.out.print("Please select quantity :");
Int choice = quantity.nextInt();
String userInput;
}
}
Since this is a homework question, I won't be providing you with the answer to your problem, but hopefully I will be able to help you in figuring out how to structure your program, as well as explain how to use the Scanner class to gather input from the user. The rest will be up to you.
First you will need to develop the pseudo-code for your main program. Basically a flow of execution based on the events that should happen.
pseudo-code is NOT code that will compile, but is useful in figuring out the structure of a program. Here is the pseudo code for your program.
show greeting with choices.
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
restart program
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
show exit message and exit program
if choice is invalid
show error message and restart program
Notice that upon successful completion of getting the total cost of a purchase, we "restart the program". If you were more advanced, this might entail calling a function, but my guess is that you are still a beginner, so doing the same thing more than once should remind you of a loop. In this case a while loop.
Thus we can rewrite this pseudocode to the following
done = false
while not done
get choice from user
if choice is valid and choice is not exit
prompt user for quantity
if quantity is valid
calculate total and show it to the user
if quantity is invalid
prompt user for a valid quantity again
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
Now, notice how when the user inputs an invalid quantity (ie: Something that is not an integer > 1) we ask for a quantity AGAIN. Doing the same thing multiple times? That's right, that means we should probably use another while loop again.
For this second while loop, the basic thinking is, "keep asking the user for a quantity until we have a valid quantity". The simplest way to accomplish this, is to create a boolean variable we call haveQuantity, and loop until that value is true.
Our pseudo-code now becomes:
done = false
while not done
get choice from user
if choice is valid and choice is not exit
haveQuantity = false
while not haveQuantity
prompt user for quantity
get quantity from user
if quantity is valid
haveQuantity = true
calculate total and show it to the user
if choice is valid and choice is exit
done = true
if choice is not valid
show error message
exit program
This should be the general structure of your program. In the following section, I will show you how to properly use the scanner class to get input from the user.
public class EchoInt
{
import java.util.Scanner;
public static void main(String[] args)
{
//Declaration of variables outside the while loop
Scanner scan = new Scanner(System.in); //declaring variables outside of a loop saves space and speeds up execution as the jvm does not need to reallocate space for an object inside the loop.
boolean done = false; //this will be our conditional for the while loop
int input = -1;
while(!done) //while done is equal to false.
{
System.out.println("Please enter a positive int to echo or 0 to exit: ");
if(scan.hasNextInt()) //If the user has inputted a valid int
input = scan.nextInt(); //set the value of input to that int.
else //The scanner does not have a integer token to consume
{
/*
THIS IS IMPORTANT. If the scanner actually does have a token
which was not an int. For example if the user entered a string,
you need to consume the token to prepare to accept further tokens.
*/
if(scan.hasNext())
scan.next(); //Actually consumes the token
input = -1; //This is used to indicate that an invalid input was submitted
}
if(input == 0) //The user chose to exit the program
done = true; //set done to true to kick out of the while loop
else if(input == -1) //This means the user inputed an invalid input
System.out.println("ERROR! Try again."); //show error message
else //The user inputted valid input
System.out.println("echo: "+input); //Echo the int
}
scan.close(); //We are done, so close the scanner
System.out.println("Exiting. Goodbye!"); //Show a goodbye message
System.exit(0); //exit the program. The zero tells us we exited without errors.
}
}
Hope this helps. And feel free to ask more questions.
Stackoverflow really excels when you have a very specific question to ask. As for your requirements, you are asking the user for input thats good. But you are not mapping items to prices or quantities. You are hardcoding in the items position ie "3) I-Pad 3" which will make it harder to get the actual item name later and match it to it's price.

Categories

Resources