My scanner skips over my next double and next integer? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
Whenever I'm running my scanner it skips over the height(double) loop after weight. It also skips over the level(int) loop after age.
Here's my scanner class.
import java.util.Scanner;
public class HowHealthy
{
public static void main(String[] args)
{
String aGender = "";
//New healthy objec tis created
Healthy person = new Healthy();
//Scanner object is created
Scanner in = new Scanner(System.in);
String name = "";
while(!person.setName(name))
{
System.out.print("Person's name: ");
name = in.nextLine();
if(!person.setName(name))
{
System.out.println("Invalid name - must be at least one character!");
}
}
char gender = '\0';
while(!person.setGender(gender))
{
System.out.print(name + ", are you male of female (M/F): ");
gender = in.nextLine().toUpperCase().charAt(0);
if(!person.setGender(gender))
{
System.out.println("Invalid gender - must be M or F (upper or lower case)":
}
}
double weight = 0;
while(!person.setWeight(weight))
{
System.out.print(name + "'s weight (pounds): ");
weight = in.nextDouble();
in.nextLine();
if(!person.setWeight(weight))
{
System.out.println("Invalid weight - must be at least 100 pounds!");
}
}
double height = 0;
while(!person.setHeight(height))
{
System.out.print(name + "'s height (inches): ");
height = in.nextDouble();
if(!person.setHeight(height))
{
System.out.println("Invalid height - must be 60..84, inclusively!");
}
}
int age = 0;
while(!person.setAge(age))
{
System.out.print(name + "'s age (years): ");
age = in.nextInt();
in.nextLine();
if(!person.setAge(age))
{
System.out.println("Invalid age - must be at least 18!");
}
}
System.out.println();
System.out.println("Activity Level: Use these categories:");
System.out.println("\t1 - Sedentary (little or no exercise, desk job)");
System.out.println("\t2 - Lightly active (little exercise / sports 3-5 days/wk");
System.out.println("\t3 - Moderately active(moderate exercise / sports 3-5
System.out.println("\t4 - Very active (hard exercise / sports 6 -7 day/wk)");
System.out.println("\t5 - Extra active (hard daily exercise / sports \n\t physica2X)
int level = 0;
while(!person.setLevel(level))
{
System.out.print("How active are you? ");
level = in.nextInt();
if(!person.setLevel(level))
{
System.out.println("Invalid acitvity level - must be 1..5, inclusively!");
}
}
System.out.println();
//Creates a new Healthy object and prints values based on user's input
System.out.println(person.getName()+ "'s information");
System.out.printf("Weight: %.1f %s \n", person.getWeight(), "pounds");
System.out.printf("Height: %.1f %s \n", person.getHeight(), "inches");
System.out.println("Age: " + person.getAge() + " years");
if (gender == 'M')
{
aGender = "male";
}
else
{
aGender = "female";
}
System.out.println("These are for a " + aGender);
System.out.println();
//Calculates the person's BMR, BMI and TDEE based on user input
System.out.printf("BMR is %.2f \n", person.calcBMR());
System.out.printf("BMI is %.2f \n", person.calcBMI());
System.out.printf("TDEE is %.2f \n", person.calcTDEE());
//Determines person's weight status based on BMI calculated
double BMI = person.calcBMI();
//Displays person's weight status
System.out.println("Your BMI classifies you as " + person.calcWeightStatus());
}
}
Here is my scanner class.

In both cases, you're missing in.nextLine() after you do in.nextInt(). If all of the other lines of code are working using things like in.nextDouble() followed by in.nextLine() my guess is that's what's missing.

Since it is skipping over the loops completely, there is something wrong with your methods for setHeight() and setLevel().
while(!person.setHeight(height))
If it is skipping this loop, it must mean that setHeight(height) is returning true when it should be returning false, or you need to get rid of the '!'

Related

I have a program where i would like to validate user input in java i want the user to input a double value and only a double value any suggestions?

I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.

No Such Element - No Line Found (Java)

I'm creating a program which prints a summary of the situation after interactive input has ended (ctrl - d). So it prints a summary of the average age and percentage of children who have received vaccines after interactive input.
However, I'm always receiving the No Line Found error whenever I press ctrl-d at Name:. My compiler tells me the error is at name = sc.nextLine(); within the while loop but I don't know what is causing the error exactly.
public static void main(String[] args) {
String name = new String();
int age, num = 0, i, totalAge = 0;
boolean vaccinated;
int numVaccinated = 0;
double average = 0, percent = 0, count = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
while(sc.hasNextLine())
{
sc.nextLine();
System.out.print("Name: ");
name = sc.nextLine();
System.out.println("Name is \"" + name + "\"");
System.out.print("Age: ");
age = sc.nextInt();
System.out.println("Age is " + age);
System.out.print("Vaccinated for chickenpox? ");
vaccinated = sc.nextBoolean();
totalAge += age;
num++;
if(vaccinated == true)
{
count++;
System.out.println("Vaccinated for chickenpox");
}
else
{
System.out.println("Not vaccinated for chickenpox");
}
}
average = (double) totalAge/num;
percent = (double) count/num * 100;
System.out.printf("Average age is %.2f\n", average);
System.out.printf("Percentage of children vaccinated is %.2f%%\n", percent);
}
}
You do not correctly implement an exit condition for your loop if you ask me.
Try something like this:
String input = "";
do {
System.out.print("Name: ");
name = sc.nextLine();
[... all your input parameters ...]
sc.nextLine();
System.out.print("Do you want to enter another child (y/n)? ");
input = sc.nextLine();
} while (!input.equals("n"));
This way you can quit entering new persons without having to enter a strange command that might lead to an error. Furthermore, a do-while loop helps you to reduce your code, because you don't have to use the same code twice, i.e., everything between Scanner sc = new Scanner(System.in); and while(sc.hasNextLine()) in your example.

for loop class assignment gone wrong

I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}

How to use loops and average in Java [duplicate]

This question already has answers here:
How to get average from given values
(3 answers)
Closed 9 years ago.
My program is supposed to find the average of female, male, and total average GPA of students. And also total female, male, and total students. First it asks if the student is male or female. If you choose male it does the loop, but after it ends. I want my program to go straight into the next choice. Example if you choose male the you'll input female and visa versa.
import java.util.Scanner;
public class practice {
public static void main(String [] args) {
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
System.out.println("Enter GPA");
GPA = keyboard.nextDouble();
if (student.equals("M")) {
while (GPA >=0) {
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
}
if (student.equals("F")) {
while (GPA >=0) {
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
}
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
allAverage = mTotal + fTotal;
totalStudents = maleCount + femaleCount;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total MALE Average GPA: " + mAverage);
System.out.println("Total average: " + allAverage);
}
}
How to use loops and average in Java?
Well, pretty much as in the code in your question, I'd say. Just add a loop around the part that needs a loop, and figure out how you are going to end the looping.
The other problems that leap out at me are:
You seem to be accepting the input in a strange order.
You are calculating allAverage incorrectly. Just look at the code again. The problem should be obvious.
Actually, one of the difficulties with answering this Question is that it is not at all clear how the program as written is supposed to behave. And we can't infer that from what you've shown us. 'Cos what you've written obviously doesn't work ... from a usability perspective.
If you don't understand and can't explain the requirements properly, there is not much chance that you will be able to implement them correctly.
Fixed my code sorry for it being unclear.
import java.util.Scanner;
public class practice
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents, count = 0;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
do{
System.out.println("Enter GPA " + student);
GPA = keyboard.nextDouble();
if (student.equals("M"))
{
while (GPA >=0)
{
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
student = "F";
}
else if (student.equals("F"))
{
while (GPA >=0)
{
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
student = "M";
}
}
while (++count < 2);
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
totalStudents = maleCount + femaleCount;
allAverage = (mTotal + fTotal)/totalStudents;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total average: " + allAverage);
}

do-while loop not continuing

I'm having an issue with the code below. It's all working fine, except I want the program to restart if the user types in "Y" at the end, and end if anything else is pressed.
However, whenever I type anything at the "Restart Calculator" prompt, it will stop running, regardless of whether I type in "Y" or "N". Validation with the Y/N is not too important here, I just want it to restart if Y is typed and end if anything else is typed.
Apologies for the noob code, Java beginner here.
import java.util.Scanner;
import java.text.*;
public class Savings {
public static void main(String[] args)
{
//Imports scanner, to read user's input
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
do {
//Asks for and receives user's initial deposit
int initial_Deposit;
do {
System.out.print("Enter initial deposit in dollars (Between $1 - $50000: ");
while (!scan.hasNextInt()) {
System.out.println("Please enter a valid number between '1-50000'");
scan.next();
}
initial_Deposit = scan.nextInt();
} while (initial_Deposit <= 0 || initial_Deposit >= 50001);
//Asks for and receives user's interest rate
double interest_Rate;
do {
System.out.print("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
while (!scan.hasNextDouble()) {
System.out.println("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
scan.next();
}
interest_Rate = scan.nextDouble();
} while (interest_Rate <= 0.0 || interest_Rate >= 100.1);
//Asks for and receives user's monthly deposit
int monthly_Deposit;
do {
System.out.print("Enter monthly deposit in dollars between '$1 - $5000: ");
while (!scan.hasNextDouble()) {
System.out.println("Enter monthly deposit in dollars between '$1 - $5000: ");
scan.next();
}
monthly_Deposit = scan.nextInt();
} while (monthly_Deposit <= 0 || monthly_Deposit >= 5001);
//Asks for and receives user's investment duration
int monthly_Duration;
do {
System.out.print("Enter investment duration (Between 1 and 12): ");
while (!scan.hasNextDouble()) {
System.out.println("Enter investment duration (Between 1 and 12): ");
scan.next();
}
monthly_Duration = scan.nextInt();
} while (monthly_Duration <= 0 || monthly_Duration >= 13);
//Asks for and receives user's first name
String first_Name;
System.out.print("Enter first name: ");
first_Name = input.next();
//Asks for and receives user's surname
String last_Name;
System.out.print("Enter surname: ");
last_Name = input.next();
//Formats first name to only first letter
char firstLetter = first_Name.charAt(0);
//Changes name to correct format
String formatted_Name;
formatted_Name = "Savings growth over the next six months for " + last_Name + ", " + firstLetter;
System.out.println(formatted_Name);
//Calculates the first balance
double balanceCurrent;
balanceCurrent = initial_Deposit + monthly_Deposit;
//Prepares to format currency
DecimalFormat df = new DecimalFormat("#.##");
//Defining variables
double balanceNew;
double interestEarned;
//Defining counter for while loop
int counter;
counter = monthly_Duration;
int month_Counter;
month_Counter = 1;
//While loop to calculate savings
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
System.out.println("Balance after month " + month_Counter + ": $" + df.format((balanceNew)));
System.out.println("Interest earned for this month: $" + df.format(interestEarned));
counter = counter - 1;
month_Counter = month_Counter + 1;
}
//Formats data into a table
balanceCurrent = initial_Deposit + monthly_Deposit;
counter = monthly_Duration;
int month;
month = 0;
String dollarSign = "$";
String stringHeadingOne = "Month";
String stringHeadingTwo = "New Balance";
String stringHeadingThree = "Interest Earned";
String dividerOne = "----- ----------- ---------------";
System.out.println("");
System.out.printf("%-9s %s %19s \n", stringHeadingOne, stringHeadingTwo, stringHeadingThree);
System.out.println(dividerOne);
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
month = month + 1;
System.out.printf("%-11s %s %s %13s %s \n", month, dollarSign, df.format((balanceNew)), dollarSign, df.format(interestEarned));
counter = counter - 1;
}
System.out.print("Restart Calculator? Y/N);");
} while (scan.next() == "Y");
}
}
while (scan.next() == "Y"); // Is checking for reference equality
When doing object comparisons in Java, use equals()
while (scan.next().equals("Y"));
Or, as the previous answer pointed out you can compare characters with the == operator
Try this:
scan.nextLine().charAt(0) == 'Y'
When comparing Strings or anyother object for that matter you need to use the .equals(Object other) method. You can only use == with primatives ( boolean, int, double,...)
scan.nextLine().equals("Y");
//or
scan.next().equals("Y");
There is also an method to take the string to Uppercase that would allow the user to enter "y" or "Y"
scan.next().toUpperCase().equals("Y");
You should be using the Equals method for Strings:
while ("Y".equals(scan.next()));

Categories