Exception in thread "main" NumberFormatException - java

Exception in thread "main" java.lang.NumberFormatException: For input string: "1001"
I dont understand why this code throws exception.
1001 elma 87 --> This is the text file and I'm sure this is a number.
public class Food {
public String[][] foodArray = new String[1000][100];
public int sayac = 0;
public void readText() {
try (Scanner sc = new Scanner(new BufferedReader(new FileReader("food.txt")))) {
while (sc.hasNextLine()) {
String bilgiler = sc.nextLine().trim();
foodArray[sayac] = bilgiler.split("\t");
System.out.println(Integer.parseInt(foodArray[sayac][0]));
sayac++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001"
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 Food.readText(Food.java:13)
at Main.main(Main.java:11)

The only problem that I can see that in the file the character that is separating the words is not a tab (\t) character, but maybe just spaces. That's why it is not able to split the line correctly. Can you show us what the exact stack trace is?

Delimiting character is not tab(\t) which is why the line is not getting split in different parts and whole line is stored at 0th index of the array. And when you use parseInt it tries to parse the whole line which is 1001 elma 87
I would suggest using bilgiler.split(" ") which will take care of single or multiple spaces used as delimiter.

your file line separator might not be tabs, i advise you to print the split array and use bilgiler.split("\\s+"); to split all the spaces between words

Related

Java Number Exception at string input from buffereader

import java.util.*;
import java.io.*;
import java.lang.*;
class Ex
{
public static void main (String[] args) throws IOException
{
BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
int a,b,n,c;
n=Integer.parseInt(br.readLine());
for(int i=1;i<=n;i++)
{
try
{
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
try
{
c=a/b;
System.out.println(c);
}
catch (ArithmeticException e)
{
System.out.println(e);
}
}
catch (InputMismatchException m)
{
System.out.println(m);
}
}
}
}
The above mentioned is my Code which I'm trying to run
and below is the input_file.txt
4
10
3
10
Hello
10
2
23.323
0.0
and this is the error which I get.
Exception in thread "main" java.lang.NumberFormatException: For input string: "4 "
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 Ex.main(Ex.java:11)
java.lang.NumberFormatException: For input string: "4 "
As you can see from the error message above the String you are trying to parse as a number has a space at the end which will cause the parsing to fail.
To get rid of leading and trailing spaces you can use the trim() method on Strings:
a=Integer.parseInt(br.readLine().trim());
I think you have entered the number 4 with space. Please check your input.
For input string: "4 "
To avoid it you can add trim function as below
Integer.parseInt(br.readLine().trim());

Exception in thread "main" java.lang.NumberFormatException: For input string: "1"

So I am reading in a CSV file which works fine if everything is a string. But when i try and parse Integers out of the file it no longer will work.
Scanner scanner = new Scanner(new File("top250.csv"));
scanner.useDelimiter(",");
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
String[] parts = line.split(",");
String rank = parts[0].trim();
System.out.println(rank);
int real_rank = Integer.parseInt(rank);
}
Output:
1, The Shawshank Redemption ,9.2,1994
1
Exception in thread "main" java.lang.NumberFormatException: For input string: "1"
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 movieranker.MovieRanker.createData(MovieRanker.java:45)
at movieranker.MovieRanker.main(MovieRanker.java:25)
java.lang.NumberFormatException indicates that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
This exception occurs because in the case that only a number is inputed, the actual string produced may have some invisible charachters and not "1". Thus, the format is incorrect. A simple fix would be:
Line changed from:
int real_rank = Integer.parseInt(rank);
to:
rank = rank.replaceAll("[^0-9]+", "")
int real_rank = Integer.parseInt(rank); //remove everything non-digit from your input, including \n symbols
Hi i think because your data file contains an UTF-8 BOM.
You have three alternatives:
edit your source data file to remove the BOM, or you can add some code to deal with the BOM. For the first option use Notepad++ and remove the BOM.
or use a Libarie which can handle it .. i like http://www.univocity.com/pages/about-parsers

java string to int not doing anything

I have a .txt file which houses data as seen below. What I want to do is read from the file line by line then convert it to an int and display the result to screen.
The first system out line works fine, no problems their. The second however doesn't even print to screen. I guess theirs a issue with the string converting to int?
try (BufferedReader br = new BufferedReader(new FileReader("f.txt")))
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line); //does show
int change2Int = Integer.parseInt(line);
System.out.println(change2Int); //doesnt show
mp.getDataForDisplay(line);
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
FIle:
0
1
4
2
5
The error it produces is a number format exception error.
java.lang.NumberFormatException: For input string: "0 "
The NumberFormatException that you're getting says what the problem is. Your input file also has some trailing whitespace characters in it, which is causing the parse to fail.
A simple way to prevent leading/trailing whitespace from tripping up your parse is to trim() your string before you attempt to parse it, like:
int change2Int = Integer.parseInt(line.trim());
As a general principle, it's a good idea to be permissive about what your program accepts as input, so that it can't be derailed by things like misplaced 'space' characters and other common human errors.
Your input string is "0 " which means there's a space. Use trim() before parsing. trim() is used to remove whitespace such as spaces.
eg:
int change2Int = Integer.parseInt(line.trim());

Extract alphabets with white-spaces from a given text file without having sentinel in the file

I have 2 text files:
1 Extract_tweet.txt - Format of the file is user_id tweet_id tweet_text
12163922 5407952300 I think I just discovered the hour when the office thermostat changes. And it ain't a good time to be at work...brrrr 2009-11-03 19:22:54
2 locations.txt - Relevance in below data is the 3rd Column, which acts like the search string
asciiname: name of geographical point in plain ascii characters, varchar(200)
4045431 Point Poker Point Poker 52.89508 173.29911 T CAPE US AK 016 0 9 America/Adak 2013-10-26
I want to extract some data from these files. Data typically has to be only a-z,A-Z and any whitespace. I was earlier thinking of tokenizing the string. However, with no sentinal given, I have thought of using regular expressions instead. PFB the code snippet of extracting 27 characters i.e. a-Z or A-Z or any whitespace. I want to extract only the text in lower case i.e. if there is any character in upper case, it should get converted to lower case.
I will open file 1 - Extract_tweet.txt and take complete text as a single string. I am then trying to replace each non alphabetic character with null.
public void readfromFile() throws FileNotFoundException
{
Scanner inputStream;
String source=null;
FileInputStream file = new FileInputStream("Extract_tweet.txt");
inputStream = new Scanner(file);
while(inputStream.hasNextLine()) //Read from file till the last line of the file.
{
source = inputStream.nextLine();
System.out.println(source);
replaceAll(source);
}
inputStream.close();
}
public String replaceAll(String source)
{
String regex = "[A-Z]*"+"["+source.toLowerCase()+"|"+"[a-z]*"+"[\\s]";
source = source.replaceAll(regex, "");
System.out.println(source);
return source;
}
public static void main(String[] args) {
StringProcessing sp = new StringProcessing();
try {
sp.readfromFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get below eerror once I run this code.
60730027 6320951896 #thediscovietnam coo. thanks. just dropped you a line. 2009-12-03 18:41:07
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal character range near index 88
[A-Z]*[60730027 6320951896 #thediscovietnam coo. thanks. just dropped you a line. 2009-12-03 18:41:07|[a-z]*[\s]
I have made some changes. However, i want to change upper case to lower case and also replace all alphanumeric values with null.
Expand your method:
public String replaceAll(String source) throws FileNotFoundException {
String regex = "[A-Z]* |[a-z]*\\s";
source = source.replaceAll(regex, "")
.replaceAll("\\d", "")
.toLowerCase();
System.out.println(source);
writetoFile(source);
return source;
}
Please change the line like that
String regex = "[A-Z]* |"+"[a-z]*"+"[\\s]";
It will work fine.

Java Scanner class reads one line and then stops

I have this problem with a method using the Scanner class. I am reading my text file with Scanner and then parse the int into an array.
public static void readItems()
{
try
{
File file = new File(System.getProperty("user.home") + "./SsGame/item.dat");
Scanner scanner = new Scanner(file);
int line = 0;
while (scanner.hasNextLine())
{
String text = scanner.nextLine();
text = text.replaceAll("\\W", "");
System.out.println(text.trim());
PlayerInstance.playerItems[line] = Integer.parseInt(text);
line++;
}
scanner.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (NumberFormatException e2)
{
e2.printStackTrace();
}
}
Heres the item.txt file:
1
1
2
3
4
I run the code and I get the following output:
1
I have tried using scanner.hasNextInt() and scaner.nextInt(); for this but then it won't print anything at all.
If I remove the parseInt part then the file will finish reading and all the numbers will be printed. Any ideas?
This the exception thrown:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at game.player.ReadPlayer.readItems(ReadPlayer.java:56)
at game.player.ReadPlayer.read(ReadPlayer.java:11)
at game.Frame.<init>(Frame.java:32)
at game.Frame.main(Frame.java:54)
I'm guessing Integer.ParseInt() is throwing an NumberFormatException because your line still contains the \n.
If you call Integer.ParseInt(text.trim()) instead, it may fix it.
If you did your Exception handling properly, we would have a better idea.
This is because, you have a NumberFormatException, while parsing integer.
Add in catch section something like this
System.out.println(e.getCause());
And see, that you have an exception, that's why this code prints only first digit.
You need to be careful when you use the Scanner.
If you are reading more data, with Scaner like input.nextInt(); then it will read only one int. The carriage return isn't consumed by nextInt. One solution is that add input.nextLine(); so that it moves to the next line.
Other Solution is, which I prefer is to use BufferedReader;
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String tempStr = bufferRead.readLine();
// Do some operation on tempStr
Hope this helps.

Categories

Resources