Do / While Loop Verification - java

I'm using javax.swing.JOptionPane.
I need the user to enter in the product number, revenue, and expenses.
I need to validate the information to make sure that the revenue is between 0 and 20000 and verify that the expenses are between 1500 and 10000. I need to make sure that if they enter in an invalid revenue or expense it prompts them, and not allow the program to continue.
The program needs to be able to determine if there was a net profit, loss, or break even.
The user has to have the option of entering multiple records. Also, I need to count how many times the user entered in the information.
I feel like I was able to knock out a big chunk of the code.
When the user inputs an invalid revenue or expense, it keeps looping the messages and doesn't return to the ability to enter in the values again.
I also am not sure how I am going to get the user to input "Y" to loop the entire program again.
Can anyone lend me some assistance please?
/**
* The program will output the Product Number, Revenue, Expenses, as well as the Net Income
*/
import javax.swing.JOptionPane;
import java.io.*; // Access System.out
import java.util.Scanner;
public class RevenueJopt
{
public static void main(String[] args)
{
// Declarations
double finalValue;
char repeat;
int counter = 1;
String input;
Scanner keyboard = new Scanner(System.in);
// Do Loop to run
do{
// Advise the user the conditions that have to be met for inputs
JOptionPane.showMessageDialog(null,"Please ensure that your revenue is between 0 to 20,000.00 dollars." +
"\nPlease ensure that your expenses are between 1,500.000 to 10,000.00 dollars.");
// Ask user the values of the variables
String response = JOptionPane.showInputDialog(null, "Enter in a Product Number(or -1 to END)");
String response1 = JOptionPane.showInputDialog(null, "Enter the Revenue?");
String response2 = JOptionPane.showInputDialog(null, "Enter the Expenses?");
// Read in values
int productNumber = Integer.parseInt(response);
float revenue = Float.parseFloat(response1);
float expenses = Float.parseFloat(response2);
//While loop to Validate Information
while(revenue < 0 || revenue > 20000 || expenses < 1500 || expenses > 10000) {
JOptionPane.showMessageDialog(null,"You have entered in either an invalid revenue or expense. Please enter in valid numbers.");
{
JOptionPane.showMessageDialog(null,"Here is the product number you entered: " + productNumber + "."
+ "\nHere is the revenue you entered: " + revenue + "."
+ "\nHere are the expenses you entered: " + expenses + ".");
JOptionPane.showMessageDialog(null,"Enter in a Product Number (or-1 to END)"
+ "\nEnter the Revenue"
+ "\nEnter the Expenses");
//When this part runs, it goes into an infinite cycle. I am not sure how to break free of this.
counter++;
//calculates final value
}
}
finalValue = revenue - expenses;
// Calculates final value and displays as net profit, loss or break even.
if (finalValue > 0) {
JOptionPane.showMessageDialog(null, "You made a profit. Your net income is: "+finalValue);
} else if (finalValue == 0) {
JOptionPane.showMessageDialog(null, "You broke even. Your revenue was "+ revenue +" your expenses were " +expenses);
} else if (finalValue < 0) {
JOptionPane.showMessageDialog(null,"You have not made any profit. Your net loss is: "+finalValue);
}
JOptionPane.showMessageDialog(null,"Number of records: " +counter);
//validate user input
JOptionPane.showMessageDialog(null,"Would you like to input more records?");
String response3 = JOptionPane.showInputDialog(null, "Enter 'Y' for yes or 'N' for no.");
// I am not sure how to hold the value "Y" to make the loop keep repeating
input = keyboard.nextLine();
repeat = input.charAt(0);
counter++;
}
while(repeat == 'Y' || repeat == 'y');
}
}

Replace
input = keyboard.nextLine();
repeat = input.charAt(0);
with
repeat = response3.charAt(0);
to get the first character of the String entered into the input dialog box.
However, this will throw an StringIndexOutOfBoundsException if the user enters nothing into the dialog box, so you have to decide on a default value for that case:
repeat = response3.isEmpty() ? 'n' : response3.charAt(0);
Reading from System.in is basically for CLI applications.
Also check the "validate information" while loop. If the user enters invalid values, he will be informed about this indefinitely, with no chance of entering correct values.

Related

Looping user input until a positive nonzero integer is entered

I'm a complete beginner and I'm trying to trying to create a while loop that keeps asking the user for input until it gets a positive nonzero integer, and then moves on to the next part. Here's what I've got so far:
System.out.println("Enter the speed of the vehicle in "
+ "miles per hour: ");
while (keyboard.hasNext())
{
if (keyboard.hasNextInt())
{
speed = keyboard.nextInt();
while (speed <= 0)
{
System.out.println("Please enter a positive nonzero number: ");
speed = keyboard.nextInt();
}
}
else
{
System.out.println("Please enter a number: ");
speed = keyboard.nextInt();
}
}
Right now, when I run it and enter anything other than an integer, it prints out the line "Please enter a number," but then I immediately get an InputMatchException error and the build fails. If I enter a negative number or zero, it does prompt me to enter a positive number until I do, but then the code just stops executing and keeps running while doing nothing indefinitely, instead of moving on to the part after the loop, which just starts with another system.Output. Thanks in advance for any help.
You need to consume the previously entered non-int, and then attempt to read the following input:
else
{
System.out.println("Please enter a number: ");
// consume and ignore the previous non-int input
keyboard.next();
}
You could do it this way. By asking for a string representation of a numerical value using the Scanner#nextLine() method then applying the String#matches() method with a small Regular Expression (regex) that validates the fact that a positive numerical value was supplied (the "\\d+" expression), for example:
String speedString = "";
while (speedString.isEmpty()) {
System.out.println("Enter the speed of the vehicle in miles per hour: ");
speedString = keyboard.nextLine().trim();
if (!speedString.matches("\\d+") || Integer.valueOf(speedString) < 1) {
System.err.println("Invalid speed value supplied!\n"
+ "Please enter a 'positive' non-zero number.\n");
speedString = "";
}
}
int speed = Integer.parseInt(speedString);

Proper placing of the myScanner.next() method using Scanner class

Question 2:
As the code is written, if the use inputs a valid integer it asks for "Enter number 2", then "Enter number 3", then sums them. If the user inputs any data other than an integer for any of the entries, the code will print out "Invalid number entered" and only sum the valid integers entered. What I would like to do is force the user to enter only valid integers and the code remain repeating "Enter number X" for that entry until the user does so. Could someone please let me know how this is done? Thanks. Ron
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int counter = 0;
int addSum = 0;
while (counter < 3) {
counter++;
int numberEntered = 0;
System.out.println("Enter number " + counter + " :");
boolean hasNextInt = myScanner.hasNextInt();
if (hasNextInt) {
numberEntered = myScanner.nextInt();
// myScanner.nextLine(); //why can't myScanner.nextLine()
// could go here right after the number entered
// is captured and stored in the numberEntered variable;
addSum = addSum + numberEntered;
} else {
System.out.println("Invalid number entered");
}
// myScanner.nextLine only works if placed here before
// closing of the while loop;
myScanner.nextLine();
}
System.out.println("The sum of the numbers entered are " + addSum);
myScanner.close();
}
}
Right now, you are always incrementing the counter no matter what:
while (counter < 3) {
counter++;
Even when the user enters an invalid number, you increment the counter, causing the loop to run 3 times as usual, hence the current behaviour.
You should only increment the counter when the user enters a valid number:
if (hasNextInt) {
counter++;
numberEntered = myScanner.nextInt();
Now you will see that the prompts say "Enter number 0 :", which is probably not desirable. You can fix this by printing (counter + 1) when you are printing the prompt:
System.out.println("Enter number " + (counter + 1) + " :");

Birthday money calculator

My assignment is to create a calculator that can calculate how much is left on a giftcard after purchasing an item, but also making sure not to go over 6 items, or $225, whichever comes first. I know I need another method to do a calculation but i'm not sure what to put in it. This is what I have so far:
I know I will need a for loop for the counter for the items, but I'm really stuck. I posted the actual assignment to give background.
For your birthday, your rich aunt & uncle give you a $225 gift card to
the local mall. They will go shopping with you and will help carry out
your items. The most that each of you can carry is one item in each
hand. Thus, you may purchase a maximum of six items. You will have a
tracker device that computes the number of items you purchase as well
as the amount of money you have spent. After you choose each item, the
tracker prompts you for the price, and then displays the amount of
money you have spent. Then it displays the number of items you may
still choose and the balance on the gift card. The program will not
terminate until you reach 6 items or $225, whichever comes first. The
tracker then will list the total spent & the number of items as well
as the balance on the gift card.
Required:
validate that negative
prices are not entered and that you can’t spend more than the balance
on the gift card. Give the user as many opportunities as needed to
enter a price above 0 or below 225. User should be able to purchase
items costing between one penny and $225, inclusive.
all dollar
amounts should be formatted for currency using the NumberFormat class.
Include at least 1 method in your program.
Be sure to create test cases for all options:
spend the entire dollar amount on fewer than 6 items
purchase 6 items totaling less than the entire dollar amount
spend the entire dollar amount on exactly 6 items
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double priceItem = 0, totalPrice = 225, currentPrice = 0;
int numItem;
System.out.println("Happy birthday from Auntie and Uncle! \nYou may purchase up to"
+ " 6 items with this gift card of $225.");
for (numItem = 1; numItem <= 6; numItem++) {
System.out.println("Enter the price for item #" + numItem + ": ");
priceItem = input.nextDouble();
while (numItem <= 6 && totalPrice <= 225) {
totalPrice = currentPrice - priceItem;
System.out.println("You may buy this item. You have spent ");
if (currentPrice > totalPrice) {
System.out.println("Item is too expensive. Balance on gift card is " + currentPrice);
}
}
}
}
Whenever I have tried to make a while loop, it is an infinite loop and again I'm not sure which calculation to put in to get it to break.
I don't want to give you the answer as it is something you should solve yourself but I will give a few pointers.
Your use of a while loop here is incorrect, do you really need a while loop?
if(totalPrice <= 225) break;
Perhaps look into the break statement to exit the loop when a certain condition is met, that why you can ensure there are 6 items or less and it is not over 225.
You also need to handle an entry of 0 as it is a penny minimum and you cannot allow them to exceed 225.
priceItem = input.nextDouble();
while(priceItem < 0.01 || priceItem > 225){
System.out.println("Item Price cannot be 0 or greater than 225, please...");
priceItem = input.nextDouble();
}
You also can't allow a value that exceeds the remaining balance, I will let you try and figure out how to do that yourself. What you have done so far isn't bad you just need to break it down a bit more.
This is how I would construct it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double balance = 225.0;
double itemPrice = 0;
int boughtItems = 0;
int maxItems = 6;
System.out.println("Happy birthday from Auntie and Uncle! \nYou may purchase up to"
+ " 6 items with this gift card of $225.");
while(boughtItems < maxItems && balance > 0) {
System.out.print("You have " + balance + "$ on your giftcard. \nEnter the price for item #" + (boughtItems + 1) + ": ");
itemPrice = input.nextDouble();
if(balance - itemPrice > 0.0) {
balance -= itemPrice;
System.out.println("You have bought the Item!\n\n\nYou can carry " + (maxItems - boughtItems - 1) + " more things!\n");
boughtItems++;
} else {
if(balance - itemPrice == 0) {
balance -= itemPrice;
boughtItems++;
System.out.println("\nYou have spent all your money.");
}
else {
System.out.println("You dont have enough money for this Item!\n\n\n");
}
}
}
System.out.println("You bought " + boughtItems + " item/s. " + "Have fun with the stuff!");
}
You can write a buy(double balance, double price) method for example, so you fill in the assignment requirements.
And of course you need to do the rest of the stuff like the number-formatting.
In the while loop, you are doing wrong assignment, that’s why infinite loop.
Assign currentPrice is equal to totalPrice - price for item purchased.

Asking the user if they want to give multiple inputs

Im working on an assignment for an intro to java class and having some difficulty accounting for a situation when a user needs to give multiple inputs. The problem is given as follows:
"Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same."
My issue is that I cannot figure out how to make the program continuously ask the user if they want to input another number....for as many times as they say yes (obviously). I know I will have to use a loop or something, but I am a beginner with this and do not know where to start. Any help would be appreciated, and thanks in advance!
Here is what I have so far:
package findingminandmax;
import javax.swing.JOptionPane;
public class Findingminandmax
{
public static void main(String[] args)
{
String a = JOptionPane.showInputDialog("Input a number:");
int i = Integer.parseInt(a);
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
if ("yes".equals(b)) {
String c = JOptionPane.showInputDialog("Input another number:");
int j = Integer.parseInt(c);
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
} else {
JOptionPane.showMessageDialog(null, "The maximum number is " + i );
}
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
while(b.equalsIgnoreCase("yes")){
String c = JOptionPane.showInputDialog("Input another number:");
// your logic
b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
}
// then have your logic to print maximum and minimum number
But to get Yes/No inputs use a Confirm dialogbox rather than a input dialogbox
e.g.
int b = JOptionPane.showConfirmDialog(null, "Would you like to input another number? yes or no", "More Inputs", JOptionPane.YES_NO_OPTION);
while (b == JOptionPane.YES_OPTION) {
// your logic
}
while(true) {
//do stuff
if ("yes".equals(b)) {
//do other stuff
} else { break; }
}

In Java, is it possible to use some sort of while loop (or anything) to determine the amount of prompts for input?

public static void main (String [] args)
{
// declare variables, capture input
String input, name = JOptionPane.showInputDialog("Please " +
"enter your first and last name.");
double testScore1, testScore2, testScore3, average;
// capture input, cast, and validate input
input = JOptionPane.showInputDialog("What is the score " +
"of your first test?");
testScore1 = Double.parseDouble(input);
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your second test?");
testScore2 = Double.parseDouble(input);
while (testScore2 < 1 || testScore2 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore2 = Double.parseDouble(input);
}
input = JOptionPane.showInputDialog("What is the score " +
"of your third test?");
testScore3 = Double.parseDouble(input);
while (testScore3 < 1 || testScore3 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore3 = Double.parseDouble(input);
}
// calculate average and display output
average = (testScore1 + testScore2 + testScore3)/3;
JOptionPane.showMessageDialog(null, name + ", your average score is: " + average);
}
First off, I'm a beginner programmer. My terminology and jargon are quite lacking, so bear with me.
I'm writing a program to capture 3 test scores then validate them using a while loop (must be within the 1-100 range). The test scores are then averaged and the output displays the average. Pretty simple stuff.
I'm wanting to find a way, if possible, to capture the number of test scores, then from there, capture each actual score. For example, the program asks "How many tests are being computed for average?", then take that number and have it be the same amount of times the program prompts, "Please enter test score (1):" or something along those lines. So for further clarity, if the user typed 4 for number of tests, then the prompt for inputting the score would show up 4 times.
I feel the above code is redundant by using a while loop for each score and at that, limited because the program is only meant for 3 scores. Any help is much appreciated and feel free to critique anything else in the code.
Yes you can.
What you need is a nested loop. In pseudo code:
while(condition)
{
int numberOfInput = getInput() ; //get the input from the user
for(int i =0 ; i < numberOfInput; i++) //iterate for the amount of prompts required
prompt() ; //get input
}
function prompt
while (testScore1 < 1 || testScore1 > 100)
{
input = JOptionPane.showInputDialog("This test score is not " +
"between 1 and 100. \nPlease enter a test score in " +
"this range:");
testScore1 = Double.parseDouble(input);
}
Short answer:Yes, it is possible.
Option 1: Initially ask the user how many scores they are planning on entering, and store that in an int variable.
For example:
Ask user how many scores to enter.
Check the response, and store it in an int variable.
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable
Once loop is exhausted, just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Option 2: Use a sentinel-loop (the user has to enter a letter -usually 'Q' or 'N'- or something to exit the loop)
Create an int variable to store total loops (initialize to 0).
Create a double variable to add the scores (initialize it to 0.0)
Use a for loop, asking for the score;
Check if the value is the quit character
If it is not
Evaluate the score to ensure it's a valid number
If it's not a valid number, prompt the user again (this is still within
the same iteration, not a different iteration)
If it's a valid number, add it to the total scores variable and increment
the total loops variable by 1.
If it is
just divide the two variables (since the total
scores is a double, your answer will automatically be a double)
Display the answer.
Hope it helps.
In http://korada-sanath.blogspot.in/p/discussion-on-tech-topics.html, there is a pseudo code which illustrates similar problem with basic Java programming skills. In that in looping section you can simply add a check whether user entered score is in range 1-100 or not. If not, you can decrease loop variable by '1' so that user can enter his score one more time...
For further illustration please add below code in looping section of code present in above mentioned link.
instead of directly assigning user entered value to your testScores array, you can use one temp var and then can assign if user entered score in range.
Double temp = Double.parseDouble(br.readLine());
if(temp > 1 && temp < 100) {
testScores[loopVar] = temp;
} else {
loopVar--;
}

Categories