My while loop prints menu twice [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I wrote this program called soccer team roaster. It stores player's jerseys number and player rating. And then does what ever the user wants to do with it within the menu option. But for some reason the menu option keeps on printing twice. I've been informed that its because when I ask for the int input for PlayerRating[i] it takes the Enter button and an input when I first ask for the user's input for String "menuOption". Can someone help?
Here is the code
import java.util.Scanner;
public class SoccerTeamRoaster {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int JERSY_NUMS = 5;
int[] JersyNumber = new int[JERSY_NUMS];
int[] PlayerRating = new int[JERSY_NUMS];
String[] jPut = new String[JERSY_NUMS];
int i = 0;
boolean quit = false;
for (i = 0; i < JERSY_NUMS; i++) {
System.out.println("Enter player " + (i + 1) + "'s jersey number: ");
JersyNumber[i] = sc.nextInt();
System.out.println("Enter player " + (i + 1) + "'s rating: ");
PlayerRating[i] = sc.nextInt();
System.out.println("");
}
System.out.println("");
System.out.println("ROSTER");
int N = 0;
for (N = 0; N < JERSY_NUMS; N++) {
System.out.println("Player " + (N + 1) + " -- Jersey number: " + JersyNumber[N] + ", Rating: " + PlayerRating[N]);
}
while (!quit) {
String Stg = "MENU\n"
+ "u - Update player rating\n"
+ "a - Output players above a rating\n"
+ "r - Replace player\n"
+ "o - Output roster\n"
+ "q - Quit\n";
System.out.println("");
System.out.println(Stg);
System.out.println("Choose an option: ");
String menuOption = "?";
menuOption = sc.nextLine();
boolean correctInput = false;
if (menuOption.equals("u") || menuOption.equals("a") || menuOption.equals("r") || menuOption.equals("o") || menuOption.equals("q")) {
correctInput = true;
menuOption = menuOption.trim();
} else {
correctInput = false;
}
if (menuOption.equals("u")) {
System.out.println("Enter jersey number: ");
int jerseyNum = sc.nextInt();
System.out.println("New rating for player: ");
int newRate = sc.nextInt();
int M = 0;
for (M = 0; M < JERSY_NUMS; M++) {
if (JersyNumber[M] == jerseyNum) {
PlayerRating[M] = newRate;
}
}
} else if (menuOption.equals("a")) {
System.out.println("Enter a rating: ");
int rating = sc.nextInt();
int k = 0;
for (k = 0; k < JERSY_NUMS; k++) {
if (PlayerRating[k] > rating) {
System.out.println("Player " + (k + 1) + " -- Jersey Number: " + JersyNumber[k] + ", Rating: " + PlayerRating[k]);
}
}
} else if (menuOption.equals("o")) {
System.out.println("ROSTER");
int J = 0;
for (J = 0; J < JERSY_NUMS; J++) {
System.out.println("Player " + (J + 1) + " -- Jersey number: " + JersyNumber[J] + ", Rating: " + PlayerRating[J]);
}
} else if (menuOption.equals("q")) {
quit = true;
} else if (menuOption.equals("r")) {
System.out.println("Enter jersey number: ");
int jerNum = sc.nextInt();
int l = 0;
for (l = 0; l < JERSY_NUMS; l++) {
if (JersyNumber[l] == jerNum) {
System.out.println("Enter new jersey number: ");
JersyNumber[l] = sc.nextInt();
System.out.println("Enter new player rating: ");
PlayerRating[l] = sc.nextInt();
}
}
int a = 0;
for (a = 0; a < JERSY_NUMS; a++) {
System.out.println("Player " + (a + 1) + " -- Jersey number: " + JersyNumber[a] + ", Rating: " + PlayerRating[a]);
}
}
}
return;
}
}

The reason why it prints two times is because of this code...
menuOption = sc.nextLine();
just change it to
menuOption = sc.next();
now, it only prints one time

You use Scanner#nextInt to get jersey numbers and rates. But Scanner#nextInt does not consume the last newline character of input, and thus that newline character is consumed when Scanner#nextLine is called after that.
So you have to call Scanner#nextLine once to throw aray the newline character before while loop.

Related

Declaring String Variables within a while loop without it looping all throughout - java

I am stuck at a part where I am supposed to declare a string variable called "phrase", where it shouldn't loop, all the way through.
to give you an idea my task is: Similar to Option 1 except the user enters 'N' (instead of 'Q') when they are done entering results for the first team. Then, the program inputs a second team name and its results until 'Q' is entered. Outputs two statements, like the statements in option 1 followed by a third statement that says which team is in first place (based on the number of points)
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal // how would I make this appear in the same while loop?
L
L
O
L
L
W
L
L
Q
Sample output:
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
UPDATE:
My code:
else if (option == 2){
int counter = 0;
int totalpoints = 0;
String phrase = keyboard.next();
while(go){
String letter = keyboard.next();
if (letter.equals("W")){
pointsW++;
}
else if (letter.equals("L")){
pointsL++;
}
else if (letter.equals("O")){
pointsO++;
}
counter++;
if (letter.equals("N")){
totalpoints = pointsW + pointsL + pointsO;
counter--;
go = false;
}
}
int counter2 = 0;
int totalpoints2 = 0;
pointsW = 2;
pointsL = 0;
pointsO = 1;
String phrase2 = keyboard.next();
while (go2){
String letter2 = keyboard.next();
if (letter2.equals("W")){
pointsW++;
}
else if (letter2.equals("L")){
pointsL++;
}
else if (letter2.equals("O")){
pointsO++;
}
counter2++;
if (letter2.equals("Q")){
counter2--;
totalpoints2 = pointsW + pointsL + pointsO;
go2 = false;
}
}
System.out.println(phrase + " has played "+counter+" games and has earned "+totalpoints+" points");
System.out.println(phrase2 + " has played "+counter2+" games and has earned "+totalpoints2+" points");
if (totalpoints > totalpoints2){
System.out.println(phrase + " is in first place by "+(totalpoints - totalpoints2) + " points");
}else{
System.out.println(phrase2 + " is in first place by "+(totalpoints2 - totalpoints) + " points");
}
}
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
The issue: This is the output I am getting "Montreal played 8 games and has earned 11 points" where instead it should be "Montreal has played 8 games and has earned 3 points"
The output I am getting
You can reuse the same variables for individual points i.e. pointsW and pointsO because you do not want to retain their values till the end where you are publishing the results. The same is the case with the variable for the loop condition i.e. go and the variable used for inputting win/loss i.e. letter.
You will need arrays or different variables for storing total points, countings, and team name.
import java.util.Scanner;
public class Standings {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
int pointsW = 0;
int pointsO = 0;
String letter;
boolean go = true;
if (option == 2) {
// Variables for total points, counting, and name for the first team
int playedGamesTeamOne = 0;
int teamOnePoints = 0;
String teamOneName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamOne++;
if (letter.equals("N")) {
teamOnePoints = pointsW + pointsO;
playedGamesTeamOne--;
go = false;
}
}
// Reset common variables
go = true;
pointsW = 0;
pointsO = 0;
// Variables for total points, counting, and name for the second team
int playedGamesTeamTwo = 0;
int teamTwoPoints = 0;
String teamTwoName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamTwo++;
if (letter.equals("Q")) {
teamTwoPoints = pointsW + pointsO;
playedGamesTeamTwo--;
go = false;
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned "
+ teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned "
+ teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out
.println(teamOneName + " is in first place by " + (teamOnePoints - teamTwoPoints) + " points");
} else {
System.out
.println(teamTwoName + " is in first place by " + (teamTwoPoints - teamOnePoints) + " points");
}
}
}
}
A sample run:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
you can use this code for option two
Scanner keyboard = new Scanner(System.in);
int teamCounter = 1;
//String[] teamsNames = new String[2];
String teamOneName="";
String teamTwoName="";
//int[] playedGames = new int[2];
int playedGamesTeamOne = 0;
int playedGamesTeamTwo = 0;
//int[] points = new int[2];
int teamOnePoints = 0;
int teamTwoPoints = 0;
boolean firstTimeTeam1 = true;
boolean firstTimeTeam2 = true;
while (teamCounter <= 2) {
if (teamCounter == 1) {
if (firstTimeTeam1) {
teamOneName = keyboard.nextLine();
firstTimeTeam1 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamOnePoints += 2;
playedGamesTeamOne++;
} else if (letter.equals("L")) {
playedGamesTeamOne++;
} else if (letter.equals("O")) {
teamOnePoints += 1;
playedGamesTeamOne++;
} else if (letter.equals("N")) {
teamCounter++;
}
} else {
if (firstTimeTeam2) {
teamTwoName = keyboard.next();
firstTimeTeam2 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamTwoPoints += 2;
playedGamesTeamTwo++;
} else if (letter.equals("L")) {
playedGamesTeamTwo++;
} else if (letter.equals("O")) {
teamTwoPoints += 1;
playedGamesTeamTwo++;
} else if (letter.equals("Q")) {
teamCounter++;
}
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned " + teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned " + teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out.println(teamOneName + " is in first place by " + (teamOnePoints-teamTwoPoints) + " points");
} else {
System.out.println(teamTwoName + " is in first place by " + (teamTwoPoints-teamOnePoints) + " points");
}

How to update data in array with user input values with java?

I am trying to create a garage with three floors and three lots on each floor. I am fairly new to java, so I am really having trouble with this. I want to ask the user if they are leaving (0) or parking (1), then which floor they were on or want to be on, and which lot they were in or want to be in. Then I want to use that data and update the array to show Reserved for that spot. But what I have isn't working. Any help would be appreciated.
import java.util.Scanner;
public class Parking {
public static void main(String[] args) {
String parkingspace[][] = new String[3][3];
for(int floor=0; floor<parkingspace[0].length; floor++) {
for(int lot=0; lot<parkingspace[floor].length; lot++) {
parkingspace[floor][lot]="Empty";
}
}
Scanner scan = new Scanner(System.in);
while(true){
for(int floor=0; floor<parkingspace[0].length; floor++) {
for(int lot=0; lot<parkingspace[floor].length; lot++) {
parkingspace[floor][lot]="Empty";
System.out.print("Floor "+floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
System.out.println();
}
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
if(input==1) {
if(parkingspace[floor][lot].equals("Empty")) {
if(input==1) {
parkingspace[floor][lot]="Reserved";
System.out.print("Floor "+ floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
}else if(input==0){
parkingspace[floor][lot]="Empty";
System.out.print("Floor "+ floor + ": Lot #" +lot +": [" + parkingspace[floor][lot]+"] ");
}
}
}
}
You are close. You need to delete the part where you reset all the parking spaces. Also, you probably don't need to print anything after the user has input their choice.
For extra credit, you need to add error checking. What if the user enters space #12345? Or "Hello"? You should handle these cases.
Here's your code, slightly modified:
public static void main(String[]args) {
String parkingspace[][] = new String[3][3];
// Make these variables to be consistent
final String empty = "EMPTY";
final String reserved = "RSRVD";
// Initialize
for (int floor = 0; floor < parkingspace.length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = empty;
}
}
Scanner scan = new Scanner(System.in);
while (true) {
// Print the parking lot
for (int floor = 0; floor < parkingspace.length; floor++) {
System.out.print("Floor " + floor + ": ");
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
System.out.print("Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
System.out.println();
}
// Get user input
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
// Update parking lot
if (input == 1 && parkingspace[floor][lot].equals(empty)) {
parkingspace[floor][lot] = reserved;
}
else if (input == 0 && parkingspace[floor][lot].equals(reserved)) {
parkingspace[floor][lot] = empty;
}
}
}
You have a redundant if(input == 1) check. It could just be:
if (input == 1 && parkingSpace[floor][lot].equals("Empty")) {
parkingSpace[floor][lot] = "Reserved";
}
Also, your code works for me. I did have to add several brackets to close off methods and the class, though.
import java.util.Scanner;
public class Parking {
public static void main(String[] args) {
String parkingspace[][] = new String[3][3];
for (int floor = 0; floor < parkingspace[0].length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = "Empty";
}
}
Scanner scan = new Scanner(System.in);
while (true) {
for (int floor = 0; floor < parkingspace[0].length; floor++) {
for (int lot = 0; lot < parkingspace[floor].length; lot++) {
parkingspace[floor][lot] = "Empty";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
System.out.println();
}
System.out.println("Are you leaving(0) or parking(1)?");
int input = scan.nextInt();
System.out.println("Which floor (0, 1, 2)?");
int floor = scan.nextInt();
System.out.println("Which lot (0, 1, 2)?");
int lot = scan.nextInt();
if (input == 1) {
if (parkingspace[floor][lot].equals("Empty")) {
if (input == 1) {
parkingspace[floor][lot] = "Reserved";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
} else if (input == 0) {
parkingspace[floor][lot] = "Empty";
System.out.print(
"Floor " + floor + ": Lot #" + lot + ": [" + parkingspace[floor][lot] + "] ");
}
}
}
}
}

How can I quit the game whenever e is pressed at any time?

If someone presses e, I want my game to stop at any time in the game.
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time! ");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
int theAnswer = input.nextInt();
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}
Instead of just "int theAnswer = input.nextInt();" write this:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equal("e")) {
System.out.println("Exiting the game...")
break;
}
else {
theAnswer = Integer.parseInt(nextIn);
}
I obviously haven't accounted for exceptions, but you can if you want.
So altogether it looks like this:
public class Game{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int points = 0;
int multiply;
System.out.println("press e to exit the game at any time!");
System.out.println("please enter a number");
int yourNumber = input.nextInt();
for (multiply = 0; multiply<= 10; multiply++){
int yourAnswer = yourNumber * multiply;
System.out.println(yourNumber + " x " + multiply + " = ? ");
//new part:
String nextIn = input.next();
int theAnswer = 0;
if (nextIn.equals("e")) {
System.out.println("Exiting the game...")
break;
} else {
theAnswer = Integer.parseInt(nextIn);
}
for (int tries = 1; tries<= 4; tries++){
if (theAnswer == yourAnswer){
points = points + 5;
System.out.println("you have " + points + " points");
break;
}
else{
System.out.println("Your answer : " + theAnswer + " is wrong, please try again. Attempts : " + tries + " out of 4");
theAnswer = input.nextInt();
points--;
if (tries == 4){
System.out.println("sorry maximum attempts!!! moving to the next question");
tries++;
break;
}
}
}
}
}
}

Player 1 doesn't get his turn in game of Nim

I am developing a game of nim which will be played by 2 people. Problem is that after 1 iteration, it keeps switching to player2 even though it is not his turn.Player 1 gets completely ignored until the end of the game. Here is my code:
int A = 3;
int B = 4;
int C = 5;
Scanner input = new Scanner(System.in);
Scanner x = new Scanner(System.in);
System.out.println("Player 1 name :");
String player1 = input.nextLine();
System.out.println("Player 2 name :");
String player2 = input.nextLine();
System.out.println(" A: " + A + " B: " + B + " C: " + C);
do {
System.out.println(player1 + " choose a pile : ");
String choose = input.nextLine();
if (choose.equals("A")) {
System.out.println("How many to remove from pile A:");
int br = input.nextInt();
if (br == 1) {
A = A - 1;
}
if (br == 2) {
A = A - 2;
} else {
A = A - 3;
}
}
Used same if statements for B & C then repeated all and just switched player.
System.out.println(" A: " + A + " B: " + B + " C: " + C);
System.out.println(player2 + " choose a pile:");
String choose2 = x.nextLine();
if (choose2.equals("A")) {
System.out.println("How many to remove from pile A:");
int br = input.nextInt();
if (br == 1) {
A = A - 1;
}
if (br == 2) {
A = A - 2;
} else {
A = A - 3;
}
}
System.out.println(" A: " + A + " B: " + B + " C: " + C);
} while (A != 0 || B != 0 || C != 0);
Your if is wrong, because will enter in your else condition if you chose 1
This error is happening because you are using the same scanner that is alredy used, soo only the first iteration will work.
One way of solving this problem is initializate the scanner in every iteration
Something like this inside your Do While:
Scanner sc = new Scanner(System.in);
String choose = sc.nextLine();
And for the second one:
Scanner sc2 = new Scanner(System.in);
String choose2 = sc2.nextLine();

Java Change Prompt Order

I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.

Categories

Resources