Java ошибка integer parseint

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class MainProgram {
   public static void main(String[] args ) throws IOException{
    String seconds = " ";

     Scanner sc2 = null;
        try {
            sc2 = new Scanner(new File("/Users/mohammadmuntasir/Downloads/customersfile.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();  
        }

        boolean first = true;
        while (sc2.hasNextLine()) {
                Scanner s2 = new Scanner(sc2.nextLine());    
            while (s2.hasNext()) {
                String s = s2.next();
                if (first == true){
                    seconds = s;
                    first = false;
                }

            }
        }
        System.out.println(Integer.parseInt(seconds)); // causes ERROR?

     }
 }

I am trying to read a number from a text file which is in the first line by itself. I made an integer called seconds that will take in the first number and will be parsed into an integer. But I always get a numbers exception error and that I can’t parse it. When I display s as a string, it displays a number without spaces next to it. Can anyone explain why this happens?

Here is the stacktrace:

Exception in thread "main" java.lang.NumberFormatException: For input string: "300" 
  at java.lang.NumberFormatException.forInputString(NumberFormatE‌xception.java:65) 
  at java.lang.Integer.parseInt(Integer.java:580) 
  at java.lang.Integer.parseInt(Integer.java:615) 
  at MainProgram.main(MainProgram.java:29)

Stephen C's user avatar

Stephen C

694k94 gold badges798 silver badges1210 bronze badges

asked Apr 21, 2017 at 6:37

Dank memer's user avatar

15

If the exception message is really this:

 java.lang.NumberFormatException: For input string: "300"

then we are starting to get into really obscure causes.

  • It could be a problem with homoglyphs; i.e. Unicode characters that look like one character but are actually different characters.

  • It could be a non-printing character. For example an ASCII NUL … or a Unicode BOM (Byte Order Marker) character.

I can think of three ways to diagnose this:

  1. Run your code in a debugger and set a breakpoint on the parseInt method. Then look at the String object that you are trying to parse, checking its length (say N) and the first N char values in the character array.

  2. Use a file tool to examine the file as bytes. (On UNIX / Linux / MacOSX, use the od command.)

  3. Add some code to get the string as an array of characters. For each array entry, cast the char to an int and print the resulting number.

All three ways should tell you exactly what the characters in the string are, and that should explain why parseInt thinks they are wrong.


Another possibility is that you copied the exception message incorrectly. The stacktrace was a bit mangled by the time you got it into the Question …

answered Apr 21, 2017 at 7:05

Stephen C's user avatar

Stephen CStephen C

694k94 gold badges798 silver badges1210 bronze badges

Have a look at your input file with a hex-editor. It might start with some «strange» hex codes called Byte Order Markers. This would explain why the Exception is so misleading becaus BOMs won’t be shown on the console.

answered Apr 21, 2017 at 12:45

Farino's user avatar

can you try this, I had the same probleme , Integer.ParseInt(String) didn’t work for me, I added .trim() and it works perfectly:

int id_of_command;
        try {
             id_of_command = Integer.parseInt(id_of_Commands_str.trim());
            }
            catch (NumberFormatException e)
            {
             id_of_command = 0;
            }

answered Dec 23, 2019 at 20:03

Hamza's user avatar

HamzaHamza

131 bronze badge

If you are sure you are reading an integer, you can use seconds.trim() to trim any spaces and parse it.

answered Apr 21, 2017 at 6:43

OTM's user avatar

OTMOTM

6565 silver badges8 bronze badges

4

If you are trying to parse space then it would cause an issue. Please check what value of seconds you are trying to parse.

Exception in thread "main" java.lang.NumberFormatException: For input string: " "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:569)
    at java.lang.Integer.parseInt(Integer.java:615)
    at HelloWorld.main(HelloWorld.java:22)

Additionally try catching the exception and printing the value which is causing it. Something like this:

try{
      System.out.println(Integer.parseInt(seconds));
    }
    catch(Exception e){
      System.out.println("String value: '" + seconds + "'");
    }

Can you update the question with stack-trace. Not sure what are the contents in your file.

answered Apr 21, 2017 at 6:42

Rupesh's user avatar

RupeshRupesh

2,6171 gold badge28 silver badges42 bronze badges

8

Is it possible to append your code with something like this and put out your answer :

    StringBuilder sb = new StringBuilder();
    for (char c : seconds.toCharArray())
    {
        sb.append((int)c).append(",");
    }
    System.out.println(sb);

answered Apr 21, 2017 at 8:06

PankajT's user avatar

0

Your string can be empty or you string may contain space. So use trim & then parse.

answered Apr 21, 2017 at 6:45

Rahul Rabhadiya's user avatar

I feel like I must be missing something simple, but I am getting a NumberFormatException on the following code:

System.out.println(Integer.parseInt("howareyou",35))

Ideone

It can convert the String yellow from base 35, I don’t understand why I would get a NumberFormatException on this String.

asked Nov 26, 2013 at 14:32

Danny's user avatar

2

Because the result will get greater than Integer.MAX_VALUE

Try this

System.out.println(Integer.parseInt("yellow", 35));
System.out.println(Long.parseLong("howareyou", 35));

and for

Long.parseLong("abcdefghijklmno",25)

you need BigInteger

Try this and you will see why

System.out.println(Long.MAX_VALUE);
System.out.println(new BigInteger("abcdefghijklmno",25));

answered Nov 26, 2013 at 14:38

René Link's user avatar

René LinkRené Link

47.4k13 gold badges107 silver badges137 bronze badges

2

Could it be that the number is > Integer.MAX_VALUE? If I try your code with Long instead, it works.

answered Nov 26, 2013 at 14:37

Blub's user avatar

BlubBlub

3,7521 gold badge13 silver badges24 bronze badges

The number is getting bigger than Integer.MAX_VALUE

Try this:

System.out.println(Integer.parseInt("yellow", 35));
System.out.println(Long.parseLong("howareyou", 35));

As seen in René Link comments you are looking for something like this using a BigInteger:

BigInteger big=new BigInteger("abcdefghijklmno", 25);

Something like this:

System.out.println(Long.MAX_VALUE);
System.out.println(new BigInteger("abcdefghijklmno",25));

Community's user avatar

answered Nov 26, 2013 at 14:38

Rahul Tripathi's user avatar

Rahul TripathiRahul Tripathi

167k31 gold badges277 silver badges331 bronze badges

From the JavaDocs:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero. FALSE: «howareyou» is not null and over 0 length
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. FALSE: 35 is in range [2,36]
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ (‘u002D’) or plus sign ‘+’ (‘u002B’) provided that the string is longer than length 1. FALSE: all characters of «howareyou» are in radix range [0,’y’]
  • ==> The value represented by the string is not a value of type int. TRUE: The reason for the exception. The value is too large for an int.

Either Long or BigInteger should be used

answered Nov 26, 2013 at 14:35

Glenn Teitelbaum's user avatar

Glenn TeitelbaumGlenn Teitelbaum

10k3 gold badges36 silver badges80 bronze badges

3

As you can see, you’re running out of space in your Integer. By swapping it out for a Long, you get the desired result. Here is the IDEOne Link to the working code.

Code

System.out.println(Integer.parseInt("YELLOW",35));
System.out.println(Long.parseLong("HOWAREYOU",35));

answered Nov 26, 2013 at 14:38

christopher's user avatar

christopherchristopher

26.7k5 gold badges55 silver badges89 bronze badges

The previous answers of parseLong would be correct, but sometime that is also not large enough so the other option would to use a BigInteger.

Long.parseLong("howareyou", 35)
new BigInteger("howareyou", 35)

answered Nov 26, 2013 at 14:45

Joe's user avatar

JoeJoe

6411 gold badge8 silver badges15 bronze badges

The number produced is too large for a Java Integer, use a Long.

Nathan Arthur's user avatar

answered Nov 26, 2013 at 14:39

Bob Flannigon's user avatar

Рассмотрим метод Integer.parseInt(String), который принимает число в форме строки (например, "94", "865") и возвращает его целочисленное представление (например, 94, 865).

Очевидно, что Integer.parseInt("650") == 650, а Integer.parseInt("-1") == -1. Но чему равно выражение Integer.parseInt("surprise")? Нулю? Это было бы ужасно, такую ошибку невозможно было бы отловить. Сумме числовых значений всех букв? Ещё хуже.

Метод parseInt не может вернуть числовое значение строки «surprise», в десятичной системе есть только цифры 0..9, эта задача невыполнима. Метод выбрасывает исключение.

{«name»:»main»,»subCalls»:[{«name»:»parseInt(«surprise»)»,»subCalls»:[{«name»:»parseInt(«surprise», 10)»,»subCalls»:[{«name»:»NumberFormatException.forInputString(«surprise»)»,»subCalls»:[]},{«type»:»crash»,»name»:»throw»,»subCalls»:[]}]}]}]}

Выброс исключения прерывает выполнение метода, если его никто не ловит. В примере оно выбрасывается из метода parseInt(String s, int radix), затем прерывает метод parseInt(String s), затем — main. В консоль будет выведена трассировка стека вызовов (stack trace) — это список методов, которые были вызваны, c именами файлов и номерами строк, в которых это произошло.

Exception in thread "main" java.lang.NumberFormatException: For input string: "surprise"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at online.javanese.basics.oop.exceptions.ParseInt.main(ParseInt.java:6)

Если в данном контексте вы не можете ничего сделать с исключением — не ловите его, пусть программа падает. Если же вы можете как-то восстановиться после исключения, можно его поймать:

package online.javanese.basics.oop.exceptions;

public class ParseInt {

    public static void main(String[] args) {
        try {
            Integer.parseInt("surprise");
        } catch (NumberFormatException e) {
            System.out.println("Так себе число.");
        }
    }
}

В блоке try выполняются действия, которые могут привести к исключению. Если исключение не будет выброшено, блок catch будет проигнорирован. Если же любой код, выполняющийся внутри try, выбрасывает исключение подходящего типа (в данном случае — NumberFormatException), управление передаётся
блоку catch. Если выброшено исключение неподходящего класса, оно не попадает в catch.

Непроверяемые исключения

Иерархия исключений, наследующих RuntimeException, предполагает, что ошибка в нахдится коде, т. е. в ней виновен программист. Следовательно, восстановить выполнение программы не удастся, нужно исправлять ошибку в коде, поэтому и ловить такие исключения не нужно. Вот основные представители:

int[] zeroSizeArray = new int[0];
int firstItem = zeroSizeArray[0]; // ArrayIndexOutOfBoundsException
zeroSizeArray[0] = 200700; // ArrayIndexOutOfBoundsException

int lol = 10 / 0; // ArithmeticException

int numberFromString = Integer.parseInt("not a number"); // NumberFormatException

Проверяемые исключения

Проверяемые исключения (checked exceptions) — такие исключения, которые необходимо ловить. Их возникновение — это штатная ситуация. Например, посчитаем отпечаток пароля с помощью алгоритма SHA-512 и выведем его как массив байт. Это удастся сделать, только если на данном компьютере доступен этот алгоритм.

План А: перебрасываем

try {
    MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
    System.out.println(Arrays.toString(sha512.digest("password".getBytes())));
} catch (NoSuchAlgorithmException e) {
    // если SHA-512 не поддерживается,
    // выполнить задачу невозможно — падаем,
    // бросая непроверяемое исключение,
    // в качестве причины которого указываем пойманное:
    throw new RuntimeException(e);
}

Успех:

[-79, 9, -13, -69, -68, 36, 78, -72, 36, 65, -111, 126, -48, 109, 97, -117, -112, 8, -35, 9, -77, -66, -3, 27, 94, 7, 57, 76, 112, 106, -117, -71, -128, -79, -41, 120, 94, 89, 118, -20, 4, -101, 70, -33, 95, 19, 38, -81, 90, 46, -90, -47, 3, -3, 7, -55, 83, -123, -1, -85, 12, -84, -68, -122]

Неудача, алгоритм недоступен:

Exception in thread "main" java.lang.RuntimeException: java.security.NoSuchAlgorithmException: SHA-512 MessageDigest not available
	at online.javanese.basics.oop.exceptions.Sha512.main(Sha512.java:14)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.security.NoSuchAlgorithmException: SHA-512 MessageDigest not available
	at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
	at java.security.Security.getImpl(Security.java:695)
	at java.security.MessageDigest.getInstance(MessageDigest.java:167)
	at online.javanese.basics.oop.exceptions.Sha512.main(Sha512.java:11)
	... 5 more

План Б: восстанавливаемся

try {
    MessageDigest sha512 = MessageDigest.getInstance("SHA-512");
    System.out.println(Arrays.toString(sha512.digest("password".getBytes())));
} catch (NoSuchAlgorithmException e) {
    System.out.println("SHA-512 недоступен. ¯\_(ツ)_/¯");
}

Успех выглядит так же. Неудача:

SHA-512 недоступен. ¯_(ツ)_/¯

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float). For example, this exception occurs if a string is attempted to be parsed to an integer but the string contains a boolean value.

Since the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. It can be handled in code using a try-catch block.

What Causes NumberFormatException

There can be various cases related to improper string format for conversion to numeric values. Some of them are:

Null input string

Integer.parseInt(null);

Empty input string

Integer.parseInt("");

Input string with leading/trailing whitespaces

Integer myInt = new Integer(" 123  ");

Input string with inappropriate symbols

Float.parseFloat("1,234");

Input string with non-numeric data

Integer.parseInt("Twenty Two");

Alphanumeric input string

Integer.parseInt("Twenty 2");

Input string exceeding the range of the target data type

Integer.parseInt("12345678901");

Mismatch of data type between input string and the target data type

Integer.parseInt("12.34");

NumberFormatException Example

Here is an example of a NumberFormatException thrown when attempting to convert an alphanumeric string to an integer:

public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int a = Integer.parseInt("1a");
        System.out.println(a);
    }
}

In this example, a string containing both numbers and characters is attempted to be parsed to an integer, leading to a NumberFormatException:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1a"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:3)

Such operations should be avoided where possible by paying attention to detail and making sure strings attempted to be parsed to numeric values are appropriate and legal.

How to Handle NumberFormatException

The NumberFormatException is an exception in Java, and therefore can be handled using try-catch blocks using the following steps:

  • Surround the statements that can throw an NumberFormatException in try-catch blocks
  • Catch the NumberFormatException
  • Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message.

The code in the earlier example can be updated with the above steps:

public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        try {
            int a = Integer.parseInt("1a");
            System.out.println(a);
        } catch (NumberFormatException nfe) {
            System.out.println("NumberFormat Exception: invalid input string");
        }
        System.out.println("Continuing execution...");
    }
}

Surrounding the code in try-catch blocks like the above allows the program to continue execution after the exception is encountered:

NumberFormat Exception: invalid input string
Continuing execution...

Track, Analyze and Manage Errors with Rollbar

Rollbar in action

Finding exceptions in your Java code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring, tracking and triaging, making fixing Java errors and exceptions easier than ever. Sign Up Today!

Выводит ошибку:

java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at com.javarush.task.task05.task0532.Solution.main(Solution.java:20)
at sun.reflect.NativeMethodA

package com.javarush.task.task05.task0532;

import java.io.*;

/*
Задача по алгоритмам
*/

public class Solution {
public static void main(String[] args) throws Exception {

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

int N = Integer.parseInt(reader.readLine());

if (N > 0) {
int maximum = Integer.parseInt(reader.readLine());

for (int i = 0; i <= N-1; i++) {
int c = Integer.parseInt(reader.readLine());
if (c > maximum) {
maximum = c;
}
}
System.out.println(maximum);
}
else
System.out.println(«Неверное значение»);
}
}

Like this post? Please share to your friends:
  • Java ошибка 403
  • Java ошибка 2203
  • Java ошибка 1723 при удалении
  • Java ошибка 170
  • Java ошибка 1625