Return statement error, return null instead - java

I'm trying to use a method to display an error message if the user enters a number other than 1 - 4, but I'm getting a missing return statement error.
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
} else {
return (playerAnswer); }
} while (incorrectAnswer);
}
The error points to the last bracket. I've done some looking around online and I think the problem is that I don't have a return statement in both parts of the if-else statement. But if they have entered an incorrect number I don't want to return anything. I tried using the below code unsuccessfully.
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
return (null);
} else {
return (playerAnswer); }
} while (incorrectAnswer);
}

The compiler's analysis does not determine that
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
} else {
return (playerAnswer); }
} while (incorrectAnswer);
is indeed an infinite loop, and the only way to get out of the loop is the return in the else branch. (Since incorrectAnswer cannot be changed except by cosmic rays flipping bits, it is, but the compiler isn't convinced.)
Thus it wants a return in case the loop is left in a different way.
If you make the loop condition a literal true,
do {
// code
} while(true);
the compiler will know that the loop can only be left via the return in the else branch (you can and should eliminate the boolean incorrectAnswer; then).
As yannis hristofakis observed, calling playerAnswer = CheckAnswers(); immediately in the loop causes an infinite recursion, and that will lead to a stack overflow. You need to call a method that obtains some input from the user instead there.

I'm amazed that 3 answers were posted and none of them mentioned that
It's an eternal procedure since you call recursevly the CheckAnswers method.
You can't return null for primitive return type methods.
I think you should skip the parenthesis.
return playerAnswer;

Just do a return statement of return -1 right after the do while.
You will not ever reach that code, but it will make the compiler happy who is not able to understand the logic of your code and just sees that there are possible execution paths that don't return anything.
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
}
else {
return (playerAnswer);
}
} while (incorrectAnswer);
return -1; //unreachable statement
}

Try this:
public int CheckAnswers () {
boolean incorrectAnswer = true;
do {
playerAnswer = CheckAnswers();
if (playerAnswer < 1 || playerAnswer > 4) {
System.out.println("You have entered an incorrect number.");
System.out.println("Please enter a number between 1 and 4");
} else {
incorrectAnswer = false;
}
} while (incorrectAnswer);
return playerAnswer;
}

Related

How can I check that the next input is an integer while checking if it's > and < at the same time in Java?

There's two things I'm needing help with. Loop issue 1) I have to initialize this variable outside of the loop, which makes the loop fail if the user inputs a string. Is there a way around that? Basically, if I set N to anything then the do-while loop just immediately reads it after getting out of the
import java.util.Scanner;
/**
* Calculates sum between given number
*/
public class PrintSum {
public static void main(String[] args) {
int N = 0;
String word;
boolean okay;
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a number from 1-100: ");
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
} else {
okay = true;
}
} while (!okay);
loop(N, 0);
}
public static void loop(int P, int total) {
while (P >= 1) {
total = total + P;
P--;
}
System.out.println(total);
}
}
If not, then the issue becomes, how do I solve this? I thing that I need to be able to say
if (scan.hasNextInt() || ??? > 100 || ??? < 1) {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
} else {
okay = true;
}
What do I put in the ??? to make this work? I think I just don't know enough syntax.
Thank you!
Why don't you try this?
do {
if (scan.hasNextInt()) {
N = scan.nextInt();
} else {
okay = false;
word = scan.next();
System.err.print(word + " is an invalid input. Try again. ");
continue;
}
if (N > 100 || N < 1) {
okay = false;
System.err.print("Invalid Input. Try again. ");
continue;
} else {
okay = true;
}
} while (!okay);
break is used to end the loop as soon as the user enters the invalid character(condition of the else clause), so the loop doesn't fail.
Looking at your edited question, continue is what you are looking for if you might want to allow the user to enter another value after entering the invalid value.
Use break or continue based on requirement. More on breaks and continue.
Your second approach can be solved as follows:
if (scan.hasNextInt()){
N = scan.nextInt();
if (N > 100 || N < 1) {
System.err.print("Invalid input. Try again. ");
}
//perform some operation with the input
}
else{
System.err.print("Invalid Input. Try again. ");
}

Validate User Input Using Java Chars and Strings

I have seen this asked 2x, but the correct response I need has not been addressed.
In this assessment,
you will design and code a Java console application that
validates the data
entry
of a course code (like IT4782)
and
report
back if the
course code is valid or
not
valid.
The
application
uses the Java char
and
String data types to implement
the validation.
You
can
use
either
the
Toolwire environment
or your
local
Java
development
environment
to complete this
assignment.
The requirements of
this application are
as follows:
The application is to read
a course code
entered
by the user
from the
keyboard.
The course code
is made
of 5 characters and should
follow
these
Rules:
First
character
is always
an
upper
case I
or a lower
case i
Second character
is always an upper
case
T or
a lower
case t
Third,
fourth,
fifth,
and sixth characters
are always digits (0-
9)
The application then validates the course code against
above the rules and prints a
message
If the
course code
is valid
or not.
If the course code is not
valid,
the application should print
a message
explaining why
the course
code is not
valid.
Output should look like this:
Here is my code, I cannot get the code to produce the pictured results. It outputs all the invalid messages.
package u4a1_validatecoursecode;
import java.util.Scanner;
public class U4A1_ValidateCourseCode {
public static void main(String[] args) {
// Larry Copy
Scanner s = new Scanner(System.in);
System.out.print("Enter a course code to validate (e.g. IT4782) : ");
String code = s.nextLine();
if (validateCode(code)) {
System.out.println("Course code: " + "" + code + "" + " is valid.");
} else {
System.out.println("Not valid code");
}
}
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
return false;
}
System.out.println("integer is not an I or i");
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
return false;
}
System.out.println("integer is not a T or t");
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
return false;
}
System.out.println("integer 3 is not a number");
if (!Character.isDigit(code.charAt(3))) {
return false;
}
System.out.println("integer 4 is not a number");
if (!Character.isDigit(code.charAt(4))) {
return false;
}
System.out.println("integer 5 is not a number");
if (!Character.isDigit(code.charAt(5))) {
return false;
}
System.out.println("integer 6 is not a number");
return false;
}
}
}
When you return false; the code after is not executed so you'll never see why it returns
If you return only false the test will never pass, you need a variable to validate or not the code
If it goes in one if (not valid) you'll get the message, and the valid will be false
private static boolean validateCode(String code) {
if (code.length() != 6) {
return false;
} else {
boolean valid = true;
//First character is always an upper case I or a lower case i
if (code.charAt(0) != 'I' && code.charAt(0) != 'i') {
System.out.println("integer is not an I or i");
valid = false;
}
// Second character is always an upper case T or a lower case t
if (code.charAt(1) != 'T' && code.charAt(1) != 't') {
System.out.println("integer is not a T or t");
valid = false;
}
// Third, fourth, fifth, and sixth characters are always digits (0-9)
if (!Character.isDigit(code.charAt(2))) {
System.out.println("integer 3 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(3))) {
System.out.println("integer 4 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(4))) {
System.out.println("integer 5 is not a number");
valid = false;
}
if (!Character.isDigit(code.charAt(5))) {
System.out.println("integer 6 is not a number");
valid = false;
}
return valid;
}
}
You are using too much line of code:
Here what I do:
private static boolean validateCode(String code,String validCode) {
boolean b=true;
if (code.length() != 6) {
return false;
}
for(int i=0;i<code.length();i++){
if(code.toLowerCase().charAt(i)!=validCode.toLowerCase().charAt(i) && i<2){
System.out.println("Character at "+i+" position is not an "+ validCode.charAt(i));
b= false;
}
if(Character.isDigit(code.charAt(i)) && i>2){
System.out.println("Character at "+i+" is not a digit");
b= false;
}
}
return b;
}

Loop certain IF statements in java

import java.util.Scanner;
public class main {
public static void main(String[] args) {
int number = 0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of sides");
number = input.nextInt();
if (number == 1) {
System.out.println("Circle");
}
if (number == 3) {
System.out.println("Triangle");
}
if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
}
}
Hello, I am trying to use the if statement. Can anyone advise me how to loop if statements? Because I get this as a result for example:
circle
Incorrect Input.
Also, How could I repeat the scanner so it allowed me to type another input?
Currently, the else clause is only associated to the last if block i.e. if (number == 4) {...} This means if any of the other if blocks are executed, it will still print "Incorrect Input". The solution is to use else if instead of separate if's.
if (number == 1) {
System.out.println("Circle");
}else if (number == 3) {
System.out.println("Triangle");
}else if (number == 4) {
System.out.println("quadrilateral");
}
else {
System.out.println("Incorrect Input");
}
You can use switch case (see : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html).
And you can check the type of number or string with instanceof.
For your second part question, I guess you're looking for something like a do....while loop, you can set up some condition like if the input result is not a number, then it will stuck in the loop until the user type in a number then only go in the the if, else-if statement

value is not returning from another class

Hi I'm making a game where the player is met with a robot and the robot asks it to guess a number between 1-10. The player has three tries or they die. I've written all my code and the guessing works fine but whenever the play gets it right he still dies. I added a couple of print statements to see what value my code was returning and it seems to be returning the wrong value. Can someone help me out? Thanks.
Goes from this class
if (choice != -1) {
if (john[choice] != null) {
if (john[choice].compPlayerAttack()) {
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
else {
System.out.println("Robot appears. Guess a number between 1-10. Get it right and you can pass, or you die. You have three chances.\"");
int answer = 0;
john[choice].toPass(answer);
if (answer== 1) {
System.out.println(answer);
map[x][y].removeJohnPlayer();
}
else { System.out.println(answer);
System.out.print("IT'S GAME OVER MAN!\n");
System.exit(0);
}
To this class
public int toPass(int right){
int hiddenNum = numram.nextInt(MAX_NUMBER);
Scanner input = new Scanner(System.in);
int numOfGuesses = 0;
int a = right;
do {
System.out.println("Enter a number by guessing: ");
int guessedNum = input.nextInt();
numOfGuesses++;
if (guessedNum == hiddenNum) {
System.out.println("Darn! Your number is matched. You may live.");
System.out.println("You have made " + numOfGuesses + " attempts to find the number!");
a = 1;
break;
} else if (guessedNum < hiddenNum) {
System.out.println("Try a bigger number");
} else if (guessedNum > hiddenNum) {
System.out.println("Try a smaller number");
}
} while (numOfGuesses < 3);
System.out.println(a);
return a;
}
Here
john[choice].toPass(answer);
you are ignoring the value returned by your toPass method.
Change it to:
answer = john[choice].toPass(answer);
BTW, there's no reason to pass an argument to your toPass method, since it makes no use of it, and it can't change it (since Java is a pass by value language). A return value is enough.
i.e. change your method to public int toPass().
Another change you should make is to change the return type to boolean. Returning true or false is more readable than returning 1 or 0.

Java Loop only running once

Im building a code guessing game if you insert an invalid input ie( 333 ) it will prompt you to change your guess. however this only works on guess #1 on guess #2 - #6 it will let any invalid input go through
public void game(){
System.out.println("Enter guess #" + (guessAtt + 1));
guess = keyboard.next();
guess = guess.toLowerCase();
if( guess.equals(quit)){
System.exit(0);
}
if (guess.length() < 2){
System.out.println("Guess Too short try again");
game();
}
if (guess.length() > 3){
System.out.println("Guess too long try again");
game();
}
letter1 = guess.charAt(0);
letter2 = guess.charAt(1);
letter3 = guess.charAt(2);
isValid();
}
public boolean isValid(){
if (letter1.equals('a')|| letter1.equals('b')|| letter1.equals('c')|| letter1.equals('d')|| letter1.equals('e')){
isValid1 = true;
}
if(letter2.equals('a')|| letter2.equals('b')|| letter2.equals('c')|| letter2.equals('d')|| letter2.equals('e')){
isValid2 = true;
}
if(letter3.equals('a')|| letter3.equals('b')|| letter3.equals('c')|| letter3.equals('d')|| letter3.equals('e')){
isValid3 = true;
}
if(isValid1 == true && isValid2 == true && isValid3 == true){
isValid = true;
}
else {
isValid = false;
}
while (isValid == false){
System.out.println("invalid input try again\n");
game();
}
return isValid;
}
you could both use a while loop in the game that breaks when isValid() returns a true. You could also call the function game if isValid() returns a false value. Now you ask for a boolean value, but you don't use it. No matter what it returns, as long as your value contains the right lenght, the game ends.

Categories