Correct code will not compile? - java

This code seems perfectly fine for me (CS101) but my IDE throws up the error "This method must return a result of type boolean"
I don't want any tips on how to streamline my code or anything like that just want a reason for / solution as to why this is happening
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}else if ( userInput.equals(correct2) )
{
return false;
}else
{
System.out.println("Try again!");
}
}
}
Question is now solved, anyone interested why i needed this full code below:
import java.util.*;
public class CheckingInput
{
public static void main(String args[])
{
System.out.println("What is 1+1?");
boolean answer = validation("two", "three");
if(answer == true)
{
System.out.print("Correct!");
}else if(answer == false)
{
System.out.print("Wrong!");
}
}
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
boolean correctInput = false;
String userInput;
while (correctInput == false)
{
System.out.print("Type in " + correct1 + " or " + correct2 + ": ");
userInput = in.next();
if ( userInput.equals(correct1) )
{
correctInput = true;
return true;
}else if (userInput.equals(correct2))
{
correctInput = true;
return false;
}else
{
System.out.println("Try again!");
correctInput = false;
}
}
return false;// Doesn't really matter, loop will never reach here
}

I'm assuming the infinite loop is intentional, as you're awaiting a response from your user, so try the following:
public static boolean validation(String correct1, String correct2)
{
Scanner in = new Scanner(System.in);
String userInput;
while (true)
{
System.out.print("Type in " + correct1 + " or " + correct2);
userInput = in.next();
if ( userInput.equals(correct1) )
{
return true;
}
else if ( userInput.equals(correct2) )
{
return false;
}
else
{
System.out.println("Try again!");
}
}
return false; // Doesn't really matter, loop will never reach here
}

A return true; or return false statement is missing before the end of the function, in case the loop exits.

Related

How can I find out why my Java program keeps crashing?

I have been learning Java for a week, I have no other experiences. The program keeps crashing, I would like to be automatically asked again in the event of an incorrect entry.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
boolean error;
Scanner scan = new Scanner(System.in);
do {
error = false;
System.out.print("Tell me the Year: ");
if (scan.hasNextInt()) {
int jahr = scan.nextInt();
scan.close();
if (schaltjahre(jahr)) {
System.out.println("Please enter the leap year ");
} else {
System.out.println("It is not a leap year");
}
} else {
System.err.println("enter an integer year!");
error = true;
scan.close();
}
}while (error);
}
public static boolean schaltjahre(int jahr) {
// Aufgabe 1
if (jahr % 400 == 0) {
return true;
} else if (jahr % 100 == 0) {
return false;
} else if (jahr % 4 == 0) {
return true;
}
return false;
}
You should instantiate the scanner inside the loop and don't close it in the else statement.
Your code should be something like this :
public static void main(String[] args) {
boolean error;
Scanner scan ;
do {
error = false;
scan = new Scanner(System.in);
System.out.print("Tell me the Year: ");
if (scan.hasNextInt()) {
int jahr = scan.nextInt();
scan.close();
if (schaltjahre(jahr)) {
System.out.println("Please enter the leap year ");
} else {
System.out.println("It is not a leap year");
}
} else {
System.err.println("enter an integer year!");
error = true;
}
} while (error);
}

Trying to get isMultiple to execute properly

this executes, however it returns all answers as positive "8 is a multiple of 15" even if it is false. Not sure what I'm not seeing.
Here is what i have:
import java.util.*;
public class Multiples {
public static void main(String [] args){
boolean run = true;
while(run = true){
Scanner input = new Scanner(System.in);
System.out.print("Enter one number:");
int num1 = input.nextInt();
System.out.print("Enter a second number:");
int num2 = input.nextInt();
boolean result = isMultiple(num1,num2);
if(result = true){
System.out.println(num2 + " is a multiple of " + num1);
}
else{
System.out.println(num2 + " is not a multiple of " + num1);
}
System.out.println("Do you want to enter another pair(y/n)?");
String a = input.next();
if(YesOrNo(a)){
break;
}
}
}
public static boolean YesOrNo(String a){
if(a.equals("y"))
return false;
else if(a.equals("n"))
return true;
else
return true;
}
public static boolean isMultiple (int x , int y){
if(x % y == 0 || y % x == 0)
return true;
else
return false;
}
}
if(result = true){
replace with
if(result == true){
(or simply)
if(result){
You are assigning it instead of comparing.

How to make this a simpler code (Java, simple String input, say if it's the correct one or no)

This is hat I've came up with:
public static void main(String[] args){
String pass = "admin";
int derp = 0;
Scanner input = new Scanner(System.in);
System.out.print("Insert the admin pass: ");
String test = input.nextLine();
if (pass.equals(test)){
System.out.print("Access granted");
}else{
int counter = 3;
while (counter > 1){
counter--;
System.out.print("You have "+counter+" try(es): ");
test = input.nextLine();
if (pass.equals(test)){
System.out.print("Access granted");
counter -= 2;
}else{
derp++;
}
}
}
if (derp == 2){
System.out.print("Access denied");
}
}
How can I make it say "Access denied"? You can probably see that to solve it I just made an int called "derp" What should I do to remove it and still say "Access denied" if the user fails three times?
Thanks. Also, if you think that there are more things that could be improved, I would be greatly appreciated.
I would do something like
boolean success = false;
int times = 0;
do {
input.nextLine();
if (condition) {
success = true;
} else {
count++;
}
} while(!success && times < MAX_TIMES);
if (success) {
print("SUCCESS!!");
} else {
print("FAIL");
}
I will go with below code :
boolean flag = true;
int counter = 3;
while(flag)
{
if (pass.equals(test))
{
System.out.print("Access granted");
break; // Permission granted so out of the Loop
}
else if(counter==0)
{
flag = false;
break;
}
System.out.print("You have "+counter+" try(es): ");
test = input.nextLine();
counter--;
}
if(!flag)
{
System.out.print("Access denied");
}
Using a for loop and break statement you can do something like this
public static void main(String[] args) {
String pass = "admin";
Scanner input = new Scanner(System.in);
System.out.print("Insert the admin pass: ");
String test = input.nextLine();
if (pass.equals(test)) {
System.out.print("Access granted");
} else {
for (int i = 1; i < 3; i++) {
System.out.print("You have " + i + " try(es): ");
test = input.nextLine();
if (pass.equals(test)) {
System.out.print("Access granted");
break;
} else if (i == 2) {
System.out.print("Access denied");
}
}
}
}
Try it:
public static void main(String[] args) {
String pass = "admin";
int maxTry = 3;
boolean success = false;
Scanner input = new Scanner(System.in);
System.out.print("Insert the admin pass: ");
String test = input.nextLine();
while(maxTry>0){
maxTry--;
if (!pass.equals(test)) {
System.out.print("You have " + maxTry + " try(es): ");
test = input.nextLine();
} else {
success = true;
break;
}
}
if(success){
System.out.println("Access granted");
}else{
System.out.println("Access denied");
}
}
If I were to write this code, I would have written like following:
import java.util.Scanner;
public class AccessPoint
{
private Scanner scanner;
public AccessPoint()
{
scanner = new Scanner(System.in);
if (tryAccessForTimes(3))
{
allowAccess();
}
else
{
denyAccess();
}
scanner.close();
}
private boolean tryAccessForTimes(int times)
{
boolean accessAllowed = false;
for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++)
{
if (getAdminPassword().equals(getUserPassword()))
{
accessAllowed = true;
}
else
{
printNumberOfTriesLeft(times, tryIndex);
}
}
return accessAllowed;
}
private void printNumberOfTriesLeft(int times, int tryIndex)
{
int triesLeft = times - tryIndex;
if (triesLeft != 0)
{
System.out.println("You have " + triesLeft
+ (triesLeft == 1 ? " try" : " tries") + " left.");
}
}
private String getUserPassword()
{
System.out.print("Enter Password: ");
String password = scanner.nextLine();
return password;
}
private String getAdminPassword()
{
return "admin";
}
private void allowAccess()
{
System.out.println("Access Granted.");
}
private void denyAccess()
{
System.out.println("Access Denied.");
}
public static void main(String[] args)
{
new AccessPoint();
}
}
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
String pass = "admin";
Scanner input = new Scanner(System.in);
for(int i=0;i<3;i++)
{
System.out.print("Insert the admin pass: ");
String test = input.nextLine();
if (pass.equals(test))
{
System.out.print("Access granted");
i=3;
}
else
{
System.out.println("Incorrect password, you have "+(2-i)+" attempts remaining");
}
}
}
}

Calling Certain Methods

import java.util.Scanner;
import javax.swing.JOptionPane;
public class HW {
public static void main(String[] args){
while (retry == true){
getGuess();
getBet(balance);
checkGuess(getGuess());
updateBal(guessResult, betParsed);
goAgain(balance);
}
}
public static String getGuess(){
//Guess input
System.out.println("Guess: (H/T");
Scanner in = new Scanner(System.in);
boolean validInput = false;
String guess = null;
while (validInput == false){
guess = in.next();
if (guess.equals("H") || guess.equals("T")){
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Input: " + guess);
}
}
return guess;
}
public static boolean checkGuess(String sideGuess){
//Checks if the side is correct
double num = Math.round(Math.random());
boolean guessResult;
if (num == 0 && sideGuess.equals("H")){
System.out.println("Correct. The side was: H");
guessResult = true;
return true;
} else if (num == 1 && sideGuess.equals("T")){
System.out.println("Correct. The side was: T");
guessResult = true;
return true;
} else {
System.out.println("Incorrect.");
guessResult = false;
return false;
}
}
public static double getBet(double balance){
//Retrieves a bet from the user
Scanner in = new Scanner(System.in);
String betInput = null;
double betParsed = 0;
boolean validInput = false;
while (validInput == false){
betInput = in.next();
try {
betParsed = Double.parseDouble(betInput);
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invlaid Input: " + betInput);
}
if (betParsed > balance || betParsed < 0){
JOptionPane.showMessageDialog(null, "Invalid Input! You have: $" + balance);
} else {
validInput = true;
}
}
return betParsed;
}
public static double updateBal(boolean checkGuess, double getBet){
//Updates the balance based on the bet
double balance = 0;
if (checkGuess == true){
balance = balance + getBet * 2;
System.out.println("Your balance is now: $" + balance);
} else {
System.out.println("Your balance is now: $" + balance);
balance = balance - getBet;
}
return balance;
}
public static boolean goAgain(double balance){
//Determines if new play is needed
Scanner in = new Scanner(System.in);
boolean validInput = false;
String goAgainInput = null;
boolean retry;
while (validInput == false){
System.out.println("Go again? (Y/N)");
goAgainInput = in.next();
if (goAgainInput.equals("Y") || goAgainInput.equals("N")){
validInput = true;
} else {
JOptionPane.showMessageDialog(null, "Invalid Input: " + goAgainInput);
}
}
if (goAgainInput.equals("Y")){
retry = true;
return true;
} else {
System.out.println("You ended with: $" + balance);
retry = false;
return false;
}
}
}
Edited the code.
I'm trying to pass some defined variables into some of the methods, but it seems that I can't use them?
How can I fix this?
It seems they are not "local", which I cannot understand as they are defined in the methods.
I must be under thinking it.
The main() method should look like this, with only one parameter:
public static void main(String[] args) {
And for the second issue, updateBal() receives two parameters, but you're passing none. So the compiler is correctly complaining that you should pass them, according to what you want to do:
updateBal(false, 0); // pass the right values
Regarding the passing of parameters to the method, this is wrong:
getBet(balance);
checkGuess(getGuess());
updateBal(guessResult, betParsed);
You see, the variables guessResult and betParsed are local to the methods in which they were defined, you can't use them outside. And the methods return a value, which gets lost, because you're not using or storing it. Both problems have a simple solution - declare new variables local to the method:
double betParsed = getBet(balance);
boolean guessResult = checkGuess(getGuess());
updateBal(guessResult, betParsed);
Again, the same problem is here, in the main loop:
boolean retry = true;
while (retry) {
// ...
retry = goAgain(balance);
}
Bottom line: you must do something with the value returned by methods, and the variables declared inside a method will not be visible outside them.

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Categories