Ask coding questions

← Back to all posts
Can you till me what is missing in my Code
DemonLord1 (0)

import java.util.Scanner;//did not work
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class ReadAndWrite {

public static void main(String [] args) 
		throws FileNotFoundException {
	
	Scanner diskScanner = new Scanner(new File("rawData.txt"));
	
	PrintStream diskWriter = new PrintStream("vita.txt");
	double unitPrice, quantity,total;
	
	unitPrice = diskScanner.nextDouble();
	quantity = diskScanner.nextInt();
	
	total = unitPrice * quantity;
	diskWriter.println(total);
	
	diskScanner.close();
	diskWriter.close();
		
}

}

Commentshotnewtop
mwilki7 (277)

What's wrong with it?

DemonLord1 (0)

@mwilki7 i get this erro when i run it Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at ReadAndWrite.main(ReadAndWrite.java:16)

mwilki7 (277)

@DemonLord1
I think it may be because your files are empty and you call:

unitPrice = diskScanner.nextDouble();
quantity = diskScanner.nextInt();

as if it has something.

To fix this do:

  • fill in text files with text
  • make sure your file has something before reading from them with:
if (diskScanner.hasNext())
{
    // do stuff with text file input here
}
else
{
    // end of file reached, no more text to be read
}

I have added some changes, refer to this if you need help:
https://repl.it/@mwilki7/NewLinearSolution-2