How to stop scanner from accepting input - java

I'm working on very simple code which asks you to enter how much money you have and and which products you wish to buy (on one line). The program is then supposed to tell you whether you have enough money to buy the products or not. Also, it should print the product with the lowest price.
Example:
Enter amount of money you have: 100
Enter products you want to buy and the value for each: Apple 10 and Orange 20
Output of the code:
you have enough money
the lowest price is (Apple 10)
I have 2 problems with this code
First, when I try to stop the scanner from taking inputs I'm supposed to enter "stop" as an input. However, in my case the action is only performed only if I enter "stop" 2 times. I don't know why.
I need to determine the minimum product value and print it. I have tried a lot of different things, but none of them worked for me.
This is my code so far:
Scanner input = new Scanner (System.in);
String productName="";
double totalPrice=0;
double productValue = 0;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (!(productName.equals("stop")) ){
if(input.hasNext()){ productName = input.next();}
if (input.hasNextDouble()){ productValue = input.nextDouble();}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}

Your code is reading two items before checking to see if the user wants to stop and that is why you're having to provide two inputs. To determine the minimum value just keep track of the lowest value you've seen so far along with the name associated with that value.
Scanner input = new Scanner (System.in);
String productName="", minProductName = null;
double totalPrice=0;
double productValue = 0, minValue = -1;
System.out.println("How much money do you have? ");
double money = input.nextDouble();
System.out.println("please insert the items in the invoice (the name of product and its price): "
+ " insert \"stop\" as the name of the product to finish your input");
while (true){
productName = input.next();
if("stop".equals(productName))
break;
productValue = input.nextDouble();
if(minValue < 0 || minValue > productValue){
minValue = productValue;
minProductName = productName;
}
totalPrice = totalPrice + productValue;
}
if (money > totalPrice ){
System.out.println("you have enough money");
} else {
System.out.println("you don't have enough money");
}
System.out.println("Minimum product value: "+minProductName + " " +minValue);
input.close();
Input/Output:
How much money do you have?
100
please insert the items in the invoice (the name of product and its price): insert "stop" as the name of the product to finish your input
apple 10
orange 5
banana 50
stop
you have enough money
Minimum product value: orange 5.0
Considerations/Notes:
You may notice that this condition has been flipped:
if("stop".equals(productName))
This is intentional because if you have a null productName somehow then your code will throw a null pointer if you use productName.equals(...) but if you use a constant like "stop" there is no way this can be null so it will never throw a NullPointerException.
You never validate your input - what if the user enters something that is less than zero for the value? Is that valid? If not then what should happen?

Instead of parsing the user input the way you are now, try parsing the entire line at once and then splitting up the input string using String.split()
Also consider what the your first call to Scanner.nextDouble() is really doing. It will read the next double input by the user but will not read to the next line (won't read past the newline character)

Related

Sentinel number in if statement

For data structures and algorithms in java class I've been assigned to create a program that takes user input for an item's name and price and then averages the price. I have successfully done that, however, I am having a great deal of trouble on a certain specification for the program: a sentinel number (-1) that terminates the project. Here is my code, I will explain what the issue is after.
while(true){
System.out.print("Enter item " + (count + 1) + " name: "); // enter name
names[count] = in.next(); // next string becomes count index
System.out.print("Enter item " + (count + 1) + " price: "); // enter price
prices[count] = in.nextDouble(); // stores price entered as array index
if(prices[count] == -1) break; // if next price == -1 // the code i want to change.
if(names[count].equalsIgnoreCase("peas")) flag = true;
average += prices[count];
count++;
}
So, my issue is: I want to terminate the program when I enter -1 for the item name, not have to enter a "dummy" item name and then have to enter the sentinel number (-1).
Sorry for the long explanation, just trying to be thorough.
Thanks for taking the time to read this and help a programmer hopeful out.
You need to use a String for your comparison (but "-1" will do). Also, do it immediately after you get the input. Something like,
names[count] = in.next();
if (names[count].equals("-1")) {
break;
} // ...

Java Looping for user input error until it's an int/double and distinguishing between the error input

I have a problem I sort of half fixed? It's more of a logic error, I think. My program overall is running smoothly, but I need to fix the flow of how my program interprets user input.
This program should report user error if they input a non numerical value or a negative number. And if the user enters 0, then is should accept it as a correct answer ( I have yet to figure out how to do that since my condition is whether or not it's a double).
I'm trying to differentiate between whether the user inputs a negative number or a character in the feedback. So far, I've made a loop to continuously prompt the user to enter a number if they don't input a double. Though I'm not sure how to go about accepting a 0 as an answer and filtering out negative numbers. I went back to my flow diagram and figured I may need to use an if-else statement to do this. But how can I do that while keeping the loop going? I'm not totally sure how I'm suppose to format that kind of thing.
Help is appreciated for this newbie! Thank you!
while(looping){
// Prompt user to enter how many grades they want averaged
System.out.println("How many grades would you like to average? ");
// Check if the input variables are positive numerical variables
// Or else report to user to input a number
while(!input.hasNextDouble()) //cannot be negative
{
input.next();
System.out.println("Please enter a number: ");
}
gradeNumber = input.nextInt();
// Prompt user to enter the grades
System.out.println("Please enter " + gradeNumber + " grades: ");
// Use a for-loop to control how many loops - reference to gradeNumber
for(gradesCount = 0; gradesCount < gradeNumber; gradesCount++){
// Check if the input variables are numerical variables
while (!input.hasNextDouble())
{
input.next();
System.out.println("Please enter a number: ");
}
gradesInput = input.nextDouble();
finalGrades = finalGrades + gradesInput;
} // end loop

Java program makes user enter same input twice to run after initial input error

I am having problems with my program. Everything is running smoothly, however, when the user inputs the wrong variable it does display the right feedback, but the user then has to enter one extra variable than previously stated.
Maybe it's a simple mistake I have made, but I can't see it..
It's confusing. An example when I run the program:
How many grades would you like to average?
3
Please enter 3 grades:
90
jf //Intentional user input error
You've entered a non-numerical variable. Please enter a number:
95
100 //The program should go ahead and calculate the average after this is entered
100 //It should not expect this fourth input if the amount of grades is 3
Your average is: 96.67
The second 100 input in the console should not appear, but it does when the user has at least one input error. If I were to run the program and input all the correct variables, then the program works smoothly.
This error also occurs when asking for how many grades the user would like to average. I thought it'd be easier to view what's wrong with my program by the second part.
I'm trying to get this program to run smoothly. Help is appreciated!
for (gradesCount = 0; gradesCount < gradeNumber; gradesCount++) {
// Check if the input variables are numerical variables
while (!input.hasNextDouble()) {
input.next();
System.out.println("You've entered a non-numerical variable. Please enter a number: ");
while (input.nextInt()<= 0){
System.out.println("You've entered a negative number. Please eneter a positive number: ");
}
}
// Read grade input
gradesInput = input.nextDouble();
Instead of input.hasNextDouble() you can try below
Scanner scan = new Scanner(System.in);
System.out.print("Enter total no of input ");
int total = Integer.parseInt(scan.nextLine());
int[] input = new int[total];
for (int i = 0; i < total; i++) {
while (true) {
try {
System.out.print("Enter number ");
String in = scan.nextLine();
input[i] = Integer.parseInt(in);
break;
} catch (RuntimeException re) {
System.err.print("Invalid input. ");
}
}
}
scan.close();
System.out.println(Arrays.toString(input));
It'll force the user input only numbers, you can add boundaries or change data type if required.

How to scan a number as a percentage?

I'm trying to create a program in java that should calculate the monthly payment and total interest paid on financing for any given purchase. The application should also allow the user to compare the differences between two different payment plans.
What I have
Scanner scan = new Scanner(System.in);
System.out.println("Enter the total cost of the purchase:");
float tPurchase = scan.nextFloat();
System.out.println("Enter your first down payment:");
float Paymentone = scan.nextFloat();
System.out.println("Enter your second down payment: ");
float Paymenttwo = scan.nextFloat();
System.out.println("Enter first lenght of time to pay");
float paylenght = scan.nextFloat();
System.out.println("Enter second length of time to pay:");
float paylength2 = scan.nextFloat();
System.out.println("Enter APR:");
My question is how do I get the program to scan the next number as a percentage. For instance, total purchase 10,000, down payment 3,000, second down 5,000, APR one 1% for three years and APR two 2% for 5 years. No need to tell me how to make it calculate, just how to make it scan as a percentage.
There is no different with how to scan the next number as a percentage and what you have done above.
Perhaps the only thing that you need to change is:
System.out.println("Enter the percentage:");
And you may retrieve the input by either:
float percentage = scan.nextFloat(); //or
int percentage = scan.nextInt();
Or if you want user to include % in their input then you might want to do:
String strPercentage = scan.nextLine();
float percentage = Float.parseFloat(strPercentage.substring(0,strPercentage.length()-1));
Of course you need to validate the user input to match you desired value first.
It depends on how you want the behaviour of your application to be. Will it accept aor to be in the form of xx %, x.xx or only xx?
Then this code will deal with all those three cases:
System.out.println("Enter APR:");
String aprTemp = scan.next();
int apr;
if (aprTemp.contains("%")) {
String aprStr = aprTemp.substring(0, aprTemp.indexOf("%"));
apr=Integer.parseInt(aprTemp);
}else if(aprTemp.matches("[0-9]+")){ // regex for number
apr=Integer.parseInt(aprTemp);
}else if(aprTemp.matches(""^([+-]?\\d*\\.?\\d*)$""){ // regex for float
float aprFloat=Float.parseFloat(aprTemp);
}

How do I output this information that I have stored?

I have written this code so far, it is part of an assignment, but I am stuck and am not sure how to do part 2. I have completed part 1. Any suggestions on where to go from here?
Thanks!
Part 1.
Prompts the user for the following information and stores the input in appropriate variables:
Whether the user is left-handed
Whether the user's father was at least 5 ft 10 inches tall
The user's age in months
The age in months of a sibling or friend of the user
The user's GPA
The displacement in liters of the user's car engine
Part 1. Code
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class InformationStationFinal{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String s1 = "yes";
String s2 = "no";
System.out.print("Are you left handed? Enter yes or no:");
String leftHand = input.next();
System.out.println("true");
System.out.print("Is your father at least 5ft 10 inches? Enter yes or no:");
String tall = input.next();
System.out.println("true ");
System.out.print("Enter your age in months: ");
int age = input.nextInt();
System.out.println(" ");
System.out.print("Enter the age of a sibling or friend in months: ");
int ageTwo = input.nextInt();
System.out.println(" ");
System.out.print("Enter your GPA as decimal, such as 3.58: ");
double gpa = input.nextDouble();
System.out.println(" ");
System.out.print("Enter displacement in liters of your cars engine:");
int liter = input.nextInt();
System.out.println(" ");
System.out.println("Are you left handed? " + " " + leftHand);
System.out.println("Is your father at least 5ft 10in? " + " " + tall);
System.out.println("Are you left handed or is your father at least 5ft 10?" + " " +
((leftHand.equals(s1)) || (tall.equals(s1))));
System.out.println("Are you left handed And is your father at least 5ft 10?" + " " +
((leftHand.equals(s1)) && (tall.equals(s1))));
System.out.println("Are your answers for left handed & father's height the same" + " " +
(leftHand.equals(tall)));
}
}
Part 2.
Prints out the following information, using either JOptionPane.showMessageDialog() or System.out.println() for the output:
Whether the user is left-handed
Whether the user's father was at least 5 ft 10 inches tall
Whether at least one of the values from a and b are true (true if either or both are true)
Whether a and b are both true (false if at least one is false)
Whether the truth values of a and b are the same (true if both a and b are true or if both a and b are false)
Whether the user is older than his/her sibling/friend (as far as we can tell from the ages in months)
Whether the user's age in months is within 12 months of the age of his/her sibling or friend. You may want to use Math.abs() for this.
Whether the user's GPA is at least equal to the displacement of his/her car engine. For this item, use an else statement to print out some appropriate message if the condition is false.
Could someone please help me complete the second part of this question? Thank you.
Sounds like you have a bunch of conditions to check. The nice thing about booleans, they lend themselves well to "if" statements . . .
Look into:
if(someCondition)
{
// Do Something
}
else
{
// Do Something Else
}
At this point, you could use a single String to gather the results for later printing in a JOptionPane.showMessageDialog(). I won't code it all for you, but here's an example:
String result = "";
if(leftHand.equalsIgnoreCase("yes")) {
result += "You are left handed.\n";
} else {
// Other stuff
}
// ...
JOptionPane.showMessageDialog(null, result);
EDIT: If you're not interested in using JOptionPane, then you can use a single System.out.println() to print the entire string out as well. You just have to remember, when you're adding your answers to the String, you need a newline character.
For those questions you will need some conditional statements, i.e.:
if(leftHand.equals("yes")){
System.out.println("User is left-handed");
} else {
System.out.println("User is right-handed");
}

Categories