How do you pass multiple parameters in java? - java

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

Related

Variable being changed for seemingly no reason in Java

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);
}

How to fix a variable from a class not being subtracted in a method?

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.

Creating Methods that will produce the same result

I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}

how to get data from other methods?

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();
}
}
}

Numberguessing class and client

I am trying to code a number guessing class and client.
The issue/problems I am having with this class/client is that my number guess either ends up too high or too low and in top of that it loops the number twice when it should once.
Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)
Let's take a guess:
50
40
Your guess is too low
What possible change can I make to improve the overall loop or change.
Here is my code for anyone that wants to look at it.
import java.util.Random;
public class NumberGuess
{
private Random generator;
private int Number;
int intGuess= (1 + (int)(Math.random()*100));
int numGuess=0;
boolean isGuessCorrect=false;
public NumberGuess(){
}
int numguess;
public int guess(int guessIn){
int numguess=guessIn;
if(numguess>intGuess){
return 1;
}else if(isGuessCorrect){
return 0;
}else{
return -1;
}
}
public int getNumberofGuesses(){
return numGuess;
}
public boolean gameIsComplete(){
if(isGuessCorrect){
return true;
}else{
return false;
}
}
public void reset(){
intGuess=(1 + (int)(Math.random()*100));
numGuess=0;
isGuessCorrect=false;
}
}
Client class
import java.util.Scanner;
public class NumberGuessclient{
public static void main(String[] args){
NumberGuess game1=new NumberGuess();
Scanner scan = new Scanner(System.in);
int quit=1;
while(quit != 0) {
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
int guess1= scan.nextInt();
while((guess1 != 0)||(!game1.gameIsComplete())) {
guess1 = scan.nextInt();
if (game1.guess(guess1)==1){
System.out.println("Your guess is too high");
}
else if(game1.guess(guess1)==-1) {
System.out.println("Your guess is too low");
}
else { System.out.println("guessed in " + game1.getNumberofGuesses() + " tries");
}
}
System.out.println("Enter 1 for new game, 0 to quit: ");
quit = scan.nextInt();
if(quit==1){
game1.reset();
}
}
}
}
source code for more ELABORATION if not clarified above.
NumberGuess Class:
The NumberGuess class will facilitate a number guessing game. The constructor should generate a random number, saving the number in a private class field. The class should also define a method which accepts a "guess", compares the "guess" to the randomly generated number, and returns one of the following:
• -1 the guess was less than the secret number
• 0 the guess matched the secret number
• 1 the guess was higher than the secret number
Determine whether other methods, constructors or otherwise, would be useful for this class.
The Java API defines a Random class for generating random numbers. The class can be reviewed in the API or in your textbook beginning on page 250. Consider limiting the range of the random number. For instance, a number between 0 and 100.
Client Application:
The client application allows the end-user to play the number guessing game. Below is a sample run. Your application does not need to match.
I'm thinking of a number between 0 and 100. Can you guess it?
Take a guess: 50
Your guess is too high
Another guess? (Y or N): y
Take a guess: 25
Your guess is too high
Another guess? (Y or N): y
Take a guess: 10
Your guess is too low
Another guess? (Y or N): y
Take a guess: 15
Your guess is too low
Another guess? (Y or N): y
Take a guess: 18
Your guess is too low
Another guess? (Y or N): y
Take a guess: 20
Congratulations! You correctly guessed the secret number in 6 tries.
There are quite a bit of things that you can change, for instance:
There's no need to call game1.guess(guess1) more than once every loop.
The completion method is quite long...
You should call scan.nextInt() before entering the while loop...
I'm assumming the last output was manually generated, because you never increment numguess
The guess(int) method doesn't work...
I'm not usually one to do homework... but (I'm having a good day...!):
import java.util.Random;
import java.util.Scanner;
public class NumberGuessclient {
private static final String[] ANS = {
"Your guess is too low\n",
"guessed in %d tries\n",
"Your guess is too high\n"
};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
NumberGuess game = new NumberGuess();
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
while (!game.isGameComplete()) {
System.out.format(ANS[game.guess(scan.nextInt())+1], game.getNumberofGuesses());
}
System.out.println("Enter 1 for new game, 0 to quit: ");
if (scan.nextInt() != 1) {
System.out.println("Bye!");
System.exit(0);
}
}
}
}
class NumberGuess {
private static final Random RAND_GENERATOR = new Random(System.nanoTime());
int intGuess = RAND_GENERATOR.nextInt(101);
int numGuess = 0;
boolean isGuessCorrect = false;
public int guess(int guessIn) {
numGuess++;
if (guessIn > intGuess) {
return 1;
} else if (guessIn == intGuess) {
isGuessCorrect = true;
return 0;
} else {
return -1;
}
}
public int getNumberofGuesses() {
return numGuess;
}
public boolean isGameComplete() {
return isGuessCorrect;
}
}
Now one comment: as I recall the "fun" of this game was that you should always "guess" the number in at the very most 10 tries, you could implement that...

Categories

Resources