Trouble calling one method into another - java

I have a program that deals with using different loops in different methods. The program as a whole is working fine apart from one method that calls another.
I am having trouble with a method that calls another.
What I want to do is:
Have the method call the other and run it which takes a variable
from the user (1 - 100).
Increment a variable if an invalid input is
entered.
Display a message and exit back to menu when 3 inputs are
entered in a row.
The method that is being called works fine on it's own and it works when I call it.
What I can't get to work is the display message when after 3 invalid inputs. At present, it takes about 7 invalid inputs then it displays the message??
Method that works:
public static boolean processGrade(int percentMark)
{
Menu m = new Menu();
clrscr();
System.out.println("Please enter your mark e.g. 90. (input -1 to exit): ");
percentMark = Genio.getInteger();
if
(percentMark >=70 && percentMark <=100)
{
clrscr();
System.out.println("Your Grade is A - Excellent!\n\n");
pressKey();
clrscr();
}
else if(percentMark >= 60 && percentMark <70)
{
clrscr();
System.out.println("Your Grade is B - Good!\n\n");
pressKey();
clrscr();
}
else if (percentMark >=50 && percentMark <60)
{
clrscr();
System.out.println("Your Grade is C - Ok!\n\n");
pressKey();
clrscr();
}
else if(percentMark >=40 && percentMark <50)
{
clrscr();
System.out.println(" Your Grade is D - Must Do Better!\n\n");
pressKey();
clrscr();
}
else if (percentMark <40 && percentMark >= 0 )
{
clrscr();
System.out.println(" Your Grade is E - Must Do Better!\n\n");
pressKey();
clrscr();
}
else if (percentMark < -1 || percentMark >100)
{
clrscr();
System.out.println("ERROR: Value MUST be in the range of 0 - 100!");
pressKey();
clrscr();
return false;
}
else if (percentMark == -1)
{
//clrscr();
System.out.println("You entered -1, you will now return to the menu!");
pressKey();
return false;
}
return true;
}
Method that I can't get to work that calls the above message:
public static void processGradeV2(int percentMark)
{
int invalid = 0;
outerloop:
do {
clrscr();
boolean result = processGrade(percentMark);
processGrade(percentMark);// Call processGrade method
if(result == false)
{
invalid++;
}
if(invalid == 3)
{
clrscr();
System.out.println("Sorry, you have entered an invalid integer 3 times in a row! The program will return to the menu screen.");
pressKey();
break outerloop;
//return;
}
if(percentMark == -1)
{
clrscr();
System.out.println("You entered -1, you will now return to the menu!");
pressKey();
clrscr();
break outerloop;
//processUserChoices();
}
}
while(invalid <3);
}

processGrade(percentMark);// Call processGrade method
will cause you a problem here, delete it.
You already assigned the processGrade(percentMark); result to the result variable.

I would delete boolean result = processGrade(percentMark) and instead change your if statement to:
if(!processGrade(percentMark)){
invalid++;
}

Related

Looping if and else statements in java

I'm working on this program that asks for model numbers of cars infinitely until the person inputs 0 to break the loop. When i run it and input a number it just infinitely loops either your car is defective or it is not defective until it crashes. I'm pretty stuck right now any help would be greatly appreciated.
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
while (modelNum != 0) {
if (modelNum >= 189 && modelNum <= 195) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 189 || modelNum == 221) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 780) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
if (modelNum == 0) {
System.out.println("end");
break;
}
}
It's because you never ask the user for another input. You should do so before the end of the loop.
Include the this part into your loop:
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
You have to ask for a new value to be evaluated:
while (modelNum != 0) {
// if conditions
modelNum = input.nextInt();
}
Also note that:
if (modelNum == 0) {
System.out.println("end");
break;
}
won't be necessary because if the last value is 0 the condition in the while loop will be false and won't loop again.
Last thing: why you have all those if-else-if when they all do the same thing (print "Your car is defective it must be repaired"). This will be enough:
while (modelNum != 0) {
if ((modelNum >= 189 && modelNum <= 195) || modelNum == 221 || modelNum == 780 || modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
modelNum = input.nextInt();
}
if you enter 0, the loop will break, therefore the last if statement will never run.
This loop just tells you if the car is defective or not depending on the model number, but you never tell the program to exit the loop if the car is defective. To do so you have to put break statements into each if statement of the loop.
Moreover this statement is useless:
if(modelNum == 0)
{
System.out.println("end");
break;
since if u enter 0 the loop won't start.

How to get method to recognize else part of if statement? [duplicate]

This question already has answers here:
How can I check for invalid input and loop until the input is valid?
(3 answers)
Closed 5 years ago.
I've made a street craps game and have an error checker in the beginning to make sure the input is valid, I put it in an if statement and then have the rest of the code (for valid inputs) as the else but it isn't recognizing the else part when the user puts in a valid number.
public void play() { //method
System.out.println("Please pick a number.");
guess = scan.nextInt();
if (guess == 7 || guess == 1 || guess == 0 || guess > 12) {
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
} else {
int roll = dieOne.roll();
int roll2 = dieTwo.roll();
int rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
while (rollSums != 7) {
if (guess == rollSums) {
System.out.println("Congratulations, you win! Your number was rolled before a seven was rolled!");
rollSums = 7;
guess = 7;
} else {
roll = dieOne.roll();
roll2 = dieTwo.roll();
rollSums = roll + roll2;
System.out.println(roll + "+" + roll2);
}
}
if (rollSums != guess) {
System.out.println("Sorry, your number was not rolled before a seven was rolled.");
}
}
}
I guess you want to execute the if part until the if condition is not satisfied, and then you want to execute the else part. If this is what you want you need to execute the if part as a while loop, and the else part as code after the while loop.
You need a while loop to make sure you get a good input first, and then do the game logic, like this:
int guess = scan.nextInt();
while (guess == 7 || guess == 1 || guess == 0 || guess > 12){
System.out.println("Sorry, that is an invalid input, please choose another number.");
guess = scan.nextInt();
}
//Game Logic (Stuff in else section)

Last questions: Mastermind Java program

I have two questions regarding my code.
Why does is the output "Oops please enter a number between 1 and 6" when I enter a number between 1 and 6. When I try to be more specific and make an else if statement, nothing happens when I enter a number NOT between 1 and 6.
How do I restart my program? In my code, there is an if statement
when the user inputs "play again" My commented out line reads
Mastermind.main() to re run the program, but that didn't work.
Here is the code:
import java.util.Scanner;
public class Mastermind {
public static void main (String [] args) {
// boolean variable to signal when the game is over.
boolean done = false;
// Scanner object
Scanner scanner = new Scanner(System.in);
// sets the value to twelve outside the loop so it doesn't set back each time.
int guesses = 12;
System.out.println("Please enter a number between 1-6 to begin (or \"quit\") to exit.");
// while loop for the game
while (!done) {
//System.out.println("Please enter a number between 1-6 (or \"quit\") to exit the game:");
// user input
String input = scanner.nextLine();
int number = 0; //Just initialized to some number
// checks to see if the user wants to quit the game.
if (input.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else{
try{
//Trying to see if the input was a number
number = Integer.parseInt(input);
}
catch(Exception e){
//The input wasn't an integer, it's invalid the starts loop again.
System.out.println("Invalid input.");
continue;
}
}
// defines necessary int variables
int random1 = (int) (Math.random() * 7);
int random2 = (int) (Math.random() * 7);
int random3 = (int) (Math.random() * 7);
int random4 = (int) (Math.random() * 7);
// If the user doesn't and decides to play, it runs this code.
// checks to see if the user enters a number between 1-6
if (number >= 1 && number <= 6) {
if (number == random1) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random2) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random3) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else if (number == random4) {
System.out.println("You guessed a correct number!");
guesses--;
System.out.println("guesses = " + guesses);
}
else {
System.out.println("Sorry that's not one of the numbers! Try again.");
guesses--;
System.out.println("guesses = " + guesses);
}
}
if (guesses == 0){
System.out.println("You've run out of guesses. To play again, enter \"play again\". Otherwise, enter or \"quit\")");
if (input.equalsIgnoreCase("play again")){
// how do I restart the program?
//Mastermind.main(); // QUESTION 2
}
else if (input.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
done = true;
scanner.close();
}
else {
System.out.println("Goodbye!");
done = true;
scanner.close();
}
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
}
}
}
You're printing that message every time through the loop whenever guesses == 0 evaluates to false. You probably just need to switch the order of the two blocks. Instead of this:
if (number >= 1 && number <= 6) {
...
}
if (guesses == 0) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
Use this:
if (number >= 1 && number <= 6) {
...
}
else { //QUESTION 1
System.out.println("Oops! Please choose a number between 1 and 6");
}
if (guesses == 0) {
...
}
Regarding restarting your program: if I'm reading the logic correctly, all you need to do is keep done set to false and reset guesses to 12.
Two other logic points. First, you should probably either continue or break after detecting that the user has entered "quit". Second, it seems like you are generating four new random integers for every user guess. I don't know if that's what you intended, but you might want to change the logic a bit. That might also affect the restart logic.

Java String Method returning Null?

I was tasked with making a simple program that will play Rock-Paper-Scissors with the user. Unfortunately, when I try to run the program, my return(sentence+outcome) both returns null. I am new to using methods, so please explain what I am doing wrong here... Thank you!
package rockpaperscissors;
/**
*
* #author Owner
*/
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int tie = 0;
static int lose = 0;
static int win = 0;
static String outcome;
static String sentence;
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
} else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
} else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
computerChoice = 1 + (int) (Math.random() * ((3 - 1) + 1));
if (computerChoice == 1) {
System.out.println("The computer has chosen Rock.");
} else if (computerChoice == 2) {
System.out.println("The computer has chosen Paper.");
} else {
System.out.println("The computer has chosen Scissors.");
}
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
System.out.println("==SCORES==");
System.out.println("WINS: " + win);
System.out.println("TIES: " + tie);
System.out.println("LOSSES: " + lose);
System.out.println("Press 1 to play again, or any other number to exit.");
String play = userInput.nextLine();
playAgain = Integer.parseInt(play);
} while (playAgain == 1);
}
public static String determineOutcome(String outcome, String sentence) {
sentence = "Your result is: ";
do {
if (weaponChoice == 1 && computerChoice == 1 || weaponChoice == 2 && computerChoice == 2 || weaponChoice == 3 && computerChoice == 3) {
tie++;
outcome = "TIE";
} else if (weaponChoice == 1 && computerChoice == 3 || weaponChoice == 2 && computerChoice == 1 || weaponChoice == 3 && computerChoice == 2) {
win++;
outcome = "You WON!";
} else {
lose++;
outcome = "You LOSE. Better luck next time?";
}
} while (lose <0 || win < 0 || tie < 0);
return(sentence+outcome);
}
}
To make this work, you'll need to replace
determineOutcome(outcome, sentence);
System.out.println(sentence+outcome);
with
String valueReturned = determineOutcome(outcome, sentence);
System.out.println(valueReturned);
because Java is pass by value, not pass by reference. That means that the determineOutcome method will work with its own copies of outcome and sentence, and not modify the versions that belong to the method that called it.
But also, the method is not actually using the two arguments you pass into it. It would be much less confusing if you just omit the parameters entirely, and change it to public static String determineOutcome() ... and declare String sentence; and String outcome; inside the method.
When calling a function that is returning a result you must either call the function within System.out.println() or assign the result to a variable which you then print.
Option 1:
String result = determineOutcome(outcome, sentence);
System.out.println(result);
or option 2:
System.out.println(determineOutcome(outcome, sentence));
In addition to the points other people made in their answers, it looks like your while loop is never being executed. The variables tie, win and lose are never less than 0, so the condition of the while loop is never true. You can try changing it to:
while (lose <= 0 || win <= 0 || tie <= 0);
But be warned, this will result in an infinite loop, so you may need to rethink your logic. You may not need a loop here, depending on what you're trying to do.

intro java coding. don't understand what i'm doing wrong

i'm really not sure what's wrong with my code. It's supposed to do rock paper scissors against the computer by taking in the user choice, comparing it to the random computer choice, and displaying the results.
I get two errors that i have no return statements for the 3rd and 4th methods. Also, when i run it without fixing the errors, the nested if statements starting at line 60 only print out one of the two println statements, which really makes zero sense to me.
import java.util.Random;
import java.util.Scanner;
public class Chapter5ProjectPart2 {
public static void main(String[] args) {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
int userNum;
int compNum;
String userChoice = "";
String compChoice = "";
int rnum;
int result = 0;
boolean keepPlaying;
int input = 1;
do
{
compNum = generator.nextInt(2)+1;
compChoice = numToChoice(compNum);
menu();
userNum = keyboard.nextInt();
userChoice = numToChoice(userNum);
keyboard.nextInt();
System.out.println();
System.out.println("you chose " + userChoice);
System.out.println("the computer chose " + compChoice);
result = resultCheck(userNum, compNum);
if (result == 1) // user wins
{
if (userNum == 1) //user won choosing rock
{
System.out.println("rock beats scissors");
System.out.println("you win");
}
else if (userNum == 2) //user won choosing paper
{
System.out.println("paper beats rock");
System.out.println("you win");
}
else if (userNum == 3) //user won choosing scissors
{
System.out.println("scissors beats paper");
System.out.println("you win");
}
}
else if (result == 3) //user loses
{
if (userNum == 1) //user lost choosing rock
{
System.out.println("paper beats rock");
System.out.println("you lose");
}
else if (userNum == 2) //user lost choosing paper
{
System.out.println("scissors beats paper");
System.out.println("you lose");
}
else if (userNum == 3) //user lost choosing scissors
{
System.out.println("rock beats scissors");
System.out.println("you lose");
}
else if (result == 2) //draw
System.out.println("draw");
}
System.out.println("would you like to play again?");
System.out.println("1 = yes");
System.out.println("2 = no");
input = keyboard.nextInt();
keepPlaying = play(input);
} while (keepPlaying == true);
}
// method 1 (menu)
public static void menu()
{
System.out.println("Enter your choice of rock, paper, or scissors\n" + "1 = rock\n" + "2 = paper\n" + "3 = scissors");
}
// method 2 (result check)
public static int resultCheck(int userNum, int compNum)
{
if (userNum == 2 && compNum == 1)
return 1;
else if (userNum == 1 && compNum == 3)
return 1;
else if (userNum == 3 && compNum == 2)
return 1;
else if (userNum == compNum)
return 2;
else
return 3;
}
// method 3 (converting number choice to rock/paper/scissors
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
//method 4 (play again)
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
}
I get two errors that i have no return statements for the 3rd and 4th methods.
Right. Let's look at the third:
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
Suppose num isn't 1, 2, or 3? Then what should the return value of the method be? That's why you're getting the error, you need a final else (with no if) saying what that return value should be when none of the earlier branches has returned a value. Without it, the method causes a compile-time error.
Also, when i run it without fixing the errors, the nested if statements starting at line 60 only print out one of the two println statements, which really makes zero sense to me.
You can't run it without fixing the errors, because these are compile-time errors. If you try to compile this source code with those errors in place, it fails, and you don't get an updated class file. So if you then try to run, and it seems to work, you're running an earlier copy of the class file you compiled before those errors were there. That class file doesn't relate to the current source code, and so it's understandable that it would make no sense to you. You're not looking at what the JVM is running.
If you correct the methods so that things compile (by adding the final else with no if on it), then run the compiled result, things should make more sense. Meanwhile, you might want to delete the previous Chapter5ProjectPart2.class file, since it's out of date.
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
//method 4 (play again)
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
These methods should always return something. Method 3 for example, if int num is 4 it won't return anything. Solve it by adding:
else return "";
That's because you are not ending your else-if statement in methods 3 and 4 with an else clause.
You indeed lack return statements. Java expects a non-void method to always return a value or throw an exception. Having a non-void method end without returning or throwing an exception is an error.
public static String numToChoice(int num)
{
if (num == 1)
return "rock";
else if (num == 2)
return "paper";
else if (num == 3)
return "scissors";
}
Here, your method doesn't return anything if num isn't 1, 2 or 3. Likewise:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
Here inputs that aren't 1 or 2 lack their return statements.
First of all, never run code that doesn't compile.
Second: examine this method:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
}
What would the method return if input is 6, or -67, or 789? You didn't tell, and the compiler can't guess it. So it refuses to compile until you tell it what to return in these cases.
If the other cases should never happen, then throw an exception:
public static boolean play(int input)
{
if (input == 1)
return true;
else if (input == 2)
return false;
else {
throw new IllegalStateException("input is " + input + ". Something's really wrong");
}
}
Java method MUST return a value unless it states void as return.
In your play method, if input is not 1 or 2, Java won't return any value. This does not allow to compile in Java.
In your numToChoice method, if num is not 1, 2 or 3, Java won't return any value. This does not allow to compile in Java.
Add an else close to return a value in "unexpected" cases, and allow Java to compile.

Categories

Resources