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;
}
}
}
Related
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
for (int j = 0; j < this.rainRecorded[i] - 1; j++) {
System.out.print("*");
}
System.out.println(i);
}
System.out.print("");
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
I guys i being struck on this for a couple of days in my switch statement in case 3 is where i create my elements to enter into my array , but in seems to only remember the last array entered when i print my histogram out in case 4 displayHistogram(); and this is where my histogram is printing wrong as well.
So to issues my array isn't recording property and histogram is printing wrong.
For example users chooses 3 days to enter and values are 10,20,30, and when i print histogram its prints this.
0
1
*****************************2
What i want this below , one * for ever ten mills of rain with index printed first.
0 *
1 **
2 **
You need to move the initialisation of this.rainRecorded to createGauge method and update the displayHistogram to print as required. You can try the following:
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
int i = 0;
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Invalid input, try again");
mainMenu();
}
while (choice != 8)
;
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
this.rainRecorded = new int[this.days]; // move the array initialization here
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
mainMenu();
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
mainMenu();
} else {
mainMenu();
}
}
private void displayHistogram() {
for (int i = 0; i < this.rainEntered.length; i++) {
System.out.print(i + " ");
for (int j = 0; j < this.rainRecorded[i] - 1; j += 10 ) {
System.out.print("*");
}
System.out.println();
}
mainMenu();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
So, your codes a little bit over the place and I've had some issues trying to understand the basic intent, for example
private int[] rainRecorded;
private int[] rainEntered;
I'm not sure what the intention is for these two variables. So in my example, I've discarded rainEntered for the time been.
So, your first problem starts here...
while( i < this.days || this.daysCounter == this.days) {
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
mainMenu();
}
if (this.days < 1) {
mainMenu();
} else {
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
mainMenu();
}
i++;
}
First, I'd remove the need to for the two exit conditions, as it is going to make it more difficult to reasons about
Next, the checks for the validity of the data should be done outside of the loop and I'd also avoid calling mainMenu from within it, this is going to quickly put you in a strange place.
But, my main problem is with
this.rainRecorded = new int[this.days];
System.out.printf("Please enter rainfall for the current day: ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
this.rainEntered = new int[this.daysCounter];
You keep creating new instances of both this.rainRecorded and this.rainEntered, meaning that each time the loop runs, you've lost anything that was previous entered.
So, in my "simplified" version, I modified it down to something like...
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
I then simplified the histogram workflow as well, but I'm still trying to get my head around what rainEntered is suppose to do...
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
One last thing I also did, was to remove all the calls to mainMenu and instead relied on a simple do-while loop to reprint the menu each time it returned from Chosen method
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
This simplifies the workflow, as it's easier to reason about where you are at any point in the execution of the program, instead of wondering why when, under some condition, when you chose something from the menu, you end up in some other part of the program instead.
Example
import java.util.Scanner;
public class RainRecording {
private int choice;
private Scanner input;
private String site;
private int days;
private int daysCounter;
private int[] rainRecorded;
//private int[] rainEntered;
private float lattitude;
private float longitude;
private String message1;
private String message2;
private String message3;
private String message4;
private String message5;
private String message6;
private boolean shouldContinue = true;
// declare name of variable
public RainRecording() {
// declare value of variable
this.message1 = "Site";
this.message2 = "lattitude";
this.message3 = "longitude";
this.message4 = "Window";
this.message5 = "days";
this.message6 = ":";
this.daysCounter = 0;
this.input = new Scanner(System.in);
mainMenu();
}
private void mainMenu() {
do {
System.out.println("");
System.out.println("*** Rain Gauge Menu ***");
System.out.println(" 1: Create rain gauge");
System.out.println(" 2: Display rain gauge details");
System.out.println(" 3: Add daily rainfall measurement");
System.out.println(" 4: Display rainfall histogram");
System.out.println(" 5: Get maximum rainfall");
System.out.println(" 6: Check rainfall is below threshold");
System.out.println(" 7: Display anaylsis");
System.out.println(" 8: Exit");
System.out.print("Please enter your selection: ");
Chosen();
} while (shouldContinue);
}
private void Chosen() {
this.choice = Integer.parseInt(input.nextLine());
switch (choice) {
case 1:
createGauge();
break;
case 2:
gaugeDetails();
break;
case 3:
if (this.days < 1) {
System.out.println("Invalid number of days");
return;
}
if (this.daysCounter == this.days) {
System.out.printf("Error - system full\n");
return;
}
while (this.daysCounter < this.days) {
System.out.printf("Please enter rainfall for the day " + (daysCounter + 1) + ": ");
rainRecorded[this.daysCounter] = Integer.parseInt(input.nextLine());
this.daysCounter++;
}
break;
case 4:
System.out.printf("\n");
displayHistogram();
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8: shouldContinue = false;
break;
default:
System.out.println("Invalid input, try again");
}
}
private void createGauge() {
System.out.printf("\nPlease enter the name of the site :");
this.site = input.nextLine();
System.out.printf("Please enter the number of days to record :");
this.days = Integer.parseInt(input.nextLine());
System.out.printf("Please enter the lattitute :");
this.lattitude = Float.parseFloat(input.nextLine());
System.out.printf("Please enter the longitude :");
this.longitude = Float.parseFloat(input.nextLine());
if (days > 0) {
this.rainRecorded = new int[this.days];
}
}
private void gaugeDetails() {
if (this.days > 0) {
System.out.printf("%-9s %-3s %s \n", this.message1, this.message6, this.site);
System.out.printf("%s %-3s % 09.4f\n", this.message2, this.message6, this.lattitude);
System.out.printf("%s %-3s %9.4f\n", this.message3, this.message6, this.longitude);
System.out.printf("%-9s %-3s %-2d%s \n", this.message4, this.message6, this.days, this.message5);
}
}
private void displayHistogram() {
for (int amount : rainRecorded) {
for (int count = 0; count < amount; count++) {
System.out.print("*");
}
System.out.println(" " + amount);
}
}
public static void main(String[] args) {
#SuppressWarnings("unused")
RainRecording objName;
objName = new RainRecording();
}
}
Now, if rainEntered is suppose to be some kind of compounding array, where it allows you to record multiple days of rain over different periods, you might consider using a multi-dimensional array instead, so you could n periods and each period could have n days of rain...
I don't know how to say
if money(); < 1000 and house(); is == small print your poor
or
if money(); >=1000 and < 5000 and house(); is == to normal to print your ok, your too rich
package ArrayTest;
import java.util.Scanner;
/**
* Created by quwi on 02/12/2017.
*/`enter code here`
public class Happyness {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// house();
// money();
comparison();
}
private static void house() {
// getting user input and using the switch statement to see the size
// of their house
System.out.println("Please enter the size of your house ");
String cap = scanner.next();
switch (cap) {
case "small":
System.out.println("you have a small house it means your poor");
break;
case "normal":
System.out.println("your house normal, it mean your not poor nor rich");
break;
case "large":
System.out.println("your house is big it means your rich");
break;
default:
System.out.println("please choose between: small, normal or large");
break;
}
}
private static void money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
System.out.println("your poor");
} else if (wage >= 1000 && wage < 5000) {
System.out.println("your not poor, your OK");
} else if (wage > 5000) {
System.out.println("your rich, Give me money");
} else {
System.out.println("please enter a number nothing else");
}
}
private static void comparison() {
System.out.println("please enter a number");
int decision = scanner.nextInt();
switch (decision) {
case 1:
money();
break;
case 2:
house();
break;
case 3:
money();
house();
break;
default:
System.out.println("Please choose 1, 2 or 3");
}
}
}
Use return value from both to compare.
private static String money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
return "poor";
} else if (wage >= 1000 && wage < 5000) {
return "ok";
} else if (wage > 5000) {
return "rich";
} else {
//ask for input again or exit, whatever
}
}
Do same for the house(). Then, compare the return values from both in another method.
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
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();
}
}
I am having an issue where it isn't checking the validity of user input correctly. It breaks if I input a letter or string as a choice instead of looping through and asking again. I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement. Advice?
public class Main
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
displayMenu();
int entryChoice = scan.nextInt();
while (entryChoice != 9)
{
System.out.println(userSelection(entryChoice));
displayMenu();
isInt(entryChoice);
entryChoice = scan.nextInt();
}
scan.close();
System.exit(0);
}
public static boolean isDouble(double x)
{
double userInput = x;
try
{
userInput = Double.parseDouble(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input. Try again.");
return false;
}
}
public static boolean isInt(int x)
{
int userInput = x;
try
{
userInput = Integer.parseInt(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input");
return false;
}
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6)
{
System.out.println("Enter one number: ");
x = scan.nextDouble();
}
else
{
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
}
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0)
{
System.out.println("Can't divide by zero. Please enter another number.");
y = scan.nextDouble();
result = x / y;
}
else
{
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
//store a number
break;
case 8:
//recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement.
You don't.
Your isInt() method ignores its parameter, reads a new value from the scanner and checks to see if it's a number, and doesn't return the new value, whether or not it's a number.
In any case, the Scanner class you are using to collect user input already does this sort of validation for you. You started in the correct direction with
int entryChoice = scan.nextInt();
but it's dangerous to try to get a token from a Scanner without first checking to see if it has one for you to get.
If you look at the API docs for Scanner, you'll see a whole list of nextFoo() and hasNextFoo() methods. These are meant to be used together.
Generally what you want is a loop which prompts the user for the desired input until they give it, like this:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (!scan.hasNextInt()) {
scan.next(); // throw away non-numeric input
System.out.println("Please enter a number");
}
System.out.println("User entered: " + scan.nextInt());
This will end up re-prompting the user until they give you a number:
Please enter a number
apple
Please enter a number
fox
Please enter a number
bear
Please enter a number
42
User entered: 42
Here is your code,However i did many changes.Wish this help you little.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static int entryChoice = 0;
static boolean tester = true;
static double result;
public static void main(String[] args) {
displayMenu();
boolean check = isInt(entryChoice);
while (check && entryChoice != 9) {
result = userSelection(entryChoice);
System.out.print(result == 0 && !tester ? "" : result + "\n");
if (!tester)
break;
}
scan.close();
System.exit(0);
}
/*
* public static boolean isDouble(double x) {
*
* try { x = Double.parseDouble(scan.next()); return true; } catch
* (NumberFormatException ignore) { System.out.println(
* "Invalid input. Try again.");
*
* return false; } }
*/
public static boolean isInt(int x) {
try {
x = Integer.parseInt(scan.next());
entryChoice = x;
return true;
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
System.err.println("program will be terminated!");
tester = false;
return false;
}
}
public static void displayMenu() {
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice) {
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6) {
try {
System.out.println("Enter one number: ");
x = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.out.println("Invalid input");
}
} else {
try {
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.err.println("Invalid input,program will be terminated !");
tester = false;
// return ;
}
}
switch (entryChoice) {
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0 && tester) {
System.out.println("Can't divide by zero. Please enter another number.");
try {
y = scan.nextDouble();
} catch (InputMismatchException ex) {
System.err.println("invalid input, program will be terminated");
tester = false;
}
result = x / y;
} else if (tester) {
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
// store a number
break;
case 8:
// recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}