java scanner next line throws but only with print statement [duplicate] - java

This question already has answers here:
using hasNextLine() but still getting java.util.NoSuchElementException: No line found
(5 answers)
Closed 5 years ago.
When I try to use java scanner it works and in my list I get all the text file content as a list.
But when I try to print within the while loop, it throws
java.util.NoSuchElementException: No line found
exception at the last line. Why would that be the case, wouldn't mylist also thrown had it been out of bound?
try {
Scanner myscanner = new Scanner(new FileReader(myfilepath));
while(myscanner.hasNextLine()){
//System.out.println(myscanner.nextLine() );
mylist.add(myscanner.nextLine());
numline += 1;
}
myscanner.close();
}
catch (Exception ex) {
ex.printStackTrace();
}

You check that you have next line and then when you print you read 2 lines.
You should change it to:
String line = myscanner.nextLine();
// print and add to list using line variable

To avoid that you should create variable to store the result fo myscanner.nextLine() then print it and add it to the list. e.g
while(myscanner.hasNextLine()){
String temp = myscanner.nextLine();
System.out.println(temp);
mylist.add(temp);
numline += 1;
}

Related

Reading from file to array but last line overrides all other lines [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 2 years ago.
So I wanted this to be my last resort because I did enough progress with doing the main code and I was only to come here if nothing else worked.
String line = "";
try
{
BufferedReader br = new BufferedReader (new FileReader("league.txt"));
FootballClub club = new FootballClub();
while ( ( line = br.readLine() ) != null )
{
String[] FC = line.split(",");
club.setName(FC[0]);
club.setLocation(FC[1]);
club.setMatchesPlayed(Integer.parseInt(FC[2]));
club.setWins(Integer.parseInt(FC[3]));
club.setDraws(Integer.parseInt(FC[4]));
club.setLosses(Integer.parseInt(FC[5]));
club.setGoalsScored(Integer.parseInt(FC[6]));
club.setGoalsAgainst(Integer.parseInt(FC[7]));
club.setGoalDifference(Integer.parseInt(FC[8]));
club.setPoints(Integer.parseInt(FC[9]));
league.add(club);
}
br.close();
}
catch (FileNotFoundException e) { }
catch (IOException e){ }
This is my code from reading from a text file into array. The text file is as follows:
Chelsea,London,0,0,0,0,0,0,0,0
WestHam,London,0,0,0,0,0,0,0,0
The problem is that when I test the program, two clubs get added to the array however the values for the first line get overridden by the second line. I have been trying to get one line added first then the second until there is no line but I seem to be lucking out. I have been looking everywhere to try and fix it but no luck and it does seem like an easy fix but I'm burned out and can't find it. Any pointers and suggestions would be appreciated.
You need to create a new instance of the class on each iteration, otherwise you keep setting properties on the same object, so only the last line will be stored.
while ((line = br.readLine()) != null){
String[] FC = line.split(",");
FootballClub club = new FootballClub();
//...
}

How to read a textfile and saving it into an Array? [duplicate]

This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 4 years ago.
i would like to build a text data-cleaner in Java, which
cleans the text from Smileys and other special charakter. I wrote a text reader,
but he stops after 3/4 of Line 97 and i just don't know why he does it? Normally he should read the complete text file (ca. 110.000 Lines) and then stop. It would be really nice if could show me where my mistake is.
public class FileReader {
public static void main(String[] args) {
String[] data = null;
int i = 0;
try {
Scanner input = new Scanner("C://Users//Alex//workspace//Cleaner//src//Basis.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
data[i] = line;
i++;
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(data[97]);
}
}
Your mistake is here:
String[] data = null;
I would expect this code to throw null pointer exception...
You can use ArrayList instead of plain array if you want to have dynamic re-sizing

How to deal with scanner exception [duplicate]

This question already has answers here:
How can I use hasNextInt() to catch an exception? I need Int but if input is character, that is bad
(3 answers)
Closed 9 years ago.
Basically I am taking a string input that represents a file. That file can contain integers, doubles or random strings. I am trying to iterate through the file adding all the integers and then taking the average of all of them. The issue I'm stuck on is when I get something other than an integer. I don't know how I am supposed to catch and deal with the error and then iterate onto the next part of the file. I can't use if statements and I'm thoroughly stuck.
String storeVariables = null;
FileReader fileReader;
BufferedReader bufferedReader;
Scanner scanner = null;
int total = 0;
int itterate = 0;
try{
fileReader = new FileReader(filename);
bufferedReader = new BufferedReader(fileReader);
scanner = new Scanner(bufferedReader);
while(scanner.hasNextInt()){
total += scanner.nextInt();
itterate++;
}
}
catch(Exception e){
}
return total/itterate;
}
Scanner#nextInt may throws
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Try this -
while(scanner.hasNextInt()){
try{
total += scanner.nextInt();
itterate++;
}catach(RuntimeException nfe){...}
}

Parse string in Java [duplicate]

This question already has answers here:
string parsing in java
(4 answers)
Closed 7 years ago.
I have a string in below format
// JCSDL_MASTER b04591342ee71a2baa468d9d2a340ec8 AND
// JCSDL_VERSION 1.0
// JCSDL_START 0980a5f2ef935c4ed153bf975879eac0 twitter.text,contains_any,27-52
twitter.text contains_any "obama, santorum, gingrich, romney, ronpaul, ron paul"
// JCSDL_END
AND
// JCSDL_START f7c18a6fedd90c6b4d77acc14a3a8e5c interaction.type,in,21-29
interaction.type in "twitter,facebook,digg,youtube"
// JCSDL_END
// JCSDL_MASTER_END
I suppose it include newline character at the end, i need to just get only those line which is not being started by // how to get only those lines?
Pretty simply, just split up the string into individual lines (note: \n is an escape character for a line break), then only use each line if it does not start with //
String[] lines = string.split("\\n");
for (String line : lines)
{
if (!line.startsWith("//"))
{
//use the line and do your thing
}
}
Use Scanner.nextLine() to read each line and then Ignore the ones which starts with // like following:
String str = "hi \n//this is kuleep\nthis is a test class";
Scanner sc = new Scanner(str);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if(!line.startsWith("//"))
{
System.out.println(line);
}
}

Preventing the NoSuchElementException when reading from a file with no spare line

I am trying to find a way to deal with the NoSuchElementException error thrown by a Scanner object when reading the last item in my text file with NO SPARE LINE. This means that my cursor will end after the last character of the last line in the file
EXAMPLE:
score.txt
[Test;Word|]
[ & ] denotes the start and end of the text file
The | is where the cursor ends.
I know that if my cursor ends a line below it, my Scanner will not throw the NoSuchElementException because there is a nextLine.
What i want to achieve is to ensure that the NoSuchElementException is not thrown when the spare line is missing. Is there a way to prevent the error from occurring besides making sure that the spare line is there?
My Driver class simply calls the method importWordList() from class WordGame.
The code for WordGame is very long so I will only upload the method importWordList() from the class.
public boolean importWordList(String fileName) throws FileNotFoundException
{
//Set default return value
boolean returnVal = false;
//Set File to read from
File wordListDest = new File(fileName);
if (wordListDest.canRead() == true)
{
lineS = new Scanner(wordListDest);
//Read each line from file till there is no line
while (lineS.hasNextLine())
{
//Set delimeter scanner to use delimeter for line from line scanner
String line = lineS.nextLine();
delimeterS = new Scanner(line);
delimeterS.useDelimiter(";");
//Read each delimeted string in line till there is no string
while (delimeterS.hasNextLine())
{
//Store Variables for quiz object
wordAndHint = delimeterS.nextLine();
answer = delimeterS.nextLine(); //ERROR
//Create Object Quiz and add to wordList
Quiz addWord = new Quiz(wordAndHint, answer);
wordList.add(addWord);
}
delimeterS.close();
}
lineS.close();
returnVal = true;
System.out.println("Word List has been Imported Successfully!");
}
else
{
System.out.println("The file path you selected either does not exist or is not accessible!");
}
return returnVal;
}
The Error that occurs is as Follows:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at mysterywordgame.WordGame.importWordList(WordGame.java:74)
at mysterywordgame.Main.main(Main.java:60)
The error (at mysterywordgame.WordGame.importWordList(WordGame.java:74)) refers to line with the comment ERROR.
I have searched around for ways to prevent the error from occurring, however, all answers were "Make sure there is a spare line at the end of the text file"
Some help will be much appreciated.
As you already consumed the next line with wordAndHint = delimeterS.nextLine(); you have to check for next line again:
if(delimeterS.hasNextLine()){
answer = delimeterS.nextLine();
}else{
answer = "";
}

Categories