While Loop takes out first line Java - 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

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 do I accept the user input and put it into the while condition

This is my code, the while loop does not have an input and the rep variable does not accept an input:
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "";
do {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} // This does not accept input
while (rep.equals("y"));
}
}
Either just add one more keyboard.nextLine() before rep = keyboard.nextLine(); (in order to clear the newline character), or read your double gpa value with:
double gpa = Double.parseDouble(keyboard.nextLine());
Important point to understand here (especially if you're a novice Java developer), about why your code doesn't work, is, that you invoke nextDouble() as a last method on your Scanner instance, and it doesn't move the cursor to the next line.
A bit more details:
All the methods patterned nextX() (like nextDouble(), nextInt(), etc.), except nextLine(), read next token you enter, but if the token isn't a new line character, then the cursor isn't moved to the next line. When you enter double value and hit Enter, you actually give to the input stream two tokens: a double value, and a new line character, the double value is initialized into the variable, and the new line character stays into input stream. The next time you invoke nextLine(), that very new line character is read, and that's what gives you an empty string.
Here's the same code using a while loop instead of do-while. It works the way you want it to.
import java.util.Scanner;
public class MixedData {
public static void main(String[] args) {
String rep = "y";
while (!rep.equals("n")) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your full name: ");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ",GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
}
}
}
You need to skip blank lines.
public static void main(String[] args) {
String rep;
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter your full name");
String name = keyboard.nextLine();
System.out.print("Enter your GPA: ");
double gpa = keyboard.nextDouble();
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.next();
keyboard.skip("\r\n"); // to skip blank lines
}
while (rep.equalsIgnoreCase("y"));
keyboard.close();
}
Use nextLine instead of nextDouble:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String rep = "";
do {
System.out.println("Enter your full name:");
String name = keyboard.nextLine();
System.out.println("Enter your GPA:");
// double gpa = keyboard.nextDouble();
double gpa = Double.parseDouble(keyboard.nextLine());
System.out.println("Name: " + name + ", GPA: " + gpa);
System.out.println("Do you want to enter the data for another student?(y/n)");
rep = keyboard.nextLine();
} while (rep.equals("y"));
keyboard.close();
}

Using method to call for a y/n answer

I have this code. The askToContinue() method is being called to ask the user if they would like to continue but my problem is it just ignores the choice and starts the program again no matter what I enter. What am I missing in the code that is causing it to ignore my choice?
public class FutureValueApp {
public static void main(String[] args) {
System.out.println("Welcome to the Future Value Calculator\n");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
System.out.println();
// calculate the future value
double monthlyInterestRate = interestRate / 12 / 100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// print the results
System.out.println("FORMATTED RESULTS");
printFormattedResults(monthlyInvestment,
interestRate, years, futureValue);
System.out.println();
askToContinue(sc);
}
}
private static void printFormattedResults(double monthlyInvestment,
double interestRate, int years, double futureValue){
// get the currency and percent formatters
NumberFormat c = NumberFormat.getCurrencyInstance();
NumberFormat p = NumberFormat.getPercentInstance();
p.setMinimumFractionDigits(1);
// format the result as a single string
String results
= "Monthly investment: " + c.format(monthlyInvestment) + "\n"
+ "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
+ "Number of years: " + years + "\n"
+ "Future value: " + c.format(futureValue) + "\n";
System.out.println(results);
}
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next();
System.out.println();
return choice;
}
You're on the right track. Change this
askToContinue(sc);
to
choice = askToContinue(sc);
Because you need to assign the value returned from askToContinue to the local reference named choice.
You are not assigning the result of askToContinue to the choice variable which is checked in the loop.
Possibly the confusion is the choice variable inside the askToContinue method. Note, this is a different variable and does not affect the choice variable checked in the while statement.
When you define a variable inside a method, it is not recognized by the code outside of your method, even if it has the same name. So, in your code for example, you have,
public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next(); // this choice variable exists only for the
// askToContinue method
// Once you assign it over here and return it
// with the code below, you should use the returned
// value to update the variable choice, which is
// defined outside your askToContinue method
System.out.println();
return choice;
}
So, as the other answers have pointed out, if you do,
choice = askToContinue(sc);
then the code will run fine since the choice variable defined in the main method will get updated according to the value you input
Based on
John Camerin's answer,to skip double assigning in your code, you can make your choice variable as global static variable by define it in your class :
public class FutureValueApp {
public static String choice;
}
Or send it as second parameter in your method :
askToContinue(sc,choice);

Tax rate java program

I am new to java and I can't figure out what is wrong with my code. After the user inputs annual income and # of exemptions, the code stops working. There are no error messages on my console either. Please help me.
The program:
My code:
import java.util.Scanner;
public class TaxRate {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
// before asking the user for input
final double TAX_RATE = 0.12;
System.out.println ("Type in your name:");
String name;
name = sc.next();
System.out.println (name + ", type in your annual income and number of exemptions, separated by spaces:");
double income, exempt;
income = sc.nextDouble();
exempt = sc.nextDouble();
sc.close();
} // main method
} // lab class
Where you have
double num2 = 2000 * exempt;
num2 = sc.nextDouble();
you are calculating num2 and then waiting for the user to enter it.
Where you have
double adjustedGrossIncome = income - num2;
adjustedGrossIncome = sc.nextDouble();
you are calculating adjustedGrossIncome and then waiting for the user to enter it.
Where you have
double tax = TAX_RATE * adjustedGrossIncome;
tax = sc.nextDouble();
you are calculating tax and then waiting for the user to enter it.
If you take out the nextDouble() lines in those three cases, your program will run along instead of stopping for user input.
Your problem is that you ask for an input for tax that you already calculated, since that would be a useless line of code.

While statement loop error

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();

Categories