Why does it prompt me twice in a row? - java

This while loop that is suppose to prompt for a price and a y/n and end if price = 0. However, when I run the code, it asks for the price, takes it, goes to a blank line, and I have to enter the number again before asking me the next question. For the second question, I only have to enter the input once.
And when I print the price array, the value is the number I inputted the second time.
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) {
prices.add(in.nextDouble());
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Help please?

That's because each time you write in.nextDouble(), the user will be need to type something into the scanner. Instead, you should store the input in a tempory variable:
Double input = in.nextDouble(); // Keep the input in this variable
if (input > 0) { // You can use it on each of these lines
prices.add(input); // so that the user doesn't have to type it twice.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
A little side note: keepGoing should probably be a boolean instead of an int
Also, you can use new String("Y").equalsIgnoreCase(input) so that you don't need the ||

It asks you twice because you call the in.nextDouble() method twice, one in the if statement and another time in the following line.

Take a look at the comments on your code below:
int keepGoing = 1;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
if (in.nextDouble() > 0) { // <-- You are asking for the input here
prices.add(in.nextDouble()); // <-- and asking for the input here again.
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}
Just change your code to be like this:
int keepGoing = 1;
double d = 0;
while (keepGoing > 0) {
System.out.print("How much is the item? (If no more items, enter '0') ");
d = in.nextDouble();
if (d > 0) {
prices.add(d);
System.out.print("Is the item a pet? (Y or N) ");
String input = in.next();
if (new String("Y").equals(input) || new String("y").equals(input)) {
isPet.add(true);
}
else { isPet.add(false); }
}
else { keepGoing = 0; }
}

Related

How am i going to use while loop and if else if user enter the same input twice and it will try again

I want to apply this function in java. Inside while loop, you need to input number of repetition you want to input a number. if you input a number that equals to the number that you enter previously, it will repeat a loop and enter a number again. This code is not finish yet. I hope u understand what i want to achive. thank you
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == input){
System.out.println("It is already taken");
}
}
}
}
Let's use a temp variable to store the value of previous input. If new input is same as previous input, the iterator i should not increase, so we use i--
System.out.print("Enter number of times: ");
int times = number.nextInt();
int i = 1;
int temp=0;
int inputArray[] = new int[times];
while ( i <= times){
System.out.print("Enter a number : ");
int input = number.nextInt();
i++;
if( input == temp){
System.out.println("It is already taken");
i--;
}else {
inputArray[i-2]=input;
}
temp=input;
}
}
The thing with that solution is that is only checks for the number just entered before the current one. I understood that you want to check that the number the user entered is unique and it has to be checked against every number that he/she has entered before.
See the code for that:
import java.util.Scanner;
import java.util.ArrayList;
public class testMe{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of times: ");
int times = scanner.nextInt();
int i = 0;
ArrayList<Integer> listWithEntries = new ArrayList<Integer>();
while (i < times){
System.out.print("Enter a number : ");
int input = scanner.nextInt();
if(listWithEntries.size() == 0){
listWithEntries.add(input);
i++;
} else {
for(int j = 0; j < listWithEntries.size(); j++){
if(input == listWithEntries.get(j)){
System.out.println("It is already taken!");
break;
}
if(j == listWithEntries.size()-1 && input !=
listWithEntries.get(j)){
listWithEntries.add(input);
i++;
break;
}
}
}
}
}
}

How can I check that the next input is an integer while checking if it's > and < at the same time in Java?

There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}

Q : Not understanding loop process? or possible if statements?

I am working on a project that involves creating a rental car calculator.
What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". If a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.
Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole positive numbers. for instance, not allowing input of 3.1, 2.35, 0.35 -2 and, etc...
here is what I have written and my attempt at these questions :
package inter;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
Scanner in=new Scanner(System.in);
System.out.println("If there are any customer press 1 else press 0");
int cus=in.nextInt();
while(cus!=0){
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car\n");
System.out.println("Enter 2 for a sedan car\n");
System.out.println("Enter 3 for an SUV");
CarType = in.nextInt();
if (CarType == 1) {
DailyFee=31.76;
}
else if(CarType == 2) {
DailyFee=40.32;
}
else if(CarType == 3) {
DailyFee=47.56;
}
else if(CarType <= 0) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
else if(CarType > 4) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = Integer.valueOf(in.nextLine());
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
System.out.printf("The total amount due is $ %.2f \n",Total);
System.out.println("If there are any customer press 1 else press 0");
cus=in.nextInt();
}
System.out.println("Count of customers : "+count);
System.out.printf("Total of the Day : $ %.2f",FullTotal);
}
}
Let me help you with this,
I made this code for you, i tried it and it worked
this will check if both answers were whole numbers (integers) and more than zero and will also check if the answer was numeric in the first place so that if the user answered with letters he will be prompted to try again
This is my suggestion:
basically i used the try-catch block with InputMismatchException to detect if the answer was not an integer (whole number ) or was not numeric at all, every time a mistake is detected i flip a boolean to false and keep looping as long as this boolean is false (i flip the boolean back to true before checking otherwise once the user gives a wrong answer he will always be prompted to answer even if he gave a correct answer after)
int vehicleType;
int numberOfDays;
double dailyFee;
boolean validAnswer1 = false;
boolean validAnswer2 = false;
Scanner scan = new Scanner(System.in);
while (validAnswer1 == false) {
validAnswer1 = true;
System.out.println("Choose Vehicle Type");
try {
vehicleType = scan.nextInt();
if (vehicleType <= 0) {
System.out.println("Number must be more than zero");
validAnswer1 = false;
} else if (vehicleType >= 4) {
System.out.println("Number should be from 1 to 3");
validAnswer1 = false;
} else {
if (vehicleType == 1) {
dailyFee=31.76;
} else if(vehicleType == 2) {
dailyFee=40.32;
}else if(vehicleType == 3) {
dailyFee=47.56;
}
while (validAnswer2 == false) {
validAnswer2 = true;
try {
System.out.println("Enter number of days rented ?");
numberOfDays = scan.nextInt();
if (numberOfDays <= 0) {
System.out.println("Number of days must be more than zero");
validAnswer2 = false;
} else {
// calculate your rent total here
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be an Integer");
validAnswer2 = false;
scan.next();
}
}
}
} catch (InputMismatchException ex) {
validAnswer1 = false;
System.out.println("Answer must be an Integer");
scan.next();
}
}
Hope this was useful, do let me know if you still need help

Two checks in while loop with Scanner - java

im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i

Looping an array

void searchForPopulationChange()
{
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
input = scan.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
}
}
}
hello!
I am working on a method that will take an users input,
lets say (5000) and search a data file with those corresponding numbers.
and return the corresponding number, and county that it corresponds with.
However, I am able to get this code to run to return the correct value,
but i am unable to get it to run when i enter an "incorrect" value.
Any pointers?
Thank you!
It's a bit unclear, but I assume you want something to handle if the input is incorrect (not an integer)? Use hasNextInt so you will only capture integers.
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
int num = scanner.nextInt();
This will keep looping the input until it is a valid integer. You can include a message in the loop reminding the user to input a correct number.
If you want something to display if your number has no match inside of the array, simply add code after your for block, if found == false. For example:
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
Since found is still false, your while loop kicks in and prints your line requesting for input again.
EDIT: Since you seem to have problem adding these two concepts to your code, here's the whole function:
void searchForPopulationChange() {
String goAgain;
int input;
int searchCount = 0;
boolean found = false;
while(found == false){
System.out.println ("Enter the Number for Population Change to be found: ");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
scanner.nextLine();
}
input = scanner.nextInt();
for (searchCount = 0; searchCount < populationChange.length; searchCount++)
{
if (populationChange[searchCount] == input)
{
found = true;
System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
}
}
if (found == false) {
System.out.println("Error, No records found!");
}
}
}

Categories