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(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at MainProgram.main(MainProgram.java:29)
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:
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.
Use a file tool to examine the file as bytes. (On UNIX / Linux / MacOSX, use the od command.)
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 ...
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.
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;
}
If you are sure you are reading an integer, you can use seconds.trim() to trim any spaces and parse it.
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.
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);
Your string can be empty or you string may contain space. So use trim & then parse.
Related
I'm doing a java project on codeZinger where I need to take in a character value from the scanner and print the ASCII value. So far the code I have works for everything besides the "/n" character. In that case, codezinger returns the error "Exception in thread "main" java.lang.NullPointerException scanner".
I have attached my code below, I've tried everything and it won't work. I'm new to java from c++.
I tried even manually testing for /n using an if statement and that didn't work
public class Solution {
public static void main(String[] args) {
//creating input stream
Scanner input = new Scanner(System.in);
// allows character input from input stream
char charIn = input.findInLine(".").charAt(0);
if(input.equals("\\n"))
{
System.out.print("10");
}
// casts character to type int to get ascii value
int intVal = (int)charIn;
System.out.print(intVal);
}
}
input.equals() method in java never takes its parameter in apostrophe.
Please go through this once :
https://www.jquery-az.com/learn-java-equals-method-5-examples/
Moreover /n doesn't exist in java. If you have to print a line(Give a break) then you have to use System.out.println() , simply, and it will be printed in next line.
Also go through this for printing ASCII value
https://www.javatpoint.com/how-to-print-ascii-value-in-java
int code;
while ((code = System.in.read()) != -1) {
System.out.format("0x%02X ", code);
}
I have this code:
public static void main(String[] args) {
List<Valtozas> lista = new ArrayList<Valtozas>();
try {
File fajl = new File("c://data//uzemanyag.txt");
Scanner szkenner = new Scanner(fajl, "UTF8");
while (szkenner.hasNext()) {
String sor = szkenner.nextLine();
String [] darabok = sor.split(";");
String szoveg = darabok[0];
Valtozas valtozas = new Valtozas(Integer.valueOf(darabok[0]), Integer.valueOf(darabok[1]), Integer.valueOf(darabok[2]));
lista.add(valtozas);
}
}
catch (Exception e) {
}
//3.FELADAT
System.out.println("3.Feladat: Változások száma: "+lista.size());
}
}
Here I want to convert the String to int, but I cant. I tried the Integer.Valueof(darabok[0]), but its not working. And nothing is happening, so the code is build, but quit from the while.
Based on the source code you have shown us, the problem is that there is a format mismatch between the input file and the program you are trying to read.
The program reads the file a line at a time, and splits it into fields using a single semicolon (with no whitespace!) as the file separator. Then it tries to parse the first three fields of each split line as integers.
For this to work the following must be true:
Every line must have at least three fields. (Otherwise you will get a ArrayIndexOutOfBound exception.)
The three fields must match the following regex: -?[0-9]+ i.e. an optional minus signed followed by one or more decimal digits.
The resulting number must be between Integer.MIN_VALUE and Integer.MAX_VALUE.
Elaborating on the above:
Leading and trailing whitespace characters are not allowed.
Embedded decimals markers and grouping characters are not allowed.
Scientific notation is not allowed.
Numbers that are too large or too small are not allowed.
Note that if any of the above constraints is not met, then the runtime system will throw an exception. Unfortunately, you surround your code with this:
try {
...
}
catch (Exception e) {
}
That basically ignores all exceptions by catching them and doing nothing in the handler block. You are saying to Java "if anything goes wrong, don't tell me about it!". So, naturally, Java doesn't tell you what is going wrong.
DON'T EVER DO THIS. This is called exception squashing, and it is a really bad idea1.
There are two ways to address this:
Print or log the stacktrace; e.g.
catch (Exception e) {
e.printStackTrace();
}
Remove the try / catch, and add throws IOException to the signature of your main method.
(You can't just remove the try / catch because new Scanner(fajl, "UTF8") throws IOException. That's a checked exception so must be handled or declared in the method signature.)
Once you have dealt with the exception properly you will get an exception message and stacktrace that tells you what is actually going wrong. Read it, understand it, and fix your program.
1 - It is like taping over the "annoying" red light that indicates that your car's oil level is low!
I am writing a code to find out the number of sentences in a file.
My code is as :
try{
int count =0;
FileInputStream f1i = new FileInputStream(s);
Scanner sc = new Scanner(f1i);
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf(".")!= -1)
count++;
sc.nextLine();
}
System.out.println("The number of sentences are :"+count);
}
catch(Exception e) {
System.out.println(e);
}
I guess my logic is right to check for the number of periods. I wrote the above code which i think is right but it displays a javautilNoElementfound : No line foundexception . I tried some other logics but this one was the best understandable. But i am stuck here. I used google on that exception and it says that it is thrown when we iterate over something that has no element.But my file contains data. Is there some way this exception could have made way?? Or is there some other error? Hints are appreciated ! Thanks
You are calling sc.nextLine() two times inside the while loop that is why the error occurs.
Also your logic doesn't account for cases when there are 2 sentences on the same line.
You can try something like this:
int sentencesPerLine = g.split(".").length;
The loop should be:
while(sc.hasNextLine()){
String g = sc.nextLine();
if(g.indexOf('.')!= -1){//check if the line contains a '.' character
count += g.split("\\.").length; // split the line into an array of Strings using '.' as a delimiter
}
}
In the split(...) method I'm using "\\." instead of "." because . is a regex element and needs to be escaped.
I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
My code is very simple (I'm a beginner):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
I have tried several things:
1) To convert row1 to a String and and say:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String and an int).
My errors usually say: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
Many thanks in advance!
You can try something like this
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String type and the try to convert that String input into integer using Integer.parseInt().
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException which will tell you that its not an Integer. So you can go ahead and check it for e if it is, do whatever you want as per your requirement.
You can't use nextInt() if you aren't sure that you will have a number coming in. Also, you can't parse e as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
That means, your code should look like:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
How to check if a String is numeric in Java
1) you should say Integer.parseInt() instead of Integer.ParseInt()
2) if you pass "e" to Integer.parseInt() you'll get java.lang.NumberFormatException
3) get your input as a string this way (cause it's safer)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
I have tried several things ....
Attempting to solve this problem by "trying things" is the wrong approach.
The correct approach is to understand what is going on, and then modify your solution to take this into account.
The problem you have is that you have a line of input that could be either a number or the special value e which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
When you attempt to either:
call Scanner.nextInt() when the next input is not an integer, OR
call Integer.parseInt(...) on a String that is not an integer
you will get an exception. So what do you do?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
call Scanner.hasInt() to see if the next token is an integer before calling nextInt(), or
test for the "e" case before you attempt to convert the String to an integer.
Another way to deal with this is to catch the exception. For example, you could do something like this:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
I said there were other cases. They are:
The user types something that is neither a number of your special e character. It could be anything. An empty line, hi mum ...
The user types the "end of file" character; e.g. CTRL-D on Linux or CTRL-Z on windows.
If you want your program to be robust you need to deal with these cases too.
Try this:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
You can't convert a string into integer, use char ASCII codes instead.
I try to convert int String to int
int port = Integer.parseInt(tokens[2]);
tokens[2] contain a String "12777"
But I got this error
Exception in thread "Thread-2019" java.lang.NumberFormatException: For
input string:
"12777"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at inet.ChildServer.hopen(ChildServer.java:88)
at inet.ChildServer.run(ChildServer.java:51)
Edit: Sorry the characters are invisible in eclipse, I don't Understand what is this.
I have a String in this form
command1|Destination-IP|DestinationPort
and I just splot it
String[] tokens = sentence.split( "[|]" );
can you trim the string before pass to Integer.parseInt(tokens[2]); it may contain blank spaces.
As have guys already mentioned your string does not contain 12777 as you think. It contains 12777 and then a lot of garbage that prevents parsing of your string to int. Debug your code to understand what is the source of this garbage. Take a look on code that assigns value to tokens[2].
If you have problems there post the code that assigns value to tokens[2].
Good luck.
EDIT
OK, you have posted yet another part of your code. But the problems seems to be before this point. Take a look on code that assigns value to sentence.
BTW: you can see everything in eclipse. Expand the string and see the character array stored into the string.
Be careful you can have errors after you
String x = "123";
Integer.parseInt(x);
do
String x = "jonas";
try{
Integer.parseInt(x.trim());
catch(NumberFormatException e){
//do something creative with the error
}