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());
Related
I was wondering if anyone could help solve this NoSuchElements exception in my program which scans a text very large text and then is added to the ArrayList.
I have tried re-arranging the order of the code to see if that would fix it but now I don't know how to fix it.
Exception itself:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at mainTest.main(mainTest.java:11)
mainTest class:
import java.io.*;
import java.util.*;
public class mainTest {
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String> bigBoi = new ArrayList<>(500000);
Scanner scan1 = new Scanner(new File("LargeDataSet.txt"));
while (scan1.hasNextLine()) {
scan1.next();
String data = scan1.next() + " " + scan1.next();
bigBoi.add(data);
}
ArrayList<String> successful = new ArrayList<>(500000);
}
}
The unit of a .txt file :
https://drive.google.com/file/d/1MWfMKMhSvuopOt9WwquABgYBTt0M4eLA/view?usp=sharing
(sorry for needing you to download it from a google drive, the file is so long I probably would've been reported or something if I had pasted 500,000 lines)
Please check with scan1.hasNext() instead of scan1.hasNextLine():
while (scan1.hasNext()) {
scan1.next();
String data = scan1.next() + " " + scan1.next();
bigBoi.add(data);
}
There is an empty line at the end of LargeDataSet.txt which is valid for scan1.hasNextLine() check, but the scan1.next() throws NoSuchElementException as there's nothing to read.
Changing validation to scan1.hasNext() as suggested in the accepted answer, solves that problem, but the program could still crash if there are less than 3 entries on any line and accepts lines with more than 3 entries.
A better practice is to validate all externally supplied data:
while (scan1.hasNextLine()) {
String line = scan1.nextLine();
String[] tokens = line.split("\\s+"); //split by space(s)
if(tokens.length != 3) { //expect exactly 3 elements on each line
throw new IllegalArgumentException("Invalid line: " + line);
}
bigBoi.add(tokens[1] + " " + tokens[2]);
}
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
For the following program i am expecting output as
Enter any Value : 3
You Entered 3
But i am not getting output, instead in output java is expecting some input without displaying "Enter any Value". If i enter any value then it will display the output as
3
Enter any value : You Entered 3.
Here is my code:
import java.io.*;
// System.in is an object of InputStream - byte stream
class ConsoleInputDemo{
public static void main(String args[]) throws IOException{
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in)); // This will convert byte stream to character stream
PrintWriter consoleOutput = new PrintWriter(System.out);
consoleOutput.println("Enter any Value : ");
int c= consoleInput.read();
consoleOutput.write("You entered " + c);
consoleInput.close();
consoleOutput.close();
}
}
consoleOutput.println didn't print anything until it close(). Use
System.out.println("Enter any Value : ")
instead of
consoleOutput.println("Enter any Value : ");
Or close consoleOuput if you want to view the text.
consoleOutput.print("Enter any Value : ");
consoleOutput.close();
System.out.print("Enter any Value : ");
try {
int c=Integer.parseInt(new BufferedReader((new InputStreamReader(System.in))).readLine());
System.out.println("Entered Character: " +c);
} catch (IOException e) {
e.printStackTrace();
}
This simple code might help you achieve your requirement.read() will just give you ascii value so I preffer using readline() method to get actual values. Offcourse it will return string so just parse it to get integer.
This question already has answers here:
System.in.read() method
(6 answers)
Closed 8 years ago.
I use this official example to receive input from the user and then print it:
import java.io.IOException;
public class MainClass {
public static void main(String[] args) {
int inChar;
System.out.println("Enter a Character:");
try {
inChar = System.in.read();
System.out.print("You entered ");
System.out.println(inChar);
}
catch (IOException e){
System.out.println("Error reading from user");
}
}
}
The problem, It always returns incorrect values. For example, When enter 10 it returns 49 while I expect to return 10!
What is the reason for this issue and how could I solve it.
This returns the int value of a character, if you want to print the character cast it to char:
System.out.println((char) inChar);
This will only print the value of the first character that was input because System.in.read() only reads the first byte.
To read a whole line you could use a Scanner:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Write something:");
// read input
String line = scanner.nextLine();
System.out.print("You entered ");
System.out.println(line);
}
}
Try this snippet.
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader brInput = new BufferedReader(isr);
String strInput = brInput.readLine();
System.out.println("You wrote "+strInput);
System.in.read reads only first byte from input stream
So if you enter
123
the first character is 1.So its corresponding ASCII is 49
If we enter
254
the first character is 2.So its corresponding ASCII is 50
Edit:This is explained also here
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.