Please Help with an Exception that I cannot get rid of
Code:
import java.util.Scanner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Assignment11c {
public static void main(String[] args) throws IOException {
URL serviceUrl = new URL("http://i5.nyu.edu/~cmk380/cs101/USStates.txt");
Scanner input = new Scanner( serviceUrl.openStream() );
String [] stateAbbr = null;
while ( input.hasNext() )
{
stateAbbr = new String[50];
for (int i = 0; i < 50; i++){
String data = input.nextLine();
String[] splitData = data.split(",");
stateAbbr[i] = splitData[1];
}
}
System.out.println(stateAbbr);
}
}
I'm trying to dump the .txt file into an array, but I kept getting this exception error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Assignment11c.main(Assignment11c.java:24)
It could be that I'm overlooking something, but for now, I cannot for the life of me figure out the problem. If someone can help, that'll be much appreciated!
Re: Please Help with an Exception that I cannot get rid of
Code:
while ( input.hasNext() )
{
for (int i = 0; i < 50; i++){
String data = input.nextLine();
}
}
You check if there is a nextLine(), then proceed to attempt to read 50 lines.
What if there were only 49, or 3?
Re: Please Help with an Exception that I cannot get rid of
Well, if you want to read the next line you should test whether the Scanner has a next line. But are you sure that's what you want to read?
db
Re: Please Help with an Exception that I cannot get rid of
It worked fine for this:
Code:
import java.util.Scanner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
public class Assignment11b {
public static void main(String[] args) throws IOException {
URL serviceUrl = new URL("http://i5.nyu.edu/~cmk380/cs101/ProfessorSalary.txt");
Scanner input = new Scanner( serviceUrl.openStream() );
String [] profRank = null;
double [] profSalary = null;
while ( input.hasNext() )
{
profRank = new String[1000];
profSalary = new double [1000];
//populate arrays
for (int i = 0; i < 1000; i++){
String data = input.nextLine();
String[] splitData = data.split(" ");
profRank [i] = splitData[2];
profSalary [i] = Double.parseDouble(splitData[3]);
}
}
input.close();
So why didn't it work for the code posted in the OP?
Re: Please Help with an Exception that I cannot get rid of
Quote:
Originally Posted by
vx117
It worked fine for this:
So why didn't it work for the code posted in the OP?
Did you take the time to read Tolls' response?
db
Re: Please Help with an Exception that I cannot get rid of
How many lines are there in the txt file?
I just had a look and there are exactly 1000...so your second code works in this special case.
Your first one has 51 lines.