Why does it skip the "control" segment? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
so I'm trying to ask the user to input value for control right after the SOP is done. But it skips it for some reason.
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your balance?");
double initialBalance = keyboard.nextDouble();
Account chase = new Account(initialBalance);
System.out.println(chase + "; Would you like to deposit or withdraw?");
String control = keyboard.nextLine();
if(control == "deposit")
{
double deposit = keyboard.nextDouble();
System.out.println("How much would you like to deposit? " +
deposit);
chase.deposit(deposit);
System.out.println(chase);
}
}

Here is a snippet of your code with the changes required.
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your balance?");
double initialBalance = keyboard.nextDouble();
keyboard.nextLine();
Account chase = new Account(initialBalance);
System.out.println("; Would you like to deposit or withdraw?");
String control = keyboard.nextLine();
if (control .equals("deposit") ){
System.out.println("How much would you like to deposit? " );
double deposit = keyboard.nextDouble();
keyboard.nextLine();
The comments are clear. You would need to see the two post that they pointed to. Briefly there is a line separator that comes in and the importance of the equals method and its significance.

New Code:
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your balance?");
double initialBalance = keyboard.nextDouble();
Account chase = new Account(initialBalance);
System.out.println(chase + "; Would you like to deposit or withdraw?");
String control2 = "deposit";
boolean control = keyboard.next().equalsIgnoreCase(control2);
if(control == true)
{
double deposit = keyboard.nextDouble();
System.out.println("How much would you like to deposit? " +
deposit);
chase.deposit(deposit);
System.out.println(chase);
}
}
}

Related

scanner skips double type numbers

Hello I'm new in java and as i was making a program practicing input/output methods I came to this error:
When I input a int value the program works well, but when I input a double value it shows me this:
Here is my code:
import java.util.Scanner;
public class InpOutp
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in); // creates a scanner
System.out.print("Enter price of a six-pack beer: ");
double packPrice = in.nextDouble();
System.out.print("Give the ml of a can: ");
double canMl = in.nextDouble();
final double CANS_PER_PACK = 6;
double packMl = canMl * CANS_PER_PACK;
// find the price per ml of a pack
double pricePerMl = packPrice / packMl;
System.out.printf("Price per ml: %8.3f", pricePerMl);
System.out.println();
}
}
The problem is the separator. If you wish to use period try this
Scanner in = new Scanner(System.in).useLocale(Locale.US);
EDIT:
Also it is worth to mention, you should use in.nextLine();
after every nextInt() or nextDouble() otherwise you will encoder problems with nextLine when entering text.
Try this
System.out.print("Enter price of a six-pack beer: ");
double packPrice = in.nextDouble();
System.out.println("this will be skipped" + in.nextLine());
System.out.print("Give the ml of a can: ");
double canMl = in.nextDouble();
in.nextLine();
System.out.print("And now you can type: ");
System.out.println(in.nextLine());
The fault was that I was typing the values with . (5.4) and I should type them with , (5,4).

How can I use input from user that exist inside of if statement in Java?

So what I trying to do is ask users to put their weight and score of exam 1 & 2 and if they input the score, use those variables to figure out current score.
However, since scores are declared by users through scanner inside of if statement, it does not let me use those variables from outside of if statement.
How can I use variable 'examOneScore' and 'examTwoScore' when I want to calculate csEx1 and csEx2.
When I try to use those it says "The local variable examOneScore may not have been initialized."
import java.util.Scanner;
public class CurrentScore
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of secondexam? ");
String examTwo = keyboard.nextLine();
if(answerTwo.equalsIgnoreCase("yes") || answerTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
double examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
}
You have to define the variables that you want to use later outside of the if statement:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("Weight of Exam 1: ");
double weightExamOne = keyboard.nextDouble();
System.out.printf("Weight of Exam 2: ");
double weightExamTwo = keyboard.nextDouble();
System.out.printf("Do you know your score of first exam? ");
String examOne = keyboard.nextLine();
double examOneScore = 1;
if(examOne.equalsIgnoreCase("yes") || examOne.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examOneScore = keyboard.nextDouble();
}
System.out.printf("Do you know your score of second exam? ");
String examTwo = keyboard.nextLine();
double examTwoScore = 1;
if(examTwo.equalsIgnoreCase("yes") || examTwo.equalsIgnoreCase("y"))
{
System.out.printf("Your score? ");
examTwoScore = keyboard.nextDouble();
}
double csEx1 = (weightExamOne * examOneScore);
double csEx2 = (weightExamTwo * examTwoScore );
}
I used the value 1 for defining them, you have to look for yourself want you want to use there

why does my scanner(system.in) run twice

I am new to java, been self teaching for the last week. I cannot find the reason why the if else statement runs twice. here is the whole code, I know is simple but still trying to learn.
package tickets;
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
//adding code that would give a percentage discount for
//4 adults or more
{
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
}else {
double adult2 = (adult * adult1.nextInt());
System.out.println("please enter the amount of consessions");
Scanner consession1 = new Scanner (System.in);
double consession2 = (consession *consession1.nextInt());
System.out.println("please enter the amount of children");
Scanner child1 = new Scanner (System.in);
double child2 = (child * child1.nextInt());
System.out.println( "total"+" " + (adult2 +consession2 + child2) );
System.out.println("hope you enjoy your visit today!");
//woop woop it works!!!!!!!!!!
}
}
}
}
The reason why your program asked for two inputs was because adult1 is the name of your scanner and in your if statement the condition was if the user input is >= 4 then take an Integer input again from the user and multiply that with percentage and store it in adult2, instead this should be done as follows
public static void main(String[] args)
{
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
double adult2 = 0.0 // you dont need to redeclare below
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
// remove this unneccessary bracket {
int num = adult1.nextInt();
if ( num >= 4)
{
adult2 =( num * percentage);
}
else
{
adult2 = (adult * num);
}
System.out.println("Adult2 is " + adult2);
}
Store the int from the scanner and use that value in your ifs and calculations. You're calling nextInt() more than once and each time you get another int.
After you enter the if or else you will wait for more input of the integer type stopping the program.

Java, does not register user input at end of do-while loop [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I have this code:
import java.util.*;
public class MyAccount {
public static double balance = 0.0;
public static double deposit(double deposit){
return balance += deposit;
}
//public void setBalance(double balance){
// this.balance = balance;
//}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String redo = "";
do{
System.out.println("What do you want to do today?");
String answer= in.nextLine();
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = in.nextDouble();
deposit(money);
}
System.out.println("Your balance is " + balance);
System.out.println("Anything else(Y or N)?");
redo = in.nextLine().toUpperCase();
} while(redo.equals("Y"));
}
}
The program works just fine up until the end. If I deposit money into it and reach the line "Anything else(Y or N)?" I can not enter anything after; even though I have the redo String there. Though if I don't deposit money, I can enter something for redo and can get the program to loop. How do I fix it so it loops even when I deposit something?
The reason is somewhat tricky. It's because after you call in.nextDouble(), the \n from the user is still in the input stream, such that redo will be equal to an empty String when you call redo = in.nextLine().toUpperCase(). To fix it, add in.nextLine() like so:
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = in.nextDouble();
in.nextLine();
deposit(money);
}
Or another alternative is:
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = Double.parseDouble(in.nextLine());
deposit(money);
}

Do/while loop isn't executing properly

Im sure I am missing something simple but I cannot get my do while loop to execute properly. I want it to run through the first time and keep going until the user inputs q. It currently executes once and then loops back up to ask what account to access and then does nothing. Any help or pointing me in the right direction so I can fix it would be greatly appreciated.
public class Crawford_Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double input1;
String accountChoice;
String accountActivity;
RegularAccount regAcct = new RegularAccount(0, .5);
SavingsAccount savAcct = new SavingsAccount(0, .5);
do{
System.out.println("What account would you like to access(regular or savings)?" );
accountChoice = keyboard.nextLine();
if(accountChoice.equalsIgnoreCase("regular"))
System.out.println("What action do you wish to perform(deposit, withdraw or monthly process)? ");
accountActivity = keyboard.nextLine();
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
regAcct.deposit(input1);
System.out.println("Your balance is " + regAcct.getBalance() );
}
else if (accountActivity.equalsIgnoreCase("withdraw"))
{
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
regAcct.withdraw(input1);
System.out.println("Your balance is "+ regAcct.getBalance());
}
else if (accountActivity.equalsIgnoreCase("monthly process"))
{
regAcct.monthlyProcess();
}
else {
if (accountChoice.equalsIgnoreCase("savings"))
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
savAcct.deposit(input1);
System.out.println("Your balance is " + savAcct.getBalance() );
}
if (accountActivity.equalsIgnoreCase("withdraw"))
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
savAcct.withdraw(input1);
System.out.println("Your balance is "+ savAcct.getBalance());
}
}while (!accountChoice.equalsIgnoreCase("Q"));
}
}
You're missing a set of curly braces after this statement:
if(accountChoice.equalsIgnoreCase("regular"))
...and this statement:
if (accountActivity.equalsIgnoreCase("withdraw"))
The default behavior for Java (and C, and C++) is to execute only the next line after an if, for, or while statement if curly braces are omitted.
When you're done, your statement should look like this:
if(accountChoice.equalsIgnoreCase("regular")) {
System.out.println("What action do you wish to perform(deposit, withdraw or monthly process)? ");
accountActivity = keyboard.nextLine();
// Rest of code that concerns activity with a "regular" account
}
You have to make sure you read both options at the start; accountChoice and accountActivity. One issue with your code is the lack of { and } usage.
So it would be like...
do { // do below first before checking the while condition
if(accountChoice.equalsIgnoreCase("regular"))
{
// do your work.
} else if (accountChoice.equalsIgnoreCase("savings"))
{
// do the rest
}
} while (!accountChoice.equalsIgnoreCase("Q"));
Below is the modified code.
public class Crawford_Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double input1;
String accountChoice;
String accountActivity;
RegularAccount regAcct = new RegularAccount(0, .5);
SavingsAccount savAcct = new SavingsAccount(0, .5);
do {
System.out.println("What account would you like to access(regular or savings)?" );
accountChoice = keyboard.nextLine();
System.out.println("What action do you wish to perform(deposit, withdraw or monthly process)? ");
accountActivity = keyboard.nextLine();
if(accountChoice.equalsIgnoreCase("regular")) { // LINE moved and BRACKET MISSING
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
regAcct.deposit(input1);
System.out.println("Your balance is " + regAcct.getBalance() );
}
else if (accountActivity.equalsIgnoreCase("withdraw"))
{
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
regAcct.withdraw(input1);
System.out.println("Your balance is "+ regAcct.getBalance());
}
else if (accountActivity.equalsIgnoreCase("monthly process"))
{
regAcct.monthlyProcess();
}
}
else if (accountChoice.equalsIgnoreCase("savings"))
{ // line changed & BRACKET MISSING
if (accountActivity.equalsIgnoreCase("deposit"))
{
System.out.println("How much would you like to deposit?");
input1= keyboard.nextDouble();
savAcct.deposit(input1);
System.out.println("Your balance is " + savAcct.getBalance() );
}
else if (accountActivity.equalsIgnoreCase("withdraw"))
{ // bracket missing
System.out.println("How much would you like to withdraw?");
input1= keyboard.nextDouble();
savAcct.withdraw(input1);
System.out.println("Your balance is "+ savAcct.getBalance());
}
}
} while (!accountChoice.equalsIgnoreCase("Q"));
}
}

Categories