Why do i get a NumberFormatException error? [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
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
}
}
}

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.

Related

Java search for number sequence

Here are the exact words of my project
"Write a class and test program that prompts the user to enter a three-digit number
such that the digits are in order. For example 123, 567. The program will loop until a
correct value is entered. ( 576 is incorrect)"
I have written this program that searches for a specific password but what i need is one that searches for any numerical value where the numbers are in order and im having trouble writing a program that searches for something thats not a specific value, heres what i have so far.
import java.util.Scanner;
public class pass {
public static void main(String[] args) {
int passw;
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter 3 digits in sequence");
passw = sc.nextInt();
if(passw != 567) {
System.out.println("Access Denied");
}
else {
System.out.println("Access Granted");
}
}
while(passw != 567);
}
}
You could use a method to check for whether the given digits are in order.
private boolean isInOrder(int number){
int digit = -1;
while(number > 0){
if (digit != -1 && digit != (number % 10) + 1)
return false; // Since the number is not in order
digit = number % 10;
number /= 10;
}
return true; // If the number is in order
}
This method can check whether a number (of any length, not only 3), is in the order specified in the question.
Since you know that your "password" will be an integer with only three digits, you can easily accomplish whether the digits are ordered or not with an if statement. Try out the following code and see if it works for you!
public class ThreeDigitPasswordTest {
public static boolean testPassword(int number) {
char[] cArr = String.valueOf(number).toCharArray();
if((cArr[2] == cArr[1] + 1) && cArr[1] == cArr[0] + 1)
return true;
return false;
}
public static void main(String[] args) {
System.out.println(testPassword(567)); //prints "true"
System.out.println(testPassword(576)); //prints "false"
}
}

Number comparision in java [duplicate]

This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 5 years ago.
This might be a very dumb question. I tried to reverse the input number and compare it.If they are same then, the output should be "the number entered is a palindrome" But, I'm getting out for every number like it is a palindrome.
package com.practise.examples;
import java.util.Scanner;
public class Practise
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
int revNum=0;
while(num!=0)
{
revNum=revNum *10;
revNum= revNum+ num%10;
num=num/10;
}
System.out.println("the reverse of the number is: " +revNum);
if(revNum==num)
{
System.out.println("the number is a palindrome" );
}
else
{
System.out.println("the number entered is not a palindrome");
}
}
}
Easier way:
String num=Integer.toString(s.nextInt());
String revNum = new StringBuffer(num).reverse().toString();
System.out.println("the reverse of the number is: " +revNum);
if(revNum.equals(num))
System.out.println("the number is a palindrome" );
else
System.out.println("the number entered is not a palindrome");
If you're insisting on your method:
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
int original = num;
int revNum=0;
while(num!=0)
{
revNum=revNum *10;
revNum= revNum+ num%10;
num=num/10;
}
System.out.println("the reverse of the number is: " +revNum);
if(revNum==original)
{
System.out.println("the number is a palindrome" );
}
else
{
System.out.println("the number entered is not a palindrome");
}
}
Try something like this:
public static int reverse(int num)
{
try
{
return Integer.parseInt(new StringBuilder(String.valueOf(num)).reverse().toString());
}
catch (Exception ex)
{
// Should not happen...
}
}
You have modified num for getting the reverse, and then using the same num for comparison. Use temporary variables.
your idea seems to only work in VERY specific instances, and the code itself... well, ill just give you a different idea.
create a stack and a queue.
take the original input, and add each consecutive item to each the stack and the queue.
once the queue and stack are full...
iterate until length=0
if stack.pop != queue.dequeue
palindrome=false
you can cast your number to a string and check doe's its palindrome?
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter the number to reverse it:\n");
int num=s.nextInt();
if (isPalindrome(num+"")){
System.out.println("the number is a palindrome" );
}else{
System.out.println("the number entered is not a palindrome");
}
}
public static boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
}

Enter a string to integer scanner [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
I want to say enter an integer when someone trying to enter a string in this code.
Can you help me?
Here is my code:
import java.util.Scanner;
public class kl {
public static void main(String[] args) {
boolean primen = true;
Scanner input = new Scanner(System.in);
System.out.print("Please enter a positive integer that is prime or not : ");
int ncheck = input.nextInt();
if (ncheck < 2) {
primen = false;
}
for (int i = 2; i < ncheck; i++) {
if (ncheck % i == 0) {
primen = false;
break;
}
}
if (primen == true) {
System.out.println(ncheck + " is a prime number.");
}
else {
System.out.println(ncheck + " is not a prime number.");
}
}
}
You can find your solution here: Exception handling, Or use codes below
Here is your complete code:
while(true){
System.out.print("Please enter a positive integer that is prime or not : ");
try{
int i = input.nextInt();
break;
}catch(InputMismatchException e){
System.out.print("Wrong type input, pls try again!");
input.nextLine(); \\ prevent infinite loop
}
You can see: I use a Exception handle processor to catch the InputMismatchException and print on console the message. You can replace InputMismatchException by Exception. It's largest Exception Handler class in java
There are two approaches you can use with Scanner.
Call nextInt() and then catch and handle the InputMismatchException that you will get if the next input token isn't an integer.
Call hasNextInt(). If that returns true then call nextInt().
In either case, if you expected an integer and the user entered something else, then neither nextInt() or hasNextInt() will "consume" the unexpected characters. So if you want the user to try try again, you need to call nextLine() which will read all remaining characters on the line. You will typically discard them.
For more information on handling exceptions:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
For more information on using Scanner:
https://docs.oracle.com/javase/tutorial/essential/io/scanning.html
http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

Making loops in order to test values [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I need help making a loop that looks at each value from 1 to number-1.
Also how to test each value to see if it is a
divisor of number, and if it is, adding it to the sum.
This is what I have so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}
You can use this as a starting block for your application:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}
If you want to do something for a known number of times, it is mostly a good idea to use a for loop. If you want to do something for number 1 to n-1, the loop could look like
for(int i = 1; i < n; i++) { // do stuff }
Note that it starts counting from 1 and stops as soon as i is greater or equal than n.
In order to know whether a number, say n, is divisible by some number, say k, the modulo-operator % could be used. If n % k == 0 this means that n is divisible by k. With an if-statement this can be tested and when you have some sum variable you can add whatever you want to that variable to sum things up.
Hope that helps

Calculator no work [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Could some one please tell me why this calculator isn't working ? It just doesn't provide an awnser.
import java.util.Scanner;
public class Calcu {
public static void main( String[] args )
{
Scanner mati = new Scanner(System.in);
System.out.println("This program adds up or substracts two numbers");
System.out.println("Enter an operator");
String letter = mati.next(); //WAITS FOR THE PHRASE ADD OR SUBSTRACT
System.out.println("Enter your first number");
int userNumberone = mati.nextInt(); // Get's first Number
System.out.println("Enter your second number");
int userNumbertwo = mati.nextInt(); //Get's Following Number
if(letter == "add") {
int result = userNumberone + userNumbertwo;
System.out.println(result);
} else if(letter == "substract") {
int result1 = userNumberone - userNumbertwo; //If statement to add or substract.
System.out.println(result1);
}
}
}
You should use letter.equals("add") instead of letters == "add". This is explained here: How do I compare strings in Java?

Categories

Resources