This question already has answers here:
What's the difference between next() and nextLine() methods from Scanner class?
(15 answers)
Closed 5 years ago.
I am trying to read a line from a text file in java. I get a java.lang.ArrayIndexOutOfBoundsException: 1 exception.
Here is my code:
try {
Scanner kb = new Scanner(new FileReader(fileName));
String line = "";
int count = 0;
while (kb.hasNext()) {
line = kb.next();
String[] temp = line.split("#");
System.out.println(temp[1]);
Wedding tempWed = new Wedding(temp[0], temp[1], temp[2], temp[3], Integer.parseInt(temp[4]));
test[count] = tempWed;
count++;
}
} catch (FileNotFoundException ex) {
}
This is the line in the textfile:
Chiquita Sanford#Magee Sosa#2016-11-05#Garden#84
I need to split by the "#", and this partly works.
Java throws the exception when I try to access the element at position 1.
I think this is because there is a space between the first name and the surname, because when I System.out.println(temp[0]) it displays "Chiquita" and not "Chiquita Sanford".
Does Java have some restriction on splitting when there are multiple words in the first array index.
You have to use the nextLine method to read the full line. next will read until the first token ("Chiquita" in your case because its followed by a space character and is interpreted as a delimiter). So change this line:
line = kb.next();
with this:
line = kb.nextLine();
You are using kb.next() that will return the next word not the next line, for this use kb.nextLine() similar issue with kb.hasNext() needs to be kb.hasNextLine()
Related
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
I have a file that looks like follows:
What I need is to read only names (first column) and output it.
while (sc.hasNext())
System.out.println(sc.next());
Another solution I tried is:
while (sc.hasNextLine())
System.out.println(sc.nextLine());
The ones that are above obviously don't work. I am stuck and don't know what to do. I was trying to google my problem but couldn't find the answer.
while(sc.hasNextLine()) {
StringBuilder toPrint = new StringBuilder();
String line = sc.nextLine();
for(int i = 0; i < line.length() && line.charAt(i) != ' '; i ++) {
toPrint.append(line.charAt(i));
}
System.out.println(toPrint.toString());
}
The reason I don't use String.split() is because that does lot's of unnecessary work, as it splits the entire string, and you only want the first word.
This question already has answers here:
Is there an equivalent method to C's scanf in Java?
(7 answers)
what is the Java equivalent of sscanf for parsing values from a string using a known pattern?
(8 answers)
Closed 4 years ago.
Hi I i'm trying to do a line by line reading in of a file in Java. For example I'd like to be able to do something like
//c code
while( fscanf(ptr, "%s %s %s",string1,string2,string3) == 3)
printf("%s %s %s",string1,string2,string3);
Where I scan in every line in the file individually and store it in a variable.
I have started out by making a file object and finding the file. However I haven't found a function to be able to read input.
Use line oriented input, split the lines and print the contents. That is, read each line, check if you have three tokens (end if you don't) and print them. Like,
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] tokens = line.split(" ");
if (tokens.length != 3) {
break;
}
System.out.printf("%s %s %s%n", tokens[0], tokens[1], tokens[2]);
}
Change System.in to a File to read from a file.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am writing a Java program to practice my programming skill. The program is supposed to read input from a file, split it using space, and then print it out.
import java.io.*;
import java.util.*;
public class SumsInLoopTester {
public static void main(String[] args) {
try
{
File f = new File("SumsInLoop.txt");
Scanner sc = new Scanner(f);
int n = sc.nextInt();
int i = 0;
int sum[] = new int[n]; // I will use this later
while(sc.hasNextLine())
{
String input = sc.nextLine();
String splits[] = input.split("\\s+");
System.out.println(splits[0]);
System.out.println(splits[1] + "\n");
}
} catch(FileNotFoundException e) {
System.out.println(e);
}
}
}
Here is what's inside the input file:
SumsInLoop.txt
The output I expect to see is:
761892
144858
920553
631146
.
.
.
.
.
.
.
.
But instead, I got ArrayIndexOutofBoundsException exception. I tried to add space after each number on the second column and it worked. But I'm just curious why it wouldn't work without adding spaces. I spent so much time trying to figure this out, but no clue. I know that I don't have to split the string before I output it. Just want to have a little practice with split() method and get to know it better.
If you expect to see this:
761892 144858
920553 631146
simply use like this ,
while (sc.hasNextLine()) {
String input = sc.nextLine();
System.out.println(input);
}
there is no use of doing System.out.println(splits[1] + "\n"); since splits[1] don't have any value
First of all, you should not expect to see
761892 144858
920553 631146
Because you have already split by whitespace, you wont find whitespace in splits
Your problem is most likely caused by some lines in file has no whitespace. Then indexing splits[1] would throw ArrayIndexOutofBoundsException because in that case splits only has one element
Edit: you can make a conditional statemetn before printing
replace
System.out.println(splits[1] + "\n");
with
if (splits.length > 1) {
System.out.println(splits[1] + "\n");
}
This question already has answers here:
Creating a Java Program to Search a File for a Specific Word
(3 answers)
Closed 5 years ago.
I am trying to count the number of times a specific string appears into a file.
This is the code I am using:
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(wordidnamee1))
count++;
}
This code only counts the number of time the string appears 'clean', but if it is attached to another word or followed by a colon it is not counted.
How can I solve this problem ?
Use contains()
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.contains(wordidnamee1))
count++;
}
For Non Case Sensitive match:
while (scanner.hasNext()) {
String nextToken = scanner.next();
if (nextToken.toLowerCase().contains(wordidnamee1.toLowerCase()))
count++;
}
I have file with the below data
A,8,43
B,7,42,
C,9,34
I am using the below code to read the data
Scanner input = new Scanner(new File("D:\\test.txt"));
input.useDelimiter(",|\n");
while(input.hasNext()) {
String name = input.next();
int age = input.nextInt();
int height = input.nextInt();
When I am executing the program I am getting InputMisMatch exception,
Please suggest what is mistake.
At end of second line you have , and line separator (I am assuming \n) This means you have empty element between these two delimiters.
So in third iteration
String name = input.next();
int age = input.nextInt();
int height = input.nextInt();
input.next(); is consuming "", which means input.nextInt() will try to consume C.
To solve this problem you can set delimiter to be combination of one or more commas and line separators like
input.useDelimiter("(,|\n)+");
To improve your code even farther instead of \n you can use \\R added in Java 8 (or \r|\n in earlier versions) to handle all line separators, because currently you don't consider \r as delimiter so it can be treated as valid token.
So better solution would be using
input.useDelimiter("(,|\\R)+"); //for readability
or even
input.useDelimiter("[,\r\n]+");
The problem lies at the use of the useDelimiter method. This method accepts a regular expression as a parameter. You can't just say ,|\n to mean "comma or new line". There are rules.
What you should pass in is "[,\\n]+". This means "one or more characters in the following set: [comma, new line character]".
With the regex that you are passing currently, ,|\n, it means that the delimiter should be either , or \n, but not both. So when it encounters the second line:
B,7,42,
this is what happens:
next reads "B"
nextInt reads "7"
nextInt reads "42"
next reads an empty string that is between the "," and the new line.
nextInt now tries to read the next token "C", which it can't.
EXCEPTION!
I would do things differently -- use one Scanner to parse each line of the File and use a 2nd Scanner nested within the while loop to extract tokens or data from the lines obtained from the first Scanner. For example:
String filePath = "D:\\test.txt";
File file = new File(filePath);
// use try-with-resources
try (Scanner input = new Scanner(file)) {
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\\s*,\\s*"); // get comma and any surrounding whitespace if present
String name = "";
int age = 0;
int height = 0;
if (lineScanner.hasNext()) {
name = lineScanner.next();
} // else ... throw exception?
if (lineScanner.hasNextInt()) {
age = lineScanner.nextInt();
} // else ... throw exception?
if (lineScanner.hasNextInt()) {
height = lineScanner.nextInt();
} // else ... throw exception?
// use name, age, height here
System.out.printf("%s %s %s%n", name, age, height);
lineScanner.close(); // don't waste resources -- return them
}
} catch (IOException e) {
e.printStackTrace();
}