Rock Paper Scissors Game (Menu Method) - java

So as it says in the title, I am trying to create a RPS Game with a Menu as a Method, the thing is I don't know how to call inputs from that menu at any point.
For a better idea, this is my code:
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String player1choice, player1Name;
int mainMenu,subMenu;
String again;
player1Name = "";
welcomeBanner ();
mainMenu = getMenu (keyboard);
if (mainMenu == 1)
{
keyboard.nextLine();
player1Name = getAName (keyboard);
for (int i = 0; i < 50; ++i) System.out.println();
main (null);
}
if (mainMenu == 2)
{
System.out.println("Welcome "+player1Name); //add name input
subMenu =getsubMenu (keyboard);
System.out.println("You have chosen: "); //add option chosen
System.out.println("Cpu has got, It's a Tie!");//cpuChoice add
}
if (mainMenu == 3)
{
keyboard.nextLine();
String exitRequest;
System.out.print("Are you sure you want to exit? (Y/N): ");
exitRequest = keyboard.nextLine ();
if (exitRequest.equals("y") || exitRequest.equals("Y"))
{
System.out.println("Good Bye!");
System.exit(0);
}
else if (exitRequest.equals("n") || exitRequest.equals("N"))
{
for (int i = 0; i < 50; ++i) System.out.println();
main(null);
}
}
}
static void welcomeBanner()
{
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("* Welcome To The Rock, Paper, Scissors Game *");
System.out.println("*----------------------------------------------------------*");
System.out.println("* Created by: Jonathan Gutierrez, and I am NoxBot! *");
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("");
}
static int getMenu (Scanner aKeyboard)
{
int playermenuChoice;
System.out.println("1. Enter Player Name");
System.out.println("2. Play a Game");
System.out.println("3. Exit Application");
System.out.println("");
System.out.print("Enter your choice: ");
playermenuChoice = aKeyboard.nextInt();
return playermenuChoice;
}
static int getsubMenu (Scanner aKeyboard)
{
int submenuChoice;
System.out.println("Enter 1 for Rock");
System.out.println("Enter 2 for Paper");
System.out.println("Enter 3 for Scissors");
System.out.println("");
System.out.print("Enter choice: ");
submenuChoice = aKeyboard.nextInt();
return submenuChoice;
}
static String getAName (Scanner aKeyboard)
{
String player1Info;
System.out.print("Enter your name: ");
player1Info = aKeyboard.nextLine ();
return player1Info;
}
static String computerChoice ()
{
String cpuChoice;
cpuChoice = "";
Random randomNumbers = new Random();
int cpu = randomNumbers.nextInt (2) + 1;
switch (cpu)
{
case 1:
cpuChoice = "Rock";
break;
case 2:
cpuChoice = "Paper";
break;
case 3:
cpuChoice = "Scissors";
break;
}
return cpuChoice;
}
So when the player chooses option 1, program asks to enter the name of the player, and i want to use that input at any point (most specifically when mainMenu ==2). How can i do that?
EDIT: this is my new code:
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String player1choice, player1Name, subMenu;
int mainMenu;
String again;
player1Name = "";
welcomeBanner ();
mainMenu = getMenu (keyboard);
if (mainMenu == 1)
{
keyboard.nextLine();
player1Name = getAName (keyboard);
for (int i = 0; i < 50; ++i) System.out.println();
welcomeBanner ();
mainMenu = getMenu (keyboard);
System.out.println("");
System.out.println("Welcome " + player1Name);
System.out.println("");
}
if (mainMenu == 2)
{
subMenu =enterPlayersChoice (keyboard);
keyboard.nextLine();
String cmpu = computerChoice ();
for(int i = 0; i < 3; i ++)
if (subMenu.equals(cmpu))
System.out.println("It's a tie!");
else if (subMenu.equals("rock"))
if (cmpu.equals("scissors"))
System.out.println("Rock crushes scissors. You win!!");
else if (cmpu.equals("paper"))
System.out.println("Paper eats rock. You lose!!");
else if (subMenu.equals("paper"))
if (cmpu.equals("scissors"))
System.out.println("Scissor cuts paper. You lose!!");
else if (cmpu.equals("rock"))
System.out.println("Paper eats rock. You win!!");
else if (subMenu.equals("scissors"))
if (cmpu.equals("paper"))
System.out.println("Scissor cuts paper. You win!!");
else if (cmpu.equals("rock"))
System.out.println("Rock breaks scissors. You lose!!");
else System.out.println("Invalid user input.");
System.out.println("");
}
if (mainMenu == 3)
{
keyboard.nextLine();
String exitRequest;
System.out.print("Are you sure you want to exit? (Y/N): ");
exitRequest = keyboard.nextLine ();
if (exitRequest.equals("y") || exitRequest.equals("Y"))
{
System.out.println("Good Bye!");
System.exit(0);
}
else if (exitRequest.equals("n") || exitRequest.equals("N"))
{
for (int i = 0; i < 50; ++i) System.out.println();
main(null);
}
}
}
static void welcomeBanner()
{
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("* Welcome To The Rock, Paper, Scissors Game *");
System.out.println("*----------------------------------------------------------*");
System.out.println("* Created by: Jonathan Gutierrez, and I am NoxBot! *");
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("");
}
static int getMenu (Scanner aKeyboard)
{
int playermenuChoice;
System.out.println("1. Enter Player Name");
System.out.println("2. Play a Game");
System.out.println("3. Exit Application");
System.out.println("");
System.out.print("Enter your choice: ");
playermenuChoice = aKeyboard.nextInt();
return playermenuChoice;
}
public static String enterPlayersChoice(Scanner aKeyboard)
{
String input = "";
System.out.print("You have a choice of picking rock, paper, or scissors: ");
input = aKeyboard.nextLine();
String inputLower = input.toLowerCase();
return inputLower;
}
static String getAName (Scanner aKeyboard)
{
String player1Info;
System.out.print("Enter your name: ");
player1Info = aKeyboard.nextLine ();
return player1Info;
}
public static String computerChoice ()
{
String cpuChoice;
cpuChoice = "nothing";
Random randomNumbers = new Random();
int cpu = randomNumbers.nextInt (2) + 1;
switch (cpu)
{
case 1:
cpuChoice = "rock";
break;
case 2:
cpuChoice = "paper";
break;
case 3:
cpuChoice = "scissors";
break;
}
return cpuChoice;
}
}
To finish this i want the game to display a message whether player wins or lose, but it is being skipped (mainMenu ==2) any ideas?

Here's a way of rearranging your existing application in a different manner. Some of the major changes include making all methods non-static except the main method, and creating a RockPaperScissorsNew object for the application's point of entry. I've also added class variables so you don't need to pass your Scanner around as an object to all of your methods.
To answer your original question of how you're able to re-use the input entered by the user, the solution I provided is to retain that information within the class variable.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsNew {
//Class variables
Scanner keyboard;
String player1choice, player1Name; //Name will be stored here.
int mainMenu,subMenu;
public RockPaperScissorsNew()
{
keyboard = new Scanner(System.in);
welcomeBanner(); //Display the welcome banner once.
while(true) //Repeatedly display the main menu.
getChoice(); //Get the user's choice
}
public void getChoice()
{
int choice = -1; //Set choice to fail first.
while (choice > 3 || choice < 0) //Wait until user choice passes.
{
choice = getMenu();
}
if (choice == 1) { //Choose your sub option.
getAName(); // Get the user name.
System.out.println("Your name is " + player1Name); //Saved
}
if (choice == 2)
getsubMenu();
if (choice == 3)
System.exit(0);
}
public void welcomeBanner()
{
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("* Welcome To The Rock, Paper, Scissors Game *");
System.out.println("*----------------------------------------------------------*");
System.out.println("* Created by: Jonathan Gutierrez, and I am NoxBot! *");
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("");
}
public int getMenu ()
{
int playermenuChoice;
System.out.println("1. Enter Player Name");
System.out.println("2. Play a Game");
System.out.println("3. Exit Application");
System.out.println("");
System.out.print("Enter your choice: ");
playermenuChoice = Integer.parseInt(keyboard.nextLine().trim());
return playermenuChoice;
}
public int getsubMenu ()
{
int submenuChoice;
System.out.println("Enter 1 for Rock");
System.out.println("Enter 2 for Paper");
System.out.println("Enter 3 for Scissors");
System.out.println("");
System.out.print("Enter choice: ");
submenuChoice = Integer.parseInt(keyboard.nextLine().trim());
return submenuChoice;
}
//This method has been changed to use the class variable, and no longer
//returns a string.
public void getAName ()
{
//String player1Info;
System.out.print("Enter your name: ");
player1Name = keyboard.nextLine ();
//return player1Info;
}
public String computerChoice ()
{
String cpuChoice;
cpuChoice = "";
Random randomNumbers = new Random();
int cpu = randomNumbers.nextInt (2) + 1;
switch (cpu)
{
case 1:
cpuChoice = "Rock";
break;
case 2:
cpuChoice = "Paper";
break;
case 3:
cpuChoice = "Scissors";
break;
}
return cpuChoice;
}
public static void main(String...args)
{
new RockPaperScissorsNew();
}
}

Related

Missing second value memory calculator

My program runs but when I need it to calculate what I need it to do (add, subtract, multiply, divide) it just puts in the value that I typed in and won't do the operation I tell it to do, it just displays the menu again. How do I fix it so it can do the function it needs to do and also loop back to the menu to do another function? (ex. I want to add 2 and 2 together then turn around and multiply 3 and 2)
public static void main(String[] args) {
Testt calc = new Testt();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
Testt calc = new Testt();
int choice;
do {
System.out.println("Hello, welcome to the menu");
System.out.println("Select one of the following items from the menu:");
System.out.println("1) Add ");
System.out.println("2) Subtract ");
System.out.println("3) Multiply ");
System.out.println("4) Divide ");
System.out.println("5) Clear ");
System.out.println("6.Quit");
System.out.println ("Please choice an option from the menu:");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 && choice < 1);
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return choice;
}
public static double getOperand(String prompt) {
return 0;
}
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue = operand2 - currentValue;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue = operand2 * currentValue;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue = operand2 / currentValue;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
From getCurrentValue() you are always returning 0.
You need to return current value.
Also if you want to loop back to same thing you can put all this in while(true) loop. like this:
public static int displayMenu() {
Scanner input = new Scanner(System.in);
Demo calc = new Demo();
int choice;
System.out.println("Hello, welcome to the menu");
System.out.println("Select one of the following items from the menu:");
System.out.println("1) Add ");
System.out.println("2) Subtract ");
System.out.println("3) Multiply ");
System.out.println("4) Divide ");
System.out.println("5) Clear ");
System.out.println("6.Quit");
while(true){
System.out.println ("Please choice an option from the menu:");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
continue;
}
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
}
}

Inconsistent output after the "while loop" in JAVA

I am new to JAVA and wrote a Nim game project, which includes Nimsys and Nimplayer.
Everything seems fine. When I run through the test file, the result is CORRECT.
However, when it goes to playing again, there's an extra space suddenly shows up, and I cannot
figure it out. There could be some mistakes. Any help is highly appreciated.
The test results
import java.util.Scanner;
public class Nimsys {
int stoneBalance;
public static void main(String[] args) {
String playOrNot;
Scanner input = new Scanner(System.in);// Scanner
System.out.println("Welcome to Nim\n");
// bring two players in the main.
System.out.println("Please enter Player 1's name:");
NimPlayer player1 = new NimPlayer(); // bring player1 object to be used
String name1 = input.nextLine(); // set the string's name to be used
System.out.println("");
NimPlayer player2 = new NimPlayer(); // bring player2 object to be used
System.out.println("Please enter Player 2's name:");
String name2 = input.nextLine();
System.out.println("");
do {
// stone upper bound
System.out.println("Please enter upper bound of stone removal:");
int removeUpBound = input.nextInt();
System.out.println("");
// intital stone numbers
System.out.println("Please enter initial number of stones:");
int totalStone = input.nextInt();
System.out.println("");
NimPlayer numStone = new NimPlayer(); // bring new object to be used
numStone.initialStone(totalStone);
System.out.print(numStone.stoneBalance + " stones left:");
numStone.printStar(totalStone);
// while stoneBalance > 0, two players keep playing the game
while (numStone.stoneBalance > 0) {
// player1's turn and remove the stones; decision of winning
player1.enterName(name1); // pass the name to be used
player1.player1Turn();
int takeStone = input.nextInt();
while (takeStone > removeUpBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper bound limit or above 0. \n Please enter again.");
takeStone = input.nextInt();
}
numStone.removeStones(takeStone);
if (numStone.stoneBalance > 0) {
System.out.print(numStone.stoneBalance + " stones left:");
numStone.printStar(numStone.stoneBalance);
} else if (numStone.stoneBalance <= 0) {
System.out.println("Game Over\n" + name2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
player2.enterName(name2); // pass the name to be used
player2.player2Turn();
int takeStone2 = input.nextInt();
while (takeStone2 > removeUpBound || takeStone2 <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper bound limit or above 0. \n Please enter again.");
takeStone2 = input.nextInt();
}
numStone.removeStones(takeStone2);
if (numStone.stoneBalance > 0) {
System.out.print(numStone.stoneBalance + " stones left:");
numStone.printStar(numStone.stoneBalance);
} else if (numStone.stoneBalance <= 0) {
System.out.println("Game Over\n" + name1 + " wins!\n");
break;
}
}
System.out.println("Do you want to play again (Y/N):");
playOrNot = input.next();
} while (playOrNot.equals("Y"));
}
}
public class NimPlayer {
String player1;
String player2;
int stoneBalance;
int stars;
public void enterName(String name) {
player1 = name;
player2 = name;
}
public void initialStone(int startStones) {
stoneBalance = startStones;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void player1Turn() {
System.out.println(player1 + "'s turn - remove how many?\n");
}
public void player2Turn() {
System.out.println(player2 + "'s turn - remove how many?\n");
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
}
To entirely fix your 2 issues I would do the following -
input.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = input.nextLine();
Instead of
System.out.println("Do you want to play again (Y/N):");
playOrNot = input.next();

Java Array Issues with adding in the Array and Sorting alphabetically

I am having some trouble figuring out how to sort the array as well as adding another name to the array. I am relatively new at coding java and I cant seem to figure it out. (The trouble is in choice 4 and enterTVshow() )
Any suggestions on how to approach this?
Thanks
import java.io.*;
import java.util.Arrays;
public class JavaVision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String name[] = new String[48];
public static void main(String[] args) throws IOException {
int choice;
do {
System.out.println(" ");
System.out.println("Java TV Program Menu");
System.out.println("----------------------------");
System.out.println("What would you like to do?");
System.out.println("1. Add a TV Show");
System.out.println("2. Modify a TV Show");
System.out.println("3. Delete a TV Show");
System.out.println("4. Sort TV Shows");
System.out.println("5. Show All TV Shows");
System.out.println("6. Exit");
choice = Integer.valueOf(in.readLine()).intValue();
if(choice ==1) {
enterTVshow();
}
if(choice ==2) {
modTVshow();
}
if(choice ==3) {
deleteTVshow();
}
if (choice ==4) {
Arrays.sort(name);
for (int i = 0; i < name.length; i++) {
}
}
if(choice ==5) {
System.out.println(Arrays.toString(name));
}
}while (choice !=6);
}
private static void deleteTVshow() throws IOException {
String deleteTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("Which TV Show do you want to delete?");
deleteTVshow = in.readLine();
for(i = 0; i<=(x-1); i++) {
if(deleteTVshow.compareTo(name[i]) == 0) {
flag = x;
found = true;
}
}
if (found == false) {
System.out.println("There is no TV Show by that name.");
}
else {
for(i = flag; i <=(x-2); x++) {
name[i] = name[i+1];
}
x = x -1;
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void modTVshow() throws IOException {
String modTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("What is the TV Show you wish to modify?");
modTVshow = in.readLine();
for(i = 0; i<= (x-1); i++) {
if(modTVshow.compareTo(name[i]) == 0) {
flag = i;
found = true;
}
}
if (found == false) {
System.out.print("There is no TV show by that name.");
}
else {
System.out.print("Enter new Name: ");
name[flag] = in.readLine();
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void enterTVshow() throws IOException {
x = 0;
do {
System.out.print("Enter TV Show Name:");
name[x] = in.readLine();
x++;
System.out.print("Adding Show.....");
System.out.println(" ");
System.out.print("Type 'go back' to go back to the menu ");
}while((in.readLine().compareTo("go back")) !=0);
}
}
You are facing problem in sorting because you might have some null value in any of 48 elements of array. to handle this just make your own comparator for sort like below or avoid null value in array.
public class JavaVision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String name[] = new String[48];
public static void main(String[] args) throws IOException {
int choice;
do {
System.out.println(" ");
System.out.println("Java TV Program Menu");
System.out.println("----------------------------");
System.out.println("What would you like to do?");
System.out.println("1. Add a TV Show");
System.out.println("2. Modify a TV Show");
System.out.println("3. Delete a TV Show");
System.out.println("4. Sort TV Shows");
System.out.println("5. Show All TV Shows");
System.out.println("6. Exit");
choice = Integer.valueOf(in.readLine()).intValue();
if(choice ==1) {
enterTVshow();
}
if(choice ==2) {
modTVshow();
}
if(choice ==3) {
deleteTVshow();
}
if (choice ==4) {
sortArray(name);
}
if(choice ==5) {
System.out.println(Arrays.toString(name));
}
}while (choice !=6);
}
private static void deleteTVshow() throws IOException {
String deleteTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("Which TV Show do you want to delete?");
deleteTVshow = in.readLine();
for(i = 0; i<=(x-1); i++) {
if(deleteTVshow.compareTo(name[i]) == 0) {
flag = x;
found = true;
}
}
if (found == false) {
System.out.println("There is no TV Show by that name.");
}
else {
for(i = flag; i <=(x-2); x++) {
name[i] = name[i+1];
}
x = x -1;
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void modTVshow() throws IOException {
String modTVshow;
int flag = 0;
int i;
boolean found = false;
System.out.print("What is the TV Show you wish to modify?");
modTVshow = in.readLine();
for(i = 0; i<= (x-1); i++) {
if(modTVshow.compareTo(name[i]) == 0) {
flag = i;
found = true;
}
}
if (found == false) {
System.out.print("There is no TV show by that name.");
}
else {
System.out.print("Enter new Name: ");
name[flag] = in.readLine();
System.out.print("Type 'go back' to go back to the menu");
}while ((in.readLine().compareTo("go back")) !=0);
}
private static void enterTVshow() throws IOException {
System.out.println();
x = 0;
while(name[x]!=null){
x++;
}
do {
System.out.print("Enter TV Show Name:");
name[x] = in.readLine();
x++;
System.out.print("Adding Show.....");
System.out.println(" ");
System.out.print("Type 'go back' to go back to the menu ");
sortArray(name);
}while((in.readLine().compareTo("go back")) !=0);
}
public static void sortArray(String [] myArray){
Arrays.sort(myArray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return o1.compareTo(o2);
}});
}
}
remove the code does not convince me two for
for(i = 0; i<=(x-1); i++) {
if(deleteTVshow.compareTo(name[i]) == 0) {
flag = x; //should not change by flag=i; ?
found = true; // add break; ?
}
}
for rearranging the elements
for(i = flag; i <=(x-2); x++) { //increases why x? should not be i ++? i<=x condition?
name[i] = name[i+1];
}
do not forget that once found an element in the array cut the cycle to avoid delay // break;

How to Loop a simple program in Java?

I am trying to code a simple program in which the user can view and update a list of NBA player's racing for the MVP Trophy. However I have failed in the past to code a program in which can loop for however long the user decides to. I want the program to have the options 1. Go Back & 2. Exit but I cannot figure out how to loop it. Here is my Rank.java & AdminAccount.java. Hope it is not confusing to understand, thank you for reading.
import java.util.Scanner;
public class Rank {
String player[] = { "Stephen Curry", "Russel Westbrook", "Kevind Durant", "LeBron James", "Kawhi Leonard" };
Scanner rankInput = new Scanner(System.in);
Scanner playerInput = new Scanner(System.in);
int rank;
String playerUpdate;
public void Rank() {
System.out.println("Rank\tPlayer");
for (int counter = 0; counter < player.length; counter++) {
System.out.println(counter + 1 + "\t" + player[counter]);
}
}
public void updateRank() {
System.out.print("Select rank to update: ");
rank = rankInput.nextInt();
if (rank == 1) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[0] = playerUpdate;
} else if (rank == 2) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[1] = playerUpdate;
} else if (rank == 3) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[2] = playerUpdate;
} else if (rank == 4) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[3] = playerUpdate;
} else if (rank == 5) {
System.out.print("\nPlayer Name: ");
playerUpdate = playerInput.nextLine();
player[4] = playerUpdate;
}
}
}
import java.util.Scanner;
public class AdminAccount {
public static void main(String[] args) {
Rank rank = new Rank();
Scanner adminInput = new Scanner(System.in);
Scanner exitInput = new Scanner(System.in);
boolean keepRunning = true;
// menu variables
int menuOption;
int exitOption;
while (keepRunning) {
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if (menuOption == 1) {
rank.Rank();
} else if (menuOption == 2) {
rank.updateRank();
}
}
}
}
Just add an "exit" option to your loop:
while(keepRunning){
System.out.println("*** NBA MVP Race Administor Account ***");
System.out.print("\n1.Ranking 2.Update 3.Exit\t- ");
menuOption = adminInput.nextInt();
System.out.println("");
if(menuOption == 1)
{
rank.Rank();
}
else if(menuOption == 2)
{
rank.updateRank();
}
else
{
keepRunning = false;
}
}
This a sample code using arrays
This Program Uses Do.... While Loop to Loop over a whole program when there is a user prompt.
package doWhileLoop;
import java.util.Scanner;
public class doWhileLoop {
public static void main(String[] args) {
//this is a program to prompt a user to continue or pass using the do while loop
String programCounter;
do {
int sum=0;
int list[] = new int[3];
Scanner in = new Scanner(System.in);
System.out.println("Enter 3 numbers to be added: ");
for (int i = 0; i < 3; i++) {
list[i] = in.nextInt();
sum+= list[i];
}
System.out.println("sum = "+ sum);
System.out.println("Enter Yes to continue or No to exit........");
programCounter = in.next();
}
while (programCounter.equals("yes"));
}
}

Adding words and checking in Arraylist Hangman

I'm having trouble with adding words and using do while in my code:
ArrayList<String> word = new ArrayList<>();
word.add("fish");
word.add("chicken");
word.add("icecream");
int lengthz = word.size();
Scanner sc = new Scanner(System.in);
System.out.println("Hangman");
System.out.println("1. 1 Player");
System.out.println("2. 2 Player");
System.out.println("3. Add word");
System.out.println("4. Quit");
System.out.print("Choice : ");
int opsi = sc.nextInt();
if (opsi == 3) {
boolean show = false;
boolean founded = false;
System.out.println("Input the words to be added : ");
boolean showall = true;
do {
String input = sc.next() + sc.nextLine();
for (int i = 0; i < lengthz; i++) {
if (!input.equals(word.get(i))) {
while (!founded) {
word.add(input);
System.out.println("Succeed!");
founded = true;
}
} else if (input.equals(word.get(i))) {
while (!show) {
System.out.println("Already Added");
show = true;
}
}
}
System.out.println("Want to add more words?");
String answer = sc.next() + sc.nextLine();
if (answer.equals("no")) {
System.out.println("Thanks for adding");
showall = false;
} else if (answer.equals("yes")) {
opsi = 3;
}
} while (showall);
for (int i = 0; i <= lengthz; i++) {
System.out.println(word.get(i));
}
}
My desired output will be like if the user wants to add more word with "yes" then it will repeat the program, and if the user types "no" then it will display all the words together with the addition, and then going back to show the menu 1-4 option. Please help me ... Thanks in advance !
Structure your code, e.g. as follows:
static final Scanner in = new Scanner(System.in);
static List<String> words = getStandardWords();
public static void main(String[] args) {
while (true) {
System.out.println("-- Hangman --");
System.out.println("1. 1 Player");
System.out.println("2. 2 Player");
System.out.println("3. Add word");
System.out.println("4. Quit");
System.out.print("Choice : ");
String choice = in.nextLine();
switch (choice) {
case "1":
//todo
break;
case "2":
//todo
break;
case "3":
addWord();
break;
case "4":
System.exit(0);
break;
default:
System.out.println("Invalid choice: " + choice);
break;
}
}
}
static List<String> getStandardWords() {
List<String> result = new ArrayList<>();
result.add("fish");
result.add("chicken");
result.add("icecream");
return result;
}
static void addWord() {
System.out.println("Input the word to be added: ");
String word = in.nextLine();
// add word
if (words.contains(word)) {
System.out.println("Already Added");
} else {
words.add(word);
System.out.println("Succeed!");
}
// add more words?
while (true) {
System.out.println("Want to add more words?");
String choice = in.nextLine();
switch (choice.toLowerCase(Locale.ROOT)) {
case "n":
case "no":
System.out.println("Thanks for adding");
// print all words
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i));
}
return;
case "y":
case "yes":
addWord();
return;
default:
System.out.println("Invalid coice: " + choice);
break;
}
}
}
1) You need to initialize the
founded = false;
inside do - while loop
2) use last printing for loop as below :
for(int i=0; i<word.size();i++)
{
System.out.println(word.get(i));
}

Categories

Resources