Unable to continue loop [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I am trying to get this code to loop so once I run through the main while loop it starts over and asks for the input of the program again. I have a commented out of input at the bottom of the code and for some reason when the program reaches this line it terminates.
enter image description here
image of output I'm looking for.
import java.util.Scanner;
public class Eggs
{
public static void main(String[] args)
{
String program="";
String program2 ="";
String PythonID;
int PythonAge = 0;
int PreviousYr=0;
int CurrentYr=35;
int SumEggs=0;
int GTeggs=0;
int PythonYr=0;
System.out.println("This is the Python Snake Eggstimator Program.");
System.out.println("It estimates the number of eggs that a female python will "
+ "produce over a lifetime.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter HISS if you want run the program STOP to quit");
program= input.nextLine();
while (program.equals("HISS"))
{
//Ask user to continue program
//ask for Python ID name
System.out.println("Enter the Python ID:");
PythonID= input.nextLine();
//Python age
do
{
System.out.println("Enter the age of the python in years:");
PythonAge= input.nextInt();
}
while(PythonAge <1 || PythonAge >20);
//setting year to 0
PreviousYr=0;
SumEggs=0;
//if age is less than 4
if (PythonAge <4)
{
PythonAge = 4;
}
//Calculation egg stuff
while (PythonAge <=20)
{
SumEggs = PreviousYr + CurrentYr;
System.out.println("Year " +PythonAge+ " Previous "+PreviousYr + " Current Year " +CurrentYr+ " Sum eggs "+SumEggs);
PreviousYr= PreviousYr + CurrentYr;
PythonAge++;
}
//ask for program again
System.out.println(PythonID+ " will lay a total of " + SumEggs + " over her remaining lifetime of 20 years.");
System.out.println("Please enter HISS if you want run the program STOP to quit");
//program= input.nextLine();
GTeggs=GTeggs + SumEggs;
System.out.println("The sum of all eggs for all Pythons processed is " + GTeggs);
}
System.out.println("The sum of all eggs for all Pythons processed is " + GTeggs);
}
}

Hi please find the modified working code.
import java.util.Scanner;
public class Demo123 {
public static void main(String[] args)
{
String program="";
String program2 ="";
String PythonID;
int PythonAge = 0;
int PreviousYr=0;
int CurrentYr=35;
int SumEggs=0;
int GTeggs=0;
int PythonYr=0;
System.out.println("This is the Python Snake Eggstimator Program.");
System.out.println("It estimates the number of eggs that a female python will "
+ "produce over a lifetime.");
Scanner input = new Scanner(System.in);
System.out.println("Please enter HISS if you want run the program STOP to quit");
program= input.nextLine();
while (program.equals("HISS"))
{
//ask for Python ID name
System.out.println("Enter the Python ID:");
PythonID= input.nextLine();
//Python age
do
{
System.out.println("Enter the age of the python in years:");
PythonAge= input.nextInt();
input.nextLine();
}
while(PythonAge <1 || PythonAge >20);
//setting year to 0
PreviousYr=0;
SumEggs=0;
//if age is less than 4
if (PythonAge <4)
{
PythonAge = 4;
}
//Calculation egg stuff
while (PythonAge <=20)
{
SumEggs = PreviousYr + CurrentYr;
System.out.println("Year " +PythonAge+ " Previous "+PreviousYr + " Current Year " +CurrentYr+ " Sum eggs "+SumEggs);
PreviousYr= PreviousYr + CurrentYr;
PythonAge++;
}
//ask for program again
System.out.println(PythonID+ " will lay a total of " + SumEggs + " over her remaining lifetime of 20 years.");
System.out.println("Please enter HISS if you want run the program STOP to quit");
//program= input.nextLine();
GTeggs=GTeggs + SumEggs;
System.out.println("The sum of all eggs for all Pythons processed is " + GTeggs);
System.out.println("Please enter HISS if you want run the program STOP to quit");
program= input.nextLine();
}
}
}

Related

Printing Appropriate Number Through Array

I'm trying to print out a baseball players on base percentage. So far, the code is going great. The only issue is that when I'm printing out the OBP for each year, I can't seem to match up the correct year that correlates to the year the user input. Each time it loops in the method printOnBasePercentage() it increments the year by one. Is there a way I can resolve this issue? Thanks.
I've tried adding +startYear++ and that didn't seem to work. It got me closer.
public static void main(String[] args) {
int numYears;
double [] years;
String name;
int startYear;
double oBP;
int hits, walks, sacFlies, hitsByPitch, atBats;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of baseball player: ");
name = keyboard.nextLine();
System.out.print("Enter the number of years " + name +" has been playing: ");
numYears = keyboard.nextInt();
years = new double[numYears];
System.out.print("Enter " +name +" first year on the team: ");
startYear = keyboard.nextInt();
for (int index = 0; index < years.length; index++) {
System.out.print("For Year: "+ startYear++);
System.out.print("\nEnter how many hits the player has: ");
hits = keyboard.nextInt();
System.out.print("Enter the number of walks the player has: ");
walks = keyboard.nextInt();
System.out.print("Enter the number of sacrifice flies the player has: ");
sacFlies = keyboard.nextInt();
System.out.print("Enter the number of hits by pitch the player has: ");
hitsByPitch = keyboard.nextInt();
System.out.print("Enter the amount of at bats the player has: ");
atBats = keyboard.nextInt();
years[index] = ((hits + walks + hitsByPitch) / atBats+ walks+ hitsByPitch +sacFlies);
}
printOnBasePercentage(name, startYear, years);
}
public static void printOnBasePercentage(String name, int startYear, double []years){
for (int index = 0; index < years.length; index++){
System.out.println("\n" + name + "'s On Base Percentage");
System.out.printf("For Year: " +startYear + " " + "%.3f", years[index]);
}
}
The problem is you use one changeable variable in the both loops. In the main method you increment startYear variable and after that you pass this changed variable in the printonBasePercentage method. Try to replace this line:
System.out.print("For Year: "+ startYear++);
by:
System.out.print("For Year: "+ startYear + index);

Why does my code exit and not accept the "yes" pulled in with a Scanner or the one hardcoded in? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
It looks like the Scanner is being used correctly here and being assigned to a variable correctly but I Cannot figure out what is going on. When I play this game in the code, the INT gets pulled in just fine. The strings will not get pulled in for some reason and even if I hardcode "yes" for the string it still exits the code.
package testTraining;
import java.util.Scanner;
public class GuessingGame {
static int gamesPlayed; // The number of games played.
static int gamesWon; // The number of games won.
public static void main(String[] args) {
gamesPlayed = 0;
gamesWon = 0; // This is actually redundant, since 0 is
// the default initial value.
System.out.println("Let's play a game. I'll pick a number between");
System.out.println("1 and 100, and you try to guess it.");
String yesno = "yes";
Scanner yesScan = new Scanner(System.in);
do {
playGame(); // call subroutine to play one game
System.out.print("Would you like to play again? ");
yesno = yesScan.next();
} while (yesno == "yes");
System.out.println();
System.out.println("You played " + gamesPlayed + " games,");
System.out.println("and you won " + gamesWon + " of those games.");
System.out.println("Thanks for playing. Goodbye.");
} // end of main()
static void playGame() {
Scanner guessScan = new Scanner(System.in);
int computersNumber; // A random number picked by the computer.
int usersGuess; // A number entered by user as a guess.
int guessCount; // Number of guesses the user has made.
gamesPlayed++; // Count this game.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a randomly
// chosen integer between 1 and 100, inclusive.
guessCount = 0;
System.out.println();
System.out.print("What is your first guess? ");
while (true) {
usersGuess = guessScan.nextInt(); // Get the user's guess.
guessCount++;
if (usersGuess == computersNumber) {
System.out.println("You got it in " + guessCount
+ " guesses! My number was " + computersNumber);
gamesWon++; // Count this win.
break; // The game is over; the user has won.
}
if (guessCount == 6) {
System.out.println("You didn't get the number in 6 guesses.");
System.out.println("You lose. My number was " + computersNumber);
break; // The game is over; the user has lost.
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
System.out.print("That's too low. Try again: ");
else if (usersGuess > computersNumber)
System.out.print("That's too high. Try again: ");
}
System.out.println();
} // end of playGame()
} // end of class GuessingGame
You need to compare strings with .equals("yes") instead of == "yes"

"Enter another number (Y/N?)" process starting over instead of continuing when "Y"

I have two programs:
Score.java set to do the following:
read scores from the keyboard and print their average.
The scores will be numeric and may include a decimal part.
For example a score might be 8.73 or some such. Different contests will have different numbers of judges. It will keep asking for and reading in scores until the user types 'done'. The program will then print the total score, the number of scores and the average score. The program will then prompt the user to see if there are any more contestants. If there are begin prompting for scores again. If there are no more then exit the program." I have it set to stop the program when you enter "N", and set to add future entries to the calculation after entering "Y".
import java.util.Scanner;
// This is the Score program
// Written by me
public class Score
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = sum + num;
cnt = cnt + 1;
System.out.print("enter number: ");
ans = game.next();
}
System.out.println(cnt);
System.out.println(sum);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
While the above process works, I cannot get my second program, Olympic.java, to work properly after typing "Y" to add more scores. Instead, it starts a whole new calculation of average instead of adding to the previous calculations:
import java.util.Scanner;
// This is the Olympic program
// Written by me
public class Olympic
{
public static void main(String args[])
{
Scanner game = new Scanner(System.in);
double num = 0.0;
double sum = 0.0;
int cnt = 0;
double highscore = Double.MAX_VALUE;
double lowscore = Double.MIN_VALUE;
while (true)
{
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
System.out.print("enter number: ");
String ans = game.next();
lowscore = game.nextDouble();
highscore = game.nextDouble();
while (!ans.equals("done"))
{
num = Double.parseDouble(ans);
sum = (sum + num) - lowscore - highscore;
cnt = cnt + 1;
System.out.print("enter number: ");
if (num > highscore)
{
highscore = num;
}
if (num < lowscore)
{
lowscore = num;
}
ans = game.next();
}
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equals("Y"))
break;
}
}
}
So I did a really quick test
public static void main(String[] args) {
Scanner game = new Scanner(System.in);
while (true) {
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
System.out.println("I'm free");
}
And this will exit fine.
As to your second problem. I think your logic is a little skewed. You could try something like...
Scanner game = new Scanner(System.in);
double num = 0;
double sum = 0;
int cnt = 0;
while (true) {
System.out.println("Enter as many non-negative integers as you like ");
System.out.println("one at a time and I will find the average");
System.out.println("Enter done to stop entering numbers");
double lowscore = Double.MAX_VALUE;
double highscore = 0;
System.out.print("enter number: ");
String ans = game.next();
while (!ans.equals("done")) {
num = Double.parseDouble(ans);
lowscore = Math.min(lowscore, num);
highscore = Math.max(highscore, num);
sum += num;
cnt++;
System.out.print("enter number: ");
if (num > highscore) {
highscore = num;
}
if (num < lowscore) {
lowscore = num;
}
ans = game.next();
}
sum -= lowscore;
sum -= highscore;
System.out.println("Throwing out low score " + lowscore + " and high score " + highscore);
System.out.println("Total Score " + sum + " count scores " + cnt + " avg score " + sum / cnt);
System.out.println("Enter another contestant (Y/N)?");
String str = game.next();
if (!str.equalsIgnoreCase("Y")) {
break;
}
}
This will output...
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 2
enter number: 3
enter number: 4
enter number: 5
enter number: 6
enter number: 7
enter number: 8
enter number: 9
enter number: 10
enter number: done
Throwing out low score 1.0 and high score 10.0
Total Score 44.0 count scores 10 avg score 4.4
Enter another contestant (Y/N)?
y
Enter as many non-negative integers as you like
one at a time and I will find the average
Enter done to stop entering numbers
enter number: 1
enter number: 12
enter number: 13
enter number: 14
enter number: 15
enter number: 16
enter number: 17
enter number: 18
enter number: 19
enter number: 20
enter number: done
Throwing out low score 1.0 and high score 20.0
Total Score 168.0 count scores 20 avg score 8.4
Enter another contestant (Y/N)?
n
As to your exception. When using Scanner.nextDouble, it will throw an exception if the input is not parsable as a double. You will need to deal with this situation as you see fit...

Code seems to skip over if or for loop

When I enter input that satisfies everything and doesn't trigger any of my errors, the program just exits after last input like it is skipping over the for or if loop.
Also after System.out.printf("Enter the name of your second species: "); it won't allow for any input, it just skips to the next prompt. I'm not sure why that is. The section above it asking for the first species' info works fine.
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species: ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
This for the predictPopulation():
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
This is because you never print anything after Species 2 overtakes Species 1, except in the very special case that Species 2 and Species 1 have exactly the same population in some year.
This is because, when you enter Species 1's growth rate, you enter an integer, and then press Enter. keyboard.nextInt() swallows the integer, but leaves the newline on the input-buffer, so the subsequent keyboard.nextLine() thinks there's an empty line there waiting for it.

how to check the int range in java and limit it only 5digits

Please help with my assignment. Here is the question:
Create a separate test driver class
called TestEmployeePayroll that will
test the EmployeePayroll class by
performing the following:
Prompt the user to enter the
employees’ ID number, First name, Last
name, Pay Category and Hours worked
(one at a time).
The user entry for employees ID
number must be exactly 5 digits long.
The user entry for Category must only
be accepted if it is in the range 1
to 4.
The user entry for Hours worked
must only be accepted if it is the
range 1 to 80.
This is what I did till now:
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
EmployeePayRoll obj1 = new EmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: "+ " ");
String EmployeeID = input.nextLine();
//How to check the range here if int is 5 digits long or not ?
System.out.println("Enter the first Name: "+ " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: "+ " ");
double PayCategory = input.nextDouble();
System.out.println("Enter the number of hours worked: "+ " ");
double HoursWorked = input.nextDouble();
}
}
You will probably want to use Integer.parseInt().
You can count the length of a String and then convert it to number, Oli Charlesworth told you how to convert it, or you can measure the number. It depends on what you want. Is 012345 a valid ID? It's a 6 char String but it is less than the biggest 5 digits number.
I think you almost got it...
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
// ... get the values, as you are doing already
// validate input
int employeeIdAsInteger = validateAndConvertEmployeeId(EmployeeId);
int payCategoryAsInteger = validateAndConvertPayCategory(PayCategory);
// ... and so on
}
private int validateAndConvertEmployeeId(String employeeId) {
// The user entry for employees ID number must be exactly 5 digits long.
if (employeeId == null || employeeId.trim().length() != 5) {
throw new IllegalArgumentException("employee id must be exactly 5 digits long");
}
// will throw an exception if not a number...
return Integer.parseInt(employeeId);
}
// ...
}
Depending on your objectives & constraints, you could look into the Pattern class and use a regular expression.
You can check for conditions like this.
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args) {
TestEmployeePayRoll obj1 = new TestEmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: " + " ");
String EmployeeID = input.nextLine();
if (EmployeeID.trim().length() != 5) {
System.out.println("--- Enter valid Employee ID number ---");
}
System.out.println("Enter the first Name: " + " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: " + " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: " + " ");
double PayCategory = input.nextDouble();
Double pay = new Double(PayCategory);
if (pay.isNaN()) {
System.out.println("***** Enter a valid Pay Category *****");
}
if (!(PayCategory >= 0 && PayCategory <= 5)) {
System.out.println(" --- PayCategory must be between 0 and 5");
}
System.out.println("Enter the number of hours worked: " + " ");
double HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if (hours.isNaN()) {
System.out.println("--- Enter a valid hours value ----");
} else {
if (!(HoursWorked >= 1 && HoursWorked <= 80)) {
System.out.println("--- Enter value between 1 and 80 ---");
}
}
}
}

Categories

Resources