While statement loop error - java

Hey I have been having an issue with this code because it has not been looping when I input a value for the String repeat. I am unable to understand whatever it is that I'm doing wrong.
import java.util.Scanner;
public class MpgCalculator
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the MPG and CPM Calculator!");
double startOd, endOd, gallons, cost, mpg, cpm;
String repeat = "yes";
while(repeat.equals("yes")||repeat.equals("Yes")||repeat.equals("y")||repeat.equals("Y"))
{
System.out.println("Please Enter:");
System.out.print("\tYour Starting Odometer Reading: ");
startOd = sc.nextDouble();
System.out.print("\tYour Ending Odometer Reading: ");
endOd = sc.nextDouble();
System.out.print("\tThe Amount of Gallons Used: ");
gallons = sc.nextDouble();
System.out.print("\tThe Cost-per-Gallon That You Spent: ");
cost = sc.nextDouble();
mpg = getMpg(startOd, endOd, gallons);
cpm = getCpm(mpg, cost);
System.out.println("\nYour Miles-per-Gallon is " + mpg + ".");
System.out.println("Your Cost-per-Mile is " + cpm + ".");
System.out.print("Do it again? ");
repeat = sc.nextLine();
}
}
public static double getMpg(double startOd, double endOd, double gallons)
{
double mpg;
mpg = (endOd - startOd) / gallons;
return mpg;
}
public static double getCpm(double mpg, double cost)
{
double cpm;
cpm = cost / mpg;
return cpm;
}
}

Change repeat = sc.nextLine(); to repeat = sc.next(); If you don't need the extra line. It only gets it if you are an the next line, which you are not, so it terminates the program.

The previous use of your Scanner prior to calling repeat = sc.nextLine(); in your while loop is nextDouble. Calling nextDouble does not consume the newline character in the stream from entering the cost per gallon.
Consume the newline character before asking to repeat:
System.out.print("Do it again? ");
String dummy = sc.nextLine(); // Add this line.
repeat = sc.nextLine();

use
repeat = sc.next();
instead of
repeat = sc.nextLine();

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.

Is this the correct syntax for inputing a string to an if statement or am i completely off?

package travelCost;
import java.util.Scanner;
public class travelCost {
public static void main(String[] args) {
//Scanner function
Scanner in = new Scanner(System.in);
//define problem variables
//first
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
//Here i want the user to input a string and then based upon the answer //section into the for loop
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec"))
{
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance/milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ", totalCostElec);
} else if (type.equals("gas: ")
{
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance/mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
}else
{
System.out.println("Please resubmit entry");
}
System.out.println();
}
}
After the corrections which mentioned by Paul, here is the complete code:
travelCost.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance / milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ",
totalCostElec);
} else if (type.equals("gas")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance / mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
} else {
System.out.println("Please resubmit entry");
}
System.out.println();
}
Input:
elec 100 10 2
Output:
The trip is going to cost $20.00:
make it
else if (type.equals("gas"))
There are 4 problems with this:
The line } else if (type.equals("gas: ") needs another ) at the end.
In the "gas" case, you are using the variable distance but you do not give it a value.
While if (type.equals("elec")) is the correct syntax (answering your question), it is usually better to write if ("elec".equals(type)) because this will not throw a NullPointerException if type == null.
It should be "gas", not "gas: ".
As Paul mentions, your if statement syntax is correct, but it is good practice to start with the hard coded strings ("elec" and "gas") in order to avoid NullPointerExceptions. As mentioned in the other answers, the if else should be using "gas" instead of "gas: ". To help avoid those kinds of errors, you might consider making "elec" and "gas" into static final String constants. If you use constants, you'll know that they are the same throughout your program. You might also want to call type.toLowerCase() in the event that the user enters the response in uppercase.

While Loop takes out first line Java

Thank you for the suggestions this is my first time on stackoverflow as I am fairly new to programming. The problem that I am having is that my program doesn't ask for a name after the while loop is executed. Specifically it seems to not execute this line after the loop.
System.out.print("Enter the dieter's name: ");
String name = input.nextLine();
Can someone please explain my possible miss use of the Scanner utility.
import java.util.*;
/**
* CS-12J
* Sweetner.java
* Purpose:
*
* #version 1.0 3/18/13
*/
public class Sweetner {
/**
* The main method begins the execution of the program
*
*#param args not used
*/
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String again = "yes";
while (again.equals("yes")) {
System.out.print("Enter the dieter's name: ");
String name = input.nextLine();
System.out.print("Enter the target weight of the dieter in pounds: ");
double weightInPounds = input.nextDouble();
//converts pounds to grams
final double IBS_TO_GRAMS = 453.59;
double weightInGrams = weightInPounds * IBS_TO_GRAMS;
//finds lethal amout of sweetner for mouse
final double MOUSE_WEIGHT = 30.0;
final double LETHAL_DOSE = 100.0;
final double MOUSE_LETHAL_PROPORTION =
(double) LETHAL_DOSE / MOUSE_WEIGHT;
//finds lethal amount of sweetner for human of given weight
double lethalSweetner = MOUSE_LETHAL_PROPORTION * weightInGrams;
//lethal number of cans
final double SODA_SWEETNER = 0.001;
final double SODA_GRAMS = 350;
double lethalCans = lethalSweetner / (SODA_SWEETNER * SODA_GRAMS);
//output
System.out.println("For dieter: " + name);
System.out.println("Dieter's target weight: " + weightInPounds
+ " pounds");
System.out.println("Lethal dose in grams of sweetner is: "
+ lethalSweetner);
System.out.println("Lethal number of cans of soda: "
+ lethalCans);
//extra credit
final int CANS_PER_DAY = 15;
final double DAYS_IN_YEAR = 365.25;
double yearsToLethal = lethalCans / (CANS_PER_DAY * DAYS_IN_YEAR);
System.out.println("Years to lethal dose: " + yearsToLethal);
System.out.print("Do you want to repeat the program? yes or no\n\t\t");
again = input.next();
}
}
}
Use next() instead of nextLine() to get the name:
String name = input.next(); // to get the name
nextLine() scans the invisible newline character which seems to be the case when user enters yes. So if you want to avoid using next(), just put input.nextLine(); at the end of the loop to consume the newline character.
try this at the end of the loop:
again = input.nextLine();
Change your
String name = input.nextLine();
to this and it'll work.
String name = input.next();
input.nextLine() retrieves the next newline character.
In your System.out.print() you provided "\n" which triggered the nextLine() method.
System.out.print("Do you want to repeat the program? yes or no\n\t\t");
again = input.next();
You need another input.nextLine() right before the second statement, such that :
System.out.print("Do you want to repeat the program? yes or no\n\t\t");
input.nextLine();
again = input.next();
I hope this solves your problem. :)
if the dieter's name may not be empty
System.out.print("Enter the dieter's name: ");
String name = scanLine.apply( input );
find scanLine here

Categories