Boolean bug (FibonacciNumbers) - java

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.

Related

Stuck with detecting next line from console

I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}

Java - Continue a game

I made some command line games and at the end of the game I want to ask if the player wants to play again. You can see in the code how I made but it's not working and I don't know why.
Can anybody help me?
import java.util.Scanner;
//WIP
public class GuessingGame2 {
static Scanner userInput = new Scanner(System.in);
static int randNumber;
static int guessNumber;
static boolean gameStatus;
static void checkNum(int x) {
guessNumber++;
if(x == randNumber) {
gameStatus = true;
} else if(x < randNumber) {
System.out.println("Too small!");
} else {
System.out.println("Too big!");
}
}
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine() == "Y" || userInput.nextLine() == "y") {
guessGame();
} else if(userInput.nextLine() == "N" || userInput.nextLine() == "n") {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
static void guessGame() {
randNumber = (int) (Math.random() * 1000);
guessNumber = 0;
gameStatus = false;
System.out.println("Try to guess a number from 1 to 1000!");
while(gameStatus == false) {
System.out.print("Your guess: ");
if(userInput.hasNextInt()) {
checkNum(userInput.nextInt());
} else {
System.out.println("You need to choose a number!");
userInput.next();
}
}
System.out.println("You guessed the number in " + guessNumber + " tries.");
System.out.print("Do you want to play again? Y or N ");
checkAnsw();
}
public static void main(String[] args) {
guessGame();
}
}
Change your checkAnsw method to this:
static void checkAnsw() {
if(userInput.hasNextLine()) {
if(userInput.nextLine().equalsIgnoreCase("y")) {
guessGame();
} else if(userInput.nextLine().equalsIgnoreCase("n")) {
} else {
System.out.print("Y or N ");
checkAnsw();
}
} else {
System.out.print("Y or N ");
userInput.next();
checkAnsw();
}
}
You cannot compare Strings with the = as they are objects. Use the .equals method to compare Strings.
Your code works fine, I have copied and pasted it in Eclipse and this is the output:
Try to guess a number from 1 to 1000!
Your guess: eeeee
You need to choose a number!
Your guess: 1
Too small!
Your guess: 2
Too small!
Your guess: 2
I don't understand which is your problem, try to explain better

How to go back into a while-loop, from an if statement?

Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement

why the code does not respond and keep runing?

I am writing a program that translates from Roman numerals to decimal numbers.
For some reason it does not return the value when it checks the user's input. However it already fixed,
what I'm facing right now is: The code does not respond me the number (it's keep show a blank screen after the input).
How can I fix this? Is there an issue in my code? I am just a starter so what I have learned is just basic stuff.
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()<=0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
return i;
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int numb = 0;
int n=0;
int ch=0;
while (n<numeral.length()) {
char l= numeral.charAt(n);
numb=convertCharacterToNumber(l);
if (numb<0) {
System.out.println("Cannot be define");
n++;
}
else if (n==numeral.length()) {
ch+=numb;
}
else {
int nnumb=convertCharacterToNumber(numeral.charAt(n));
if (nnumb>numb) {
ch+=nnumb-numb;
n++;
}
else {
ch+=numb;
}
}
}
if (ch>3999) {
System.out.println("Input number must be less than 3999");
numb=ch;
}
return numb;
}
private static int convertCharacterToNumber(char numeral) {
// Fill in the body
int n=0;
if (numeral=='m' || numeral =='M') {
return 1000;
}
else if (numeral=='d' || numeral=='D') {
return 500;
}
else if (numeral=='c' || numeral=='C') {
return 100;
}
else if (numeral=='l' || numeral=='L') {
return 50;
}
else if (numeral=='x' || numeral=='X') {
return 10;
}
else if (numeral=='v' || numeral=='V') {
return 5;
}
else if (numeral=='i' || numeral=='I') {
return 1;
}
else {
return -1;
}
}
}
public class stringTest {
public static void main(String[] args) {
// Fill in the body
Scanner in= new Scanner(System.in);
String user = promptUserForNumeral(in);
while (user.length()!=0) {
int numb= convertNumeralToNumber(user);
System.out.println("The numeral "+user+ " is the decimal number "+numb);
user = promptUserForNumeral(in);
}
}
private static String promptUserForNumeral(Scanner inScanner) {
// Fill in the body
System.out.println("Enter a roman numeral (Q to quit): ");
String i = inScanner.nextLine();
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
else return i; // in your program the while is never ending, so it does not return any value.
}
return "";
}
private static int convertNumeralToNumber(String numeral) {
// Fill in the body
int preNumber = 0;
int curNumber = 0;
int n=0;
int ch=0;
while (n<numeral.length()) {
char l= numeral.charAt(n);
curNumber=convertCharacterToNumber(l);
if (curNumber<0) {
System.out.println("Cannot be define");
System.exit(0);
}
else {
// I have changed the logic to evaluated decimal Number equivalent to Roman Literal
if(preNumber < curNumber && n != 0) ch = curNumber - ch;
else ch += curNumber;
preNumber = curNumber;
}
n++;
}
return ch;
}
private static int convertCharacterToNumber(char numeral) {
// Fill in the body
if (numeral=='m' || numeral =='M') {
return 1000;
}
else if (numeral=='d' || numeral=='D') {
return 500;
}
else if (numeral=='c' || numeral=='C') {
return 100;
}
else if (numeral=='l' || numeral=='L') {
return 50;
}
else if (numeral=='x' || numeral=='X') {
return 10;
}
else if (numeral=='v' || numeral=='V') {
return 5;
}
else if (numeral=='i' || numeral=='I') {
return 1;
}
else {
return -1;
}
}
}
You can probably look into promptUserForNumeral method, I think it is not necessary. You can include that in the main while loop to look for user errors.
Check this
while (i.length()>=0) {
if (i.length()==0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
else if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
}
return i;
This won't quit or return anything while i.length() > 0. That return is dead code if user didn't enterq.
Solution: Specify a else with break; then it will work.
else
break;
I would rewrite your while loop :
while (i.length()<=0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
}
if ( i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
return i;
You have lots of redundant conditions. The problem lies within this loop:
while (i.length() >= 0) {
if (i.length() == 0) {
System.out.println("ERROR! You must enter a non-empty line!");
System.out.println("Enter a roman numeral (Q to quit): ");
i = inScanner.nextLine();
} else if (i.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
System.exit(0);
}
}
Take any value for i like "V".
It's length is greater than zero, hence it enters the loop.
It's length is again not zero in the first if condition, hence it proceeds to the elseIf
Since the value isn't a "q", the else part doesn't execute either.
So it goes back to the loop's start & again checks the condition if length is greater than zero.
So, you have an infinite loop. Work through your logic again & remove any unnecessary conditions. You can also use the break; statement to terminate the loop.

Correct code will not compile?

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.

Categories