details:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine<Scanner.java:1540>
at CarReader2.main<CarReader2.java:30>
that's the entirety of the error.
My code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CarReader2 {
String name, speed, acc;
public CarReader2(String carName, String carSpeed, String carAcc){
name = carName;
speed = carSpeed;
acc = carAcc;
}
public String toString(){
return "Name of car: " +name+ "\nSpeed of car: " +speed+"\nAcceleration of car: " +acc+"\n";
}
public static void main(String[] args) {
File file = new File("carlist.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String c1Name = sc.nextLine();
String c1Speed = sc.nextLine();
String c1Acc = sc.nextLine();
CarReader2 car1 = new CarReader2(c1Name,c1Speed,c1Acc);
car1.speed = c1Speed;
car1.acc = c1Acc;
String c2Name = sc.nextLine();
String c2Speed = sc.nextLine();
String c2Acc = sc.nextLine();
CarReader2 car2 = new CarReader2(c2Name,c1Speed,c1Acc);
car2.speed = c2Speed;
car2.acc = c2Acc;
System.out.println("Information on both cars");
System.out.println("First car:");
System.out.println(car1.toString());
System.out.println("Second car:");
System.out.println(car2.toString());
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
It's supposed to read data of 2 cars from a file called carlist.txt, then print the data of both cars in the correct format.
carlist.txt is a text file containing:
jonathan 3 7
dio 8 2
And the program is supposed to print out,
Information on both cars
First car:
Name of car: jonathan
Speed of car: 3
Acceleration of car: 7
Second car:
Name of car: dio
Speed of car: 8
Acceleration of car: 2
The program compiles but doesn't run correctly and shows the error i posted at the very top.
You're using nextLine method wrong. Name, speed and acceleration are in the same line, but you're using 3 nextLine methods to read them. That's what happens when you try to read 6 lines from a file that only has 2 lines in it. use sc.next() instead of sc.nextLine().
You are reading too many lines. There are only two lines in your file, but you are trying to read 6. You can change your text file to:
jonathan
3
7
dio
8
2
or you can read one line and split out the information you want.
Related
New to Java. I'm having a hard time understanding why my code isn't running. I'm getting a InputMismatchException when I try to run my code.
I did some testing and problems occur if there's white space in my file such as "New York." I've been trying different things such as looping with .hasNextLine() instead of .hasnext() as suggested in other threads but to no avail. Sometimes I can get it to run until the end it gives me a NoSuchElementException. If you could please put me in the right direction, that would help a lot thank you!
import java.util.*;
import java.io.*;
public class StandaloneReport {
public static void main(String[] args) {
String fileInputName;
String fileOutputName;
String firstName;
String lastName;
String houseNumber;
String street;
String city;
String state;
String zip;
String productDescription;
double productPrice;
//Scanner obj1
Scanner input = null;
input = new Scanner(System.in);
System.out.printf("What is the file name?\n");
fileInputName = input.nextLine();
//Print out the name user inputed
System.out.println("File name is: " + fileInputName);
//Read the file
FileReader filereader;
Scanner readInput = null;
try {
readInput = new Scanner(filereader = new FileReader(fileInputName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (readInput.hasNext())
{
firstName = readInput.next();
lastName = readInput.next();
houseNumber = readInput.next();
street = readInput.next();
city = readInput.nextLine();
state = readInput.next();
zip = readInput.next();
productDescription = readInput.nextLine();
productPrice = readInput.nextDouble();
Textfile looks like this:
Jane
Doe
10
Broadway
New York
NY
10001
Galaxy S10
199.99
2
Samsung Bluetooth
29.99
1
Slim Fit Hard Plastic Case
2.99
2
Charger
17.99
3
Error I get:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at hey.bcs.hwk.purchases.standalonereport.StandaloneReport.main(StandaloneReport.java:55)
I expected it to read it smoothly so I can print it using PrintStream in another file but I cannot even get past this part.
To be honest your program is problematic in so many ways. But here's an explanation to fix the mismatch issue you mentioned.
readInput.nextLine()
will read the remainder of the current line. So after reading "Broadway" the Scanner stays in the same line and when you call nextLine, the Scanner yields whatever is left in the line for "Broadway", which is an empty String.
To avoid this situation, do
street = readInput.next();
readInput.nextLine();
To drop the current line("Broadway" for example). And then call
city = readInput.nextLine();
That way the program will read "New York" as you expected. As Tom mentioned in the comments, for more details, look at the question asked here.
Apart from the Scanner issue, your program is ambiguous as to where it ends – you did not provide closing brackets. That while loop seems redundant considering that your input is broken: it ceases to match what you have in your code after the "199.99" line. Please put your complete code on there and revise your sample input.
This is for one set of data, one data item per line. You have to make adjustments for multiple sets of data.
int i = 0;
while (readInput.hasNext())
{
if (i == 0)
{
firstName = readInput.nextLine();
}
else if (i == 1)
{
lastName = readInput.nextLine();
}
else if (i == 2)
{
houseNumber = readInput.nextLine();
}
else if (i == 3)
{
street = readInput.nextLine();
}
else if (i == 4)
{
city = readInput.nextLineLine();
}
else if (i == 5)
{
state = readInput.nextLine();
}
else if (i == 6)
{
zip = readInput.nextLine();
}
else if (i == 7)
{
productDescription = readInput.nextLine();
}
else if (i == 8)
{
productPrice = readInput.nextDouble();
}
i += 1;
} // End while
I am currently going through the Helsinki MOOC for Java OOP and I have hit a snag on one of the questions. I am working on Week 7 Exercise 8 and when I run my code manually I am getting everything to work out okay. However when I run their automated tests I am getting the "NoSuchElementException" error.
It is my understanding from the JavaDoc on this particular error that it is most likely caused by .nextLine() not finding a line to read. What confuses me though is based on the error message, and the location of the exceptions, my use of .nextLine() is working in some places and not others while I am using it in the same manner. I included my class that I am using below. Thanks for the help everyone, and if I overlooked a previous post similar to this I apologize.
import java.util.Scanner;
import java.util.ArrayList;
public class AirportPanel {
private Scanner reader;
private ArrayList<Airplane> airplanes;
private ArrayList<Flight> flights;
public AirportPanel(Scanner reader){
this.reader = reader;
this.airplanes = new ArrayList<Airplane>();
this.flights = new ArrayList<Flight>();
}
public void start(){
System.out.println("Airport panel");
System.out.println("--------------------\n");
while(true){
printMenu();
String input = readString();
if(input.toLowerCase().equals("x")){
break;
}else{
chooseOperation(input);
}
}
}
private void printMenu(){
System.out.println("Choose operation:");
System.out.println("[1] Add airplane" + "\n[2] Add flight" + "\n[x] Exit");
System.out.print("> ");
}
private void chooseOperation(String input){
if(input.equals("1")){
addPlane();
}else{
addFlight();
}
}
private void addPlane(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give plane capacity: ");
String planeCap = readString();
this.airplanes.add(new Airplane(planeID, planeCap));
}
private void addFlight(){
System.out.print("Give plane ID: ");
String planeID = readString();
System.out.print("Give departure airport code: ");
String airport1 = readString();
System.out.print("Give destination airport code: ");
String airport2 = readString();
String airports = airport1 + "-" + airport2;
for(Airplane ap : this.airplanes){
if(ap.getID().equals(planeID)){
this.flights.add(new Flight(ap, airports));
}
}
}
private String readString(){
return this.reader.nextLine();
}
EDIT: Here is a screenshot of the stack trace. I also made a github repo with all of my files in the event that would help more. I am pretty new to coding so excuse the mess I surely made of these files.
EDIT 2: I went to my readString() method and changed my call of .nextLine() to .next() and it fixed my issue. I'm not entirely sure how or why but it is now submitting correctly.
I've been trying to practice I/O file programming and I'm still at the basics. Writing into a file using the java was simple enough but reading to a file is beginning to give me a headache. Here's a simple program I tried to run(btw, I based the program from a book by Liang) .
import java.util.Scanner;
import java.io.File;
public class Reading {
private static Scanner n;
public static void main(String[] args) throws Exception
{
File files = new File("samples.txt");
n = new Scanner(files);
while(n.hasNext())
{
String firstName = n.next();
String mi = n.next();
String lastName = n.next();
int score = n.nextInt();
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
}
n.close();
}
}
Here's the error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at OOPFinals.Reading.main(Reading.java:17)
How do I make this program work?
Help!
The NoSuchElementException is thrown by Scanner.next() and means there are no more tokens to be found in the file.
The problem here is that your while() loop only guarantees that there is at least ONE token left to read from the file, however on each iteration of the loop you are reading in FIVE tokens.
What is happening in your code, you are trying to read from the Scanner although there's nothing left there to read.
What you should do - You need to check n.hasNext() before each call to n.next() or n.nextInt(), or just read the entire line (which seems exactly what you want):
while (n.hasNextLine()) {
String line = n.nextLine();
System.out.println(line);
}
Your code is working given that the right input file "samples.txt" is provided. For example, given the following input:
Richard Phillips Feynman 100
Paul Adrien Dirac 90
Everything works fine, however if you use the following:
Richard Feynman 100
Paul Adrien Dirac 90
then you obtain the NoSuchElementException. In the last example, I removed the middle name that your program is expecting. As such, we can conclude that you are expecting to read information in a file with no information left to read. I recommend something like the following:
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.File;
public class Reading {
private static Scanner n;
public static void main(String[] args) throws Exception
{
File files = new File("samples.txt");
n = new Scanner(files);
String data;
while(n.hasNextLine() && !(data = n.nextLine()).equals(""))
{
StringTokenizer st = new StringTokenizer(data);
if(st.countTokens() >= 4) {
String firstName = (String) st.nextElement();
String mi = (String) st.nextElement();
String lastName = (String) st.nextElement();
int score = Integer.parseInt( (String) st.nextElement());
System.out.println(
firstName + " " + mi + " " + lastName + " " + score);
} else {
System.err.println("This line is malformed!");
}
}
n.close();
}
}
In this program, you can have a sample file that has empty lines and it expects to read 4 tokens per line or else it prints an error message informing you that a line has malformed input.
Sometimes when you're reading a file you'll run into various characters. Some are letters, some are numbers, and some are integers. You need to check whether it's a letter, number, or an integer because the following line assumes you are passing an integer:
int score = n.nextInt();
It can be resolved by checking for integers:
int score = 0;
if(n.hasNextInt()) { score = n.nextInt(); }
When you're reading from the program, make sure to take Cathial's answer into consideration. By using hasNext(), you're only checking if there is one string, also known as a token. You should check if there are n strings available where n is the number of .next() functions in your loop.
So for my current school project we have to read input from a file containing info on the periodic table of elements. Essentially I have to seperate bits of each line which has info on an element and put them into seperate string values.
Here the bit of code I'm having problems with.
for(int i=0;inputStream.hasNextLine();i++)
{
String line = inputStream.nextLine();
String[] info = line.split(",");
name=info[0];
atomicNumber=info[1];
symbol=info[2];
boilingPoint=info[3];
meltingPoint=info[4];
density=info[5];
molecularWeight=info[6];
elementInfo[i]= new Element(name,atomicNumber,symbol,boilingPoint,meltingPoint,density,molecularWeight);
It stores everything in the proper place except for the information for the density and the molecular Weight which i get null values for. I couldn't find any info why it isn't working for those last two Strings.
Example output:
Element Name: actinium
Atomic Number: 89
Symbol: Ac
Boiling Point: 3470
Melting Point: 1324
Density: null
Molecular Weight: null
Here's the constructor for the element object:
public Element(String name,String atomicNumber,String symbol, String boilingPoint, String meltingPoint, String density, String molecularWeight)
{
this.name=name;
this.atomicNumber=atomicNumber;
this.symbol=symbol;
this.boilingPoint=boilingPoint;
this.meltingPoint=meltingPoint;
this.density=density;
this.molecularWeight=molecularWeight;
}
You can try this,
// mean into file that info not exist, in that case take its default i.e. empty
info[5] == null ? "empty" : info[5];
info[6] == null ? "empty" : info[6];
Definitely the file you are reading contains 7 elements, else the following code will result in an error
density=info[5]; molecularWeight=info[6];
Example:
public static void main(String args[]) {
String line = "1,2,3,4,5,,";
String[] info = line.split(",");
System.out.println(info.length);
System.out.println(Arrays.deepToString(info));
}
The Output of the above snippet is 5 and [1, 2, 3, 4, 5]
Here we cannot use info[5] or info[6] as it will result in an error.
So your data is correct and you are capturing all the values.
I believe the problem is in printing the output, but you have not mentioned that code in your query to investigate deep.
Hope it helped.
String.split() never ever returns null (see here), which means the problem is not with split() method but, elsewhere. The split() method seem to return at least 7 chunks of data and this is because you are not getting ArrayIndexOutOfBoundException when you do this molecularWeight=info[6].
Then the problem is elsewhere and you can find out by reviewing your code and there must be something you are missing, something really really simple.
Let's assume you have the following input (2 elements):
actinium,89,Da,3470,1926,missing-x,missing-y
actinium,13,Gk,5480,1124,missing-z,missing-w
I used majority of your code, and developed a sample use cases to read the above two elements from file and store them in a list and print them back. I used List<Element> instead of your Element[] solution as well as overrided toString() in Element class to pretty-print the elements with Java 8's stream, see below and compare with your solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFromFileElements {
public static void main(String... args) throws FileNotFoundException {
// You can use list instead of Element[] array
List<Element> elementInfo = new ArrayList<Element>();
//file containing the input
File file = new File("C:\\test_java\\elements.txt");
//open input stream to the file
Scanner input = new Scanner(file);
//as long as there is nextLine() keep looping
while(input.hasNextLine()) {
String line = input.nextLine();
String[] chunk = line.split(",");
Element e = new Element(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5],
chunk[6]);
//add to the list of Element/s
elementInfo.add(e);
}
//close input stream
input.close();
//java 8 stream iterator through collection
elementInfo.stream().forEach((temp) -> {
//temp.toString() uses the overrided toString() of element class
System.out.println(temp.toString());
});
}
}
class Element {
String name;
String atomicNumber;
String symbol;
String boilingPoint;
String meltingPoint;
String density;
String molecularWeight;
public Element(String name, String atomicNumber, String symbol, String boilingPoint, String meltingPoint,
String density, String molecularWeight) {
this.name = name;
this.atomicNumber = atomicNumber;
this.symbol = symbol;
this.boilingPoint = boilingPoint;
this.meltingPoint = meltingPoint;
this.density = density;
this.molecularWeight = molecularWeight;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\n Element name: " + this.name);
builder.append("\n Atomic no: " + this.atomicNumber);
builder.append("\n Symobl : " + this.symbol);
builder.append("\n Boiling point : " + this.boilingPoint);
builder.append("\n Melting point : " + this.meltingPoint);
builder.append("\n Density : " + this.density);
builder.append("\n Molecular weight: " + this.molecularWeight);
return builder.toString();
}
}
And running the above code against the above two lines in the file, I get the following input:
Element name: actinium
Atomic no: 89
Symobl : Da
Boiling point : 3470
Melting point : 1926
Density : missing-x
Molecular weight: missing-y
Element name: actinium
Atomic no: 13
Symobl : Gk
Boiling point : 5480
Melting point : 1124
Density : missing-z
Molecular weight: missing-w
Use this
public static void readFileData(String filename) throws FileNotFoundException{
ArrayList<Element> list = new arrayList<>();
String split = ","; //split with comma
Scanner in = new Scanner(new File(filename));
String wordIn;
Element elem = new Element();
while (in.hasNextLine()) {
wordIn = in.nextLine();
String splitter[] = wordIn.split(split);
String name = splitter[0];
int atomicNumber = Integer.parseInt(splitter[1]);
String symbol = splitter[2];
String boilingPoint = splitter[3];
String meltingPoint = splitter[4];
String density = splitter[5];
String molecularWeight = splitter[6]
elem.setName(name);
elem.setAtomicNumber(atomicNumber);
elem.setSymbol(symbol);
elem.setBoilingPoint(boilingPoint);
elem.setMeltingPoint(meltingPoint);
elem.setDensity(density);
elem.setMolecularWeight(molecularWeight);
list.add(elem);
}
for(Element el : list){
sout(el.toString()) // if you have a to string method
}
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String file = sc.next();
readFileData(file);
}
Make sure you have those setters in your Element class. And a too String method would be handy but not necessary. If the variable is type int in your Element class the you can do Integer.parseInt() or Double.parseDouble which converts string to integer or float etc. sout is short for System.out.println(); type sout + tab and you get the full thing.
I have a plain format txt file named enroll.txt which contains:
1997 2000
cs108 40 35
cs111 90 100
cs105 14 8
cs101 180 200
The first row shows the years of class
The second row first column shows the class name, and the following two columns show the number of students in the class in the years mentioned on the first row.
ex) In 1997, there were 40 students in class cs108.
My desired outcome: code prints as follows using
(i) split (ii) parseInt (iii) for-loop
student totals:
1997: 324
2000: 343
But this code should also work for any number of years (for example if I had student numbers for four years for each class instead of two, the code would still give me a similar output as below with student totals of say 1997, 2000, 2001, 2002 etc.)
What I have so far:
import java.util.*;
import java.io.*;
public class ProcessCourses{
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
String fileName = console.nextLine();
Scanner input = new Scanner(new File(fileName));
while(input.hasNextLine()){
String line = input.nextLine();
String[] arr = line.split(" ");
//......????
}
}
}
What would go inside the //....????
So in the first line you have years, read them first :
Scanner input = new Scanner(new File(fileName));
String str = input.nextLine();
String[] years = str.split(" ");
Now you have set of student's information,
int[] total = new int[years.length];
while(input.hasNextLine()){
String line = input.nextLine();
String[] strength = line.split(" ");
int len = strength.length; // no of entries which includes course id + "years" no.of numbers.
for(int i=1;i<len;i++){ // from 1 because you don't care the course id
total[i-1] = total[i-1] + Integer.parseInt(strength[i]);
}
}
Then just print it :
for(int i=0;i<years.length;i++){
System.out.println(years[i]+ " : " + total[i]);
}