Input data: java.lang.NumberFormatException: For input string: "2 " - java

Here is my data from the text file:
21/08/12#ESE-6329#PV/5732#30
27/08/12#PEA-4567#PV/5732#3#
11/09/12#ESE-5577#Xk/8536#2
14/09/12#PNW-1235#HY/7195#2#
And this is a code form the main method:
File orderData = new File("PurchaseOrderData.txt");
Scanner dataScan = new Scanner(orderData);
while(dataScan.hasNextLine())
{
String lineData = dataScan.nextLine();
Scanner lineScan = new Scanner(lineData);
lineScan.useDelimiter("#");
String date = lineScan.next(); // line 259
String id = lineScan.next();
String code = lineScan.next();
String quantityPlus = lineScan.next();
if(!quantityPlus.contains("#"))
management.addNewPurchaseOrder(date, id, code,
Integer.parseInt(quantityPlus)); // line 267
else
{
quantityPlus = quantityPlus.replace("#", "");
management.addNewPurchaseOrder(date, id, code,
Integer.parseInt(quantityPlus));
management.startNewMonth();
}
On the first instance of
management.addNewPurchaseOrder(date, id, code, Integer.parseInt(quantityPlus));
I get this exception:
java.lang.NumberFormatException: For input string: "2 "
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 Assignment2.MainTest.main(MainTest.java:267)
If I do:
String quantityPlus = lineScan.next();
quantityPlus = quantityPlus.replace(" ", "");
I get the following:
java.util.NoSuchElementException
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Assignment2.MainTest.main(MainTest.java:259)
MainTest.java:259 - String date = lineScan.next();
I've tried to use nextInt() as well, but the result is the same. What is wrong there?
Thanks a lot!

MainTest.java:259 - String date = lineScan.next();
You should check before if the line is not empty this might be why the scanner is throwing an exception

Regarding NoSuchElementException - one of your lines ends prematurely (most likely there's no data after the last #). As you can see from specification this exception is thrown when:
#throws NoSuchElementException if no more tokens are available

Related

Why am I getting an ArrayIndexOutOfBoundsException when I try to tokenize the input from the console (Java)?

I'm trying to separate the input from the console using the split method, and then putting each of these values into separate containers, and I keep on getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1. I assume the issue is that it ignores the input after the first space, but I am clueless as to why and how to solve that.
Could someone tell me what I'm doing wrong and advise what I should do so that the text after the space is stored in my container? Thank you in advance.
Scanner s = new Scanner(System.in);
System.out.println("Input the name and phone no: ");
String text = s.next();
String[] temp = text.split(" ");
String name = temp[0];
String phoneNoTemp = temp[1];
System.out.println(name + ": name");
System.out.println(phoneNoTemp + ": phoneNoTemp");
The input I tried it with was:
Input the name and phone no:
kate 99912222
Sidenote: Yes, I did import the scanner
Try to use s.nextLine() instead of s.next() because the next() method only consumes until the next delimiter, which defaults to any whitespace.

Exception in thread "main" java.lang.NumberFormatException:For input string: on Intellij IDEA

int[] a = new int[3];
String s = e.nextLine();
String[] sa = s.split(" ");
for (int i = 0;i<sa.length;i++){
a[i]=Integer.parseInt(sa[i]);
}
I could not find any issue. Getting this error...
Exception in thread "main" java.lang.NumberFormatException: For input
string: "" at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662) at
java.base/java.lang.Integer.parseInt(Integer.java:770) at
Team.main(Team.java:23)
I think my Intellij IDEA is having some trouble. Does this error appear, if IDE does not work well?
The problem is that your string has two or more blank spaces one after the other so when you do the split(" ") it will return you empty strings between those spaces.
You have to remove the empty strings before trying to convert to integer.
You can do that using an if statement:
int j = 0;
for (int i = 0;i<sa.length;i++){
if(!sa[i].isEmpty()){
a[j]=Integer.parseInt(sa[i]);
j++;
}
}

Trying to store values from a a text file but it outputting incorrectly [duplicate]

This question already has answers here:
How do I use a delimiter with Scanner.useDelimiter in Java?
(3 answers)
Closed 5 years ago.
Here is my program currently for retrieving data from the text file which looks like this:
try {
File file = new File("dataCollection.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
String firstName = s.next();
String lastName = s.next();
String address = s.next();
String suiteNumber = s.next();
String city = s.next();
String state = s.next();
String zipCode = s.next();
String balance = s.next();
System.out.println("First Name is " + firstName);
}
s.close();
The input file looks like this:
FirstNameFXO|LastFXO|2510 Main Street|Suite 101D|City100|GA|72249|$280.80
FirstNamePNR|LastPNR|396 Main Street|Suite 100A|City102|GA|24501|$346.01
FirstNameXZU|LastXZU|2585 Main Street|Suite 107C|City101|GA|21285|$859.40
I am trying to print out just the firstName so I can use the values later for various other uses but it outputs this instead (the output is much larger, this is just the first three lines):
First Name is FirstNameFXO|LastFXO|2510
First Name is FirstNameXZU|LastXZU|2585
First Name is FirstNameGHP|LastGHP|2097
the problem that you are using method .next() which has default delimiter whitespace so it will read and return the next series of string token until a whitespace is reached.
in your case it will return:
firstname ="FirstNameFXO|LastFXO|2510";
to solve your problem instead you can use method .nextLine()
read each line then save it in variable line and substring it to get the First Name:
while(s.hasNextLine()){
String line = s.nextLine();
String firstname = line.substring(0,line.indexOf("|"));
System.out.println("First Name is " + firstName);
}

Trying to split up a string with blank space

I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]

Using a pipe character as a delimiter, but getting an invalid escape sequence error on it?

I'm not certain why I'm getting an "invalid escape sequence" error for using "\|", since it's supposed to make it just a | character? I'm attempting to read in a file, where values are separated by a | character, and for some reason it's giving me a very odd output. I have a text file:
Star Trek|Sci-fi|Sy-fy|48|is
Word Girl|Children's|PBS Kids|21|is
Firefly|Sci-fi|FOX|50|is
America's Next Top Model|Drama|CNN|51|is not
Being Human|Sci-fi|Sy-fy|48|is not
Black Mirror|Anthology|Channel 4|55|is
Grandma's House|Comedy|BBC Two|26|is
Sherlock|Crime drama|BBC One|55|is
Psych|Comedy-Drama|ION|51|is not
The Big Bang Theory|Sitcom|CBS|23|is not
I would like to go through this text file line by line, and then pass it through a TV shows class, which is as follows:
public class TVShows {
private String showName;
private String genre;
private String network;
private String favourite;
private String runningTime;
public TVShows(String showName, String genre, String network, String favourite, String runningTime){
this.genre = genre;
this.showName = showName;
this.network = network;
this.runningTime = runningTime;
this.favourite = favourite;
}
public String toString(){
return showName + ", on " + network + ", a " + genre + " show with a running time of " + runningTime + " minutes. This "
+ favourite + " a favourite.";
}
}
It's all very simple, but for some reason, when I implement it in the driver, which is here:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File("./src/TVShows.txt");
Scanner fileScanner = new Scanner(myFile);
while(fileScanner.hasNextLine())
{
TVShows myShows = new TVShows("test","test","test","test","test");
String line = fileScanner.nextLine();
System.out.println(fileScanner.nextLine());
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\|");
while(lineScanner.hasNext())
{
System.out.println(lineScanner.next());
String showName = lineScanner.next();
String genre = lineScanner.next();
String network = lineScanner.next();
String runningTime = lineScanner.next();
String favourite = lineScanner.next();
TVShows myShows1 = new TVShows(showName, genre, network, favourite, runningTime);
System.out.println(myShows1);
}
}
}
}
I get an invalid escape sequence error on "\|". Why is this? Do I just need to put another backslash in? Like "\|"? When I do this, and run the program, I get the output:
ÿþS t a r T r e k
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Program3.Driver.main(Driver.java:30)
This is line 30:
String favourite = lineScanner.next();
Thanks for any help.
you should use two backslash in java
lineScanner.useDelimiter("\\|");
You need two backslashes:
lineScanner.useDelimiter("\\|");
First one is to escape the second one from parsing in the compiler. They together make a single backslash in the string constant that is used to escape the pipe symbol in the regex engine.
This section of code
while(lineScanner.hasNext())
{
System.out.println(lineScanner.next());
String showName = lineScanner.next();
String genre = lineScanner.next();
String network = lineScanner.next();
String runningTime = lineScanner.next();
String favourite = lineScanner.next();
}
involves checking hasNext() once, then running next() six times. Therefore, if you have a number of elements not divisible by six, you will inevitably have some n<6 number of elements left, get n elements, then get an error on trying to get the n+1th element.
From your data, I assume you are supposed to have 5 elements, not 6. I'm guessing that your println is disrupting the flow by requesting an extra element. Delete it and add System.out.println(showName); somewhere after you define showName; this should fix your problem.

Categories

Resources