0

So the code is supposed to continually give fibonacci values for any given number until you enter "q", but for some reason instead of stopping, I get an error, anyone know why? I know that if you try to parse a string, it will cause the error but I have "if(input != "q")" to stop that so why is it still happening?

Tester class:

import java.util.Scanner;
public class FibonacciTester
{
    public static void main(String[] args)
    {
        String input = "1";
        System.out.println("Input a positive integer that you want to find the fibonacci number for");
        System.out.println("Type 'q' to quit");
        Scanner in = new Scanner(System.in);
        while (input != "q"){
            System.out.print("Type in the positive integer");
            input = in.next();
            if(input != "q"){
                int number = Integer.parseInt(input);
                FibonacciV fibonacci = new FibonacciV(number);
                number = FibonacciV.fibonacci(number);
                System.out.println("The Fibonacci number: " + number);  
            }
        }
    }
}

Class

public class FibonacciV
 {
    FibonacciV(int x)       
    {
    }
    public static int fibonacci(int x)
    {
        if (x == 0)            //Base case
        {
            return 0;
        }
        else if (x == 1)       //Second base case
        {
            return 1;
        }
        else 
        {
            return fibonacci(x-1)+ fibonacci(x-2);   // recursive call
        }
     }
}
Yitian Zhang
  • 314
  • 1
  • 3
  • 18

1 Answers1

3

Change input != "q" to !input.equals("q").

Read more about how to compare strings in java.

You are getting NumberFormatException because it's running Integer.parseInt(input) when the input is "q", which is not a number. And the code was able to reach this statement because your string comparison is incorrect.

Kartik
  • 7,677
  • 4
  • 28
  • 50
  • Thanks, you were right, I tried to use notequals but it wouldn't work lmao so i thought it was != – mantaray205 Oct 16 '18 at 03:13
  • Im kind of new to programming and never used !*****.equals – mantaray205 Oct 16 '18 at 03:14
  • 1
    @mantaray205 it's not about equals.. you can toggle any boolean value by putting a `!` in front of it.. in this case `input.equals("q")` returns true/false, so we added `!` in front to make it false/true. – Kartik Oct 16 '18 at 03:20