So i just started learning Java yesterday so apologies if this is a bit of a mess.
Basically i am testing the function menuValid() by printing the input from the function questionTime(), my problem is regardless of what my input for the menu is menuValid() will always print '0' as my answer. However the X variable is declared and printed at the same points however x will remain the same and will not be set to '0'.
Here is my code:
import java.util.Scanner;
public class Test {
public static int menu_input;
public static int x;
static void menuError() {
System.out.println("Please pick a valid option.");
questionTime();
}
public static void questionTime() {
Scanner scan = new Scanner(System.in);
try {
int menu_input = scan.nextInt();
x = 25;
if(menu_input>4 && menu_input < 9){
menuError();
}
if(menu_input>9 || menu_input<1){
menuError();
}
else{
System.out.println(menu_input);
menuValid();
}
scan.close();
} catch(Exception e) {
menuError();
}
}
public static void menuValid() {
System.out.println(menu_input);
System.out.println(x);
}
public static void main(String[] args) {
System.out.println("P4CS Mini Applications");
System.out.println("----------------------");
System.out.println("Please Select an option:");
System.out.println("1) Keep Counting Game");
System.out.println("2) Number Conversion Tool");
System.out.println("3) Universal Product Code (UPC) Calculator");
System.out.println("4) Universal Product Code (UPC) Checker");
System.out.println("9) Quit");
System.out.println("Please enter option");
questionTime();
}
}
Here is an example of the output of the code so you can see my issue:
1) Keep Counting Game
2) Number Conversion Tool
3) Universal Product Code (UPC) Calculator
4) Universal Product Code (UPC) Checker
9) Quit
Please enter option
1
1
0
25
You re-declared menu_input inside questionTime (when you did int menu_input = scan.nextInt();), which is different from how you treated x, where you just changed its value (x = 25;). So the menu_item you're setting via the Scanner is not the menu_input class variable you're printing inside menuValid.
You will have to pass menu_input to menuValid() like so -
else{
System.out.println(menu_input);
menuValid(menu_input); // see this line
}
And change menu valid function as below -
public static void menuValid(int menu_input) {
System.out.println(menu_input);
System.out.println(x);
}
Related
import java.util.Scanner;
public class MP3
{
//this is the main code that I need to connect each method to each method.
//so that if the user press 2 it will go to snacks but even if you press two now it just continues the code and go-to meals.
//how can I make it so that the user can choose which menu he/she likes to go through?
public static void main(String[] args)
{
int Options_Snacks;
int Options_Snacks2;
int Options_Snacks3;
int Options_Drinks;
int Options_Drinks2;
int Options_Drinks3;
int diff,prod ;
int yes = 1;
int no = 2;
int End;
do {
mainmenu();
mainmeals();
mainsnacks();
Scanner myInput = new Scanner(System.in);
System.out.println("Would you like to order more: press " + yes +" for yes and " + no +" for no");
End = myInput.nextInt();
} while(End == 1);
}
// this code runs smoothly but the other menus don't run when the user press the number instead it runs all the code within the while loop.
public static void mainmenu()
{
int Orders;
int Meals = 1;
int Snacks = 2;
int Drinks = 3;
int EXIT = 4;
Scanner myInput = new Scanner(System.in);
System.out.println("=======[STRESSFOOD]=====");
System.out.println("---------[ Menu ]-------");
System.out.println("1----------Meals--------");
System.out.println("2---------Snacks--------");
System.out.println("3---------Drinks--------");
System.out.println("4--------[ EXIT ]-------");
Orders = myInput.nextInt();
}
[here's the code I didn't get all in the picture][1]
}
What about the following implementation:
public static void main(String[] args) {
openMenu();
}
With the while loop in the menu function :
private static void openMenu() {
Scanner scan = new Scanner(System.in);
do {
System.out.println("1) Meals");
System.out.println("2) Snacks");
System.out.println("3) Drinks");
System.out.println("4) Exit");
System.out.print("Your choice ? ");
switch (scan.nextInt()) {
case 1:
openMealsMenu();
break;
case 2:
openSnacksMenu();
break;
case 3:
openDrinksMenu();
break;
case 4:
scan.close();
return;
default:
System.out.println("This is not a valid choice");
}
} while (true);
}
Note that you should only use one scanner in your application. If you need your scanner in the openMealsMenu() for example, pass it as a parameter of the method, or just declare a static scanner in your MP3 class since your methods are in the same class.
By the way, by convention, variables should start with a lowercase letter and do not take a _ (ie. Options_Drinks3 becomes optionsDrinks3).
The gist of this assignment is that there are two players who take a stick out of a pile. I made a class that has the number of sticks available. There is a method that is called to remove sticks. However when I try to remove sticks the number of sticks doesn't change. Therefore the game not being able to end because there are still sticks "left".
I've tried using int sticks to be subtracted. The total amount of sticks changes but only in the method in which they are subtracted. The number of sticks don't change in the main method.
I decided to make use classes as I saw on this site that that is how this issue can be fixed. I've had no success with it.
So I made a class that has the amount of sticks so now the number of sticks is the same for each method. The same issue persists. One that changes the number of sticks in the getSticksRemove() method but not main() or getSticksLeft().
//Main Class
public class Main {
//Method to remove sticks which considers different scenarios.
public static int getSticksRemove(int sticks) {
sticks = StickPile.getValue(StickPile.value);
Scanner input = new Scanner(System.in);
print ("How many sticks to remove?(1-3)");
int x = input.nextInt();
if( x>=1 && x<=3) {
sticks -= x;
}else if(sticks < 3 && x ==2 ) {
print("Not enough sticks left.");
getSticksRemove(sticks);
}else if (x>3) {
sticks -=3;
}else { `enter code here`
sticks-=1;
}
print(sticks);
return sticks;
}
//Main method
public static void main(String [] args) {
StickPile stickPile = new StickPile();
int turnP1 = 0;
int turnP2 = 0;
int sticks = 0;
print("How many sticks are there initially? (1-100)");
StickPile.setValue();
sticks = StickPile.getValue(StickPile.value);
//This is the loop that determines when to stop the game
while(sticks != 0) {
System.out.print("Player 1: ");
getSticksRemove(sticks);
getSticksLeft(sticks);
turnP1++;
System.out.print("Player 2: ");
getSticksRemove(sticks);
getSticksLeft(sticks);
turnP2++;
}
if(turnP1 % 2 == 0 && turnP2 % 2 == 1) {
System.out.println("P2 Loses");
}else {
System.out.println("P1 Loses");
}
}
}
// This StickPile class is the one I made to store the number of sticks.
public class StickPile {
static Scanner input = new Scanner(System.in);
public static int value;
public static void setValue() {
value = input.nextInt();
}
public static int getValue(int x) {
x = value;
System.out.println(x);
return x;
}
I expect to enter a number of sticks to remove from the pile. Ex. PileAmount: 20--> Remove: 12--> PileAmount: 8.
However, I get Ex. PileAmoun: 20 --> Remove: 5--> PileAmount: 20,
You're ignoring the return of getSticksRemove. You can't reassign the parameter to effect the number outside of the function.
Just use the return value:
sticks = getSticksRemove(sticks)
Make that change in both places.
I am a beginner at java and just need to find out how to send multiple parameters to one method (being 'game()'). The program is not complete I just need to get that bit working before I continue. The program is a 'safe-cracker' which takes user input and tells them if there guess is correct or not (I haven't done that part of the code yet). The code needed a menu system where the user can input the original number manually, whether they want hints or not, the amount of guesses they get, and a 3 digit number randomly generated. Any help would be appreciated
import java.util.*;
import java.util.Random;
public class ModularSafecracker
{
Scanner inputScanner = new Scanner(System.in);
public void menu() //main menu
{
ModularSafecracker MS = new ModularSafecracker();
System.out.println("-=- MENU -=-");
System.out.println("1 - Manually set a 3-digit code");
System.out.println("2 - Randomly generate a 3-digit code");
System.out.println("3 - Set max number of guesses");
System.out.println("4 - Turn hints on/off");
System.out.println("5 - Begin game");
System.out.println("-=- -=-");
int menuDecision = inputScanner.nextInt();
if(menuDecision == 1)
{
MS.manual();
}
if(menuDecision == 2)
{
MS.random();
}
if(menuDecision == 3)
{
MS.setMax();
}
if(menuDecision == 4)
{
MS.setHints();
}
if(menuDecision == 5)
{
}
}
public void manual() //option 1
{
ModularSafecracker MS = new ModularSafecracker();
System.out.println("Please enter a 3 digit code");
int manualCode = inputScanner.nextInt();
MS.menu();
}
public void random() //option 2
{
ModularSafecracker MS = new ModularSafecracker();
Random x = new Random();
int randomCode = x.nextInt(899)+100;
MS.menu();
}
public void setMax() //option 3
{
ModularSafecracker MS = new ModularSafecracker();
System.out.println("Please enter the max number of guesses");
int max = inputScanner.nextInt();
MS.menu();
}
public void setHints() //option 4
{
ModularSafecracker MS = new ModularSafecracker();
System.out.println("Would you like hints?");
String option = inputScanner.nextLine();
if (option.equalsIgnoreCase("Yes"));
{
int hints = 1;
}
if (option.equalsIgnoreCase("No"));
{
int hints = 0;
}
MS.menu();
}
public void game()
{
//in this method I want the variables 'max' 'hints' 'manualCode' and 'randomCode'
}
public static void main(String[] args)
{
ModularSafecracker MS = new ModularSafecracker();
MS.menu();
}
}
public void game(int max, int hints, int manualCode, int randomCode){
You should probably be using boolean for your hints value, and ideally enums for your manualCode and randomCode variables but I went with what you were using
I'd encourage you to read a bit on the very basics, as having a solid foundation will make it much easier for you to teach yourself in the future.
To have the variables 'max', 'hints', 'manualCode' and 'randomCode' in your game method, you need to declare them as instance variables. Right now you have them as local variables for the other methods.
You can read about variables in Java here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
I'm stumped on how to format my menu. What I have so far isn't working but I know it could be better formatted and shorter. This is the description of the assignment. You can see that my approach isn't going to work but I don't know how to change my approach...
I'm pretty sure I need to use arrays but I'm not sure how to store a public array so any method can call and store information to it.
import java.util.Scanner;
/*
#author David Jacobsen
#version 10-23-16
*/
/*
CODE DESIGN:
-> Bring menu from basicMenu assingment [X]
-> Adapt for this assignment [X]
-> Add content for new menu style []
-> Adapt loop position from basicMenu []
-> Add interior loops []
-> Capitalize class name for *proper grammer* [X]
For Display Cart have three seperate totals for each item then divide by each total by its respective items total
to find the number of that item the customer has purchased and assign it to a varible to be added into menu print out.
For Print Recipt have the system call 'display cart' and add a subtotal, tax, and total printer to the end.
Loop with basic menu while looper. (method 'startOver').
*/
public class CheckoutCounter {
public static void main(String[] args) {
while (startOver() == true) {
//Define Menu Bins
//Top Menu Choice Printer
System.out.println("1. Purchase Items");
System.out.println("2. Display Cart");
System.out.println("3. Print Your Recipt");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Purchase Items"
if (doubleA <= 1) {
priceTotalDragonfruit = priceTotalDragonfruit + CheckoutCounter.purchaseItems();
}
//Menu Choice "Print Recipt"
else if (doubleA >= 3) {
CheckoutCounter.printRecipt();
}
//Menu Choice "Display Cart"
else {
CheckoutCounter.displayCart();
}
}
}
//Purchase Items Method
public static double purchaseItems() {
//Define Variables and Initialize
double dragonfruit = 5.99;
double organicBlasphemy = 99.99;
double dayOldAnswerToTheUniverse = 100000;
double total = 0;
double multiplier;
//Define Total Containers and Initialize
double priceTotalDragonfruit = 0;
double priceTotalOrganicBlasphemy = 0;
double priceTotaldayOldAnswerToTheUniverse = 0;
//Top Menu Choice Printer
System.out.println("1. Dragonfruit ($5.99/lb)");
System.out.println("2. Organic Blasphemy ($99.99 per comment)");
System.out.println("3. 1 Day Old Answer to the Universe ($100,000 per request)");
System.out.println(" ");
//Choose 1, 2, or 3 Menu Input
double doubleA;
Scanner topMenu = new Scanner(System.in);
System.out.print("Please select and option, 1 - 3:");
doubleA = topMenu.nextDouble();
System.out.println(" ");
System.out.println("Good choice.");
System.out.println(" ");
//Method Chooser
//Menu Choice "Dragonfruit"
if (doubleA <= 1) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalDragonfruit = total + (5.99 * multiplier);
}
//Menu Choice "1 Day Old Answer to the Universe"
else if (doubleA >= 3) {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotaldayOldAnswerToTheUniverse = total + (100000 * multiplier);
}
//Menu Choice "Organic Blasphemy"
else {
System.out.println("How much/many do you want?");
Scanner multiplierScanner = new Scanner(System.in);
System.out.println("Enter amount here:");
multiplier = multiplierScanner.nextDouble();
System.out.println("We added your item(s) to your cart.");
priceTotalOrganicBlasphemy = total + (99.99 * multiplier);
}
}
//Display Cart Method
public static void displayCart() {
}
//Print Recipt/End Program Method
public static void printRecipt() {
}
//Start Over Loop Method
public static boolean startOver() {
Scanner inputScanner = new Scanner(System.in);
System.out.print("Please enter either 'True', to continue, or 'False', to stop: ");
Boolean userInputA;
userInputA = inputScanner.nextBoolean();
boolean goAhead;
if (userInputA == false) {
goAhead = false;
}
else {
goAhead = true;
}
return goAhead;
}
}
This is actually a good exercise for a student like you. I wont give you the exact answer (there are many ways though) but let me help you analyze this.
Java is an OOP language. The first thing to do is always determine what your domain objects would be.
Based on your requirement, it is asking for a Menu and create a method for each of the things it does. (sounds like an Object, yes?)
It should look something like below:
public class Menu{
public void purchaseItems(){ // pass an argument or return something depending on what you need
// figure out how you purchase items
}
public void displayCurrentPurchases(){
// figure out how you display the cart (your cart can be a List, Map, or even a class)
}
public void printReceipt(){
// figure out how you print the receipt
//somewhere here you would need to call your computeTaxes method
double netAmount = computeTaxes(grossAmount);
}
/* It's a good idea to limit a method to doing only one thing as much as possible, so you might need to make private methods such as computing for taxes below */
private double computeTaxes(double totalAmount){
return total * 0.098;
}
// and so on...
}
Now that you've got your Menu object set, you can create your Main class to actually create an instance of your Menu:
public class MainClass{
public static void main(String[] args) {
Menu menu = new Menu();
/* create your scanner here, and call the methods on the Menu depending on the user's choice */
// a switch for the user's selection might be a good idea:
switch(selected){
case 1:
menu.purchaseItems();
break;
case 2:
// you get the point. I leave this to you.
default:
sysout("Invalid selection");
break;
}
}
}
does anyone know how to get the counters value transfered after it is increased? so if you awnser it right it changes to one in the next method?
package swag;
import java.util.Scanner;
public class Main {
public static void enter(){
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")){
System.out.println(" Level one");
}else{
System.out.println("Please press enter");
}
}
public static void firstlevel(){
System.out.println("What is the tenth digit of PI?");
Scanner input = new Scanner(System.in);
int awnser = input.nextInt();
int awnser1 = 5;
int counter = 0;
if (awnser == awnser1 ){
System.out.println("Correct!");
counter++;
System.out.println(" Score: " +counter + "/1");
}else{
System.out.println("Wrong!");
System.out.println(" Score:"+ counter+"/1");
}
}
public static void secondlevel(){
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
Scanner input = new Scanner(System.in);
String awnser = input.nextLine();
if (awnser.equals("two ")){
System.out.println(" Correct!");
}
}
public static void main(String args[]){
enter();
firstlevel();
}
}
Ah, the way you have defined counter, it can only be seen in firstLevel.
Best thing to do is make it a 'class variable'. To do that:
Delete int counter = 0; from the firstLevel method.
Add static int counter = 0; on the very next line after public class Main {
So the start of your class should look like:
public class Main {
static int counter = 0;
Now counter will be visible in all methods.
I would highly recommend not using a static counter, as suggested by others. Static mutable objects tend to violate the principle of object oriented programming. If you separate the functionality of your game into methods, you'll have a much more beautiful main method:
public static void main(String args[]) {
// Lets create a new Game object. it will keep track of the counter itself!
Game game = new Game();
// Then we only have to call the methods defined below..
game.enter();
game.firstLevel();
game.secondlevel();
}
Now the code for the class Game containing all the logic:
public class Game {
// Some static final members. they are not meant to change throughout the execution of the program!
// The advantage of defining INDENTAION just once, is that you can easily change it in one place and it will always be consistent!
private static final String INDENTAION = "\t\t";
private static final int TOTAL_POINTS = 2;
// We can use the same scanner object in each method!
private Scanner input = new Scanner(System.in);
// Just like the counter. it will be accessible in each method and refer to the same integer!
private int counter = 0;
public void enter() {
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")) {
System.out.println(INDENTAION + "Level one");
} else {
// I am not sure why you put this here, but I'll leave it in for now
System.out.println("Please press enter");
}
}
// We put that code into seperate methods, since it will get called multiple times!
private void answerCorrect() {
System.out.println("Correct!");
counter++;
printScore();
}
private void answerWrong() {
System.out.println("Wrong!");
printScore();
}
private void printScore() {
System.out.println(INDENTAION + "Score: " + counter +"/"+ TOTAL_POINTS);
}
public void firstLevel() {
System.out.println("What is the tenth digit of PI?");
int awnser = input.nextInt();
if (awnser == 5) {
answerCorrect();
}else{
answerWrong();
}
}
public void secondlevel() {
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
String awnser = input.nextLine();
if (awnser.equals("two") || awnser.equals("2")) {
answerCorrect();
} else {
answerWrong();
}
}
}