I have a scanner called input with this code:
Scanner input = new Scanner(System.in);
int cFreq = 0;
System.out
.println("Enter the symbol which you want to find the frequency of:");
char s = 'a';
symbolLoop: while (s == 'a') {
try {
s = input.next(".").toLowerCase().charAt(0);
} catch (InputMismatchException e) {
System.out.println("Please enter a valid symbol!");
input.next();
}
switch (checkSymbol(s)) {
case 0:
s = 'a';
break;
case 1:
break symbolLoop;
}
}
for (int i = 0; i < words.size(); i++) {
cFreq += words.get(i).find(s, true);
}
System.out.println("Number of times " + s + " is in the coded words: "
+ cFreq);
}
However when it reaches the line where it reads from the scanner it terminates with this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.next(Scanner.java:1418)
at Home.frequency(Home.java:118)
at Menu.select(Menu.java:58)
at Menu.view(Menu.java:17)
at Home.main(Home.java:22)
(Home is the name of the class).
I have no idea what is causing this and would appreciate some help! :)
Thanks!
EDIT:
I have also tried with this code: String str = input.nextLine(); in the same method but it throws the same error.
If data from user wouldn't match "." regex (possibly surrounded by delimiters - whitespaces) next(".") would't throw NoSuchElementException, not InputMismatchException.
NoSuchElementException exception is thrown when Scanner can't even hope for more data, in which case it is sure that potentially next element will not even exist. Such situation is only possible if Scanner knows that source of data will not have more elements, which in case of Stream is when we will read entire content of stream (like in case of FileInputStream) or it will be closed.
In case of System.in we can assume that content of this stream is infinite, because it is provided by user, so when we try to read from it, application is waiting until user will provide its data. Which means that only way Scanner would throw NoSuchElementException is when System.in was closed, so next doesn't have more data to read.
To avoid such cases you should avoid closing streams which are using System.in because you will not be able to reopen it again in your application.
Related
Ok so I have a text file like so
dears fears
heart heart
sail ruin
etc
I'm trying to run the scanner through each line so I can
create a WordLadder object which requires the 2 strings in each line.
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String s = sc.next();
String s2 = sc.next();
WordLadder wl = new WordLadder(s, s2);
System.out.print(wl.toString());
}
}
catch (FileNotFoundException ex)
System.out.print("File not found");
}
For some reason, when I run the debugger, as far as I can tell, it runs through once then it waits for user input. It creates a word ladder with dears and fears and prints the solution for that word ladder. Then second loop it waits for user input instead of doing it again.
I'm thoroughly confused because when I do something like this
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String s = sc.next();
System.out.println(s);
}
}
catch (FileNotFoundException ex)
{
System.out.print("File not found");
}
It prints all the words. But any variation I tried of trying to put those words in a wordladder object it waits for user input. Any ideas?
I just tried your code and I have no issues unless I have a file with an odd number of Strings. In that case, I get the following error:
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:1478)
at Main.main(Main.java:19)
This is expected since you are reading 2 Strings for each sc.hasNext().
So it seems to me that the issue might be the content of your input.txt file.
I need to try count the number of lines in a file while using "try" and "catch". This is what I have so far. Hoping I could get some help. It just keeps timing out.
public class LineCount {
public static void main(String[] args) {
try {
Scanner in = new Scanner(new FileReader("data.txt"));
int count = 0;
//String line;
//line = in.readLine();
while (in.hasNextLine()) {
count++;
}
System.out.println("Number of lines: " + count);
}catch (Exception e){e.printStackTrace();}
}
}
Seems like you are doing everything but consuming the newline character. To do this with java.util.Scanner, simply run in.nextLine() in your while loop. This Scanner.nextLine() method will return all characters before the next newline and consume the newline character itself.
Another thing to consider with your code is resource management. After opening the Scanner, it should be closed when it'll no longer be read. This can be done with in.close() at the end of your program. Another way to accomplish this is to setup a try-with-resources block. To do this, just move your Scanner declaration like this:
try (Scanner in = new Scanner(new FileReader("data.txt"))) {
Regarding the need for the try-catch block, as part of the Java compilation process, checked-exceptions will be checked if they are caught or thrown from a method. Checked-exceptions are everything that are not RuntimeExceptions or Errors.
It times out because you do not advance the Scanner. If you enter the while loop you will never exit it.
Also it would be better if you use BufferedReader as is is faster than a standard Scanner. Although if the file is small, maybe for readability purposes you do not. But this is up to you. Anyway.
Here you go:
//this is the try-with-resources syntax
//closing the autoclosable resources when try catch is over
try (BufferedReader reader = new BufferedReader(new FileReader("FileName"))){
int count = 0;
while( reader.readLine() != null){
count++;
}
System.out.println("The file has " + count + " lines");
}catch(IOException e){
System.out.println("File was not found");
//or you can print -1;
}
Probably your questiong has already been answered and you should not ask already answered questions before you search, for a while at least.
I cannot explain my problem very well, this is the prompt.
I believe I am going in the right direction, my professor really went through this fast. Even though I am using the book and asking for help, it is to no avail.
'**Ask the user to enter a filename on the keyboard, including “.txt.” Read five integers from that file (all on the same line, separated by spaces) and tell the user their sum by printing it to the screen (console).**'
It compiles and runs, but when entering the filename(io.txt) I get an Exception in thread "main" java.util.NoSuchElementException: No line found
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String myString = " ";
Scanner inputStream = null;
System.out.println("Please enter a Filename, including '.txt' at the end: ");
myString = in.next();
try
{
inputStream = new Scanner(new FileInputStream(myString));
}
catch(FileNotFoundException e) //Giving the file not found a name,
{
System.out.println("Invalid File or filename");
System.out.println("Or could not be found,try again");
System.exit(0);
}
//True will always add on, not overwrite
int n1 = inputStream.nextInt();
int n2 = inputStream.nextInt();
int n3 = inputStream.nextInt();
int n4 = inputStream.nextInt();
int n5 = inputStream.nextInt();
String line = inputStream.nextLine(); //wait for new line, get the next line
inputStream.close( );
System.out.println("The five numbers read from the file are: ");
System.out.println(n1+" , "+ n2 + ", "+ n3 + ", "+ n4 +", "+ n5);
System.out.println("Which adds together to eqaul: " + (n1+n2+n3+n4+n5));
}
I want direction, not for someone to solve it for me.
After testing the code you gave it returns with
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.example.Test.main(Test.java:37)
which is the following line in your code
String line = inputStream.nextLine(); //wait for new line, get the next line
So your code tries to read another line from the file, but it can't find one. In reality what this means is your code is expecting to read
"1 2 3 4 5\n" from a file io.txt whereas the file actually contains "1 2 3 4 5" (no newline at the end of the file).
However since you've already read all the integers you needed you can simply stop there.
Also make sure to close your file stream.
Use in. nextLine() in place of in. next().
I'm currently trying to read a file from my HDD. The file name is "Sample.txt", below is my code. I'm able to get it to compile and run, but receive this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at Proj1GradesService.errorReport(Proj1GradesService.java:42)
at Proj1GradesClient.main(Proj1GradesClient.java:13)
I've tried reading the file w/just a While loop and now with a try/catch, but received the same error, and I'm unsure what's exactly wrong with it. I'm trying to read the file from the Service Class and have the call to the method errorReport() from the Client Class.
Any help would be greatly appreciated.
import java.util.*; //allows use of Scanner class
import java.io.*; //for File and IOException classes
class Proj1GradesService
{ //begin Proj1GradesService
public void pageAndColHeading(char letter) //accepts char as a parameter
{ //start pageAndColHeading
switch (letter)
{ //start switch
case 'e': //write the caption for error report
System.out.println ("Error Report - Students With Invalid GPA"); //prints Error Report
break;
case 'v': //write the caption for valid report
System.out.println ("Valid Report - Students With Valid"); //prints Valid Report
break;
default: ; //do nothing
}//end switch
} //end pageAndColHeading
public void errorReport() throws IOException
{ //start errorReport
Scanner scanFile = null;
try
{
scanFile = new Scanner (new File ("p1SampleGPAData.txt"));
}
catch (FileNotFoundException fnfe)
{
System.out.println ("wrong file name.");
}
String name; //name read from file
double gpa; //gpa read from file
int count = 0; //line #
while (scanFile.hasNext( ))
{
name = scanFile.next();
gpa = scanFile.nextDouble();
System.out.println ("Line Number: " + count + "Name: " + name + "GPA: " + gpa);
++count;
} //end while
scanFile.close();
} //end errorReport
} //end class
Considering your file structure below which is assumed from printing statement
name1 1.1
name2 2.2
name3 3.3
Now according to your code following line
// consume your whole line. ie name1 1.1
name = scanFile.next();
// looking for double but instead getting string ie name2
// hence throwing InputMismatchException
gpa = scanFile.nextDouble();
Now to resolve above issue. You can use String.split().
// collect whole line
name = scanFile.next();
// split by one or more whitespace OR use your delimiter
String[] str = name.split("\\s+");
// gives name
String actName = str[0];
// gives gpa, throws NumberFormatException if str[1] is not double value
double gpa = Double.parseDouble(str[1]);
I hope this helps. If you need anymore help just ask.
Generally, InputMismatchException is thrown if the thing you're trying to parse doesn't match the format that Scanner expects.
So in this case, check your input file to see if the element you're parsing is actually a double. Be careful too of any extra whitespace.
This is most likely an issue of your data not matching what your program actually expects.
You need to recheck your file structure.
As the stacktrace shows nextDouble, the problem is a non-double within the file where scanner is expecing a double.
Without knowing what your input file looks like, this error is happening because you are trying to read character data into a double, and those characters being read are not doubles.
Make sure all the data you are reading in is in the format you expect it to be.
If this was me, I would read the entire data into a string, and then try to convert those strings in doubles, so I could surround that statement in a try/catch and then deal with it appropriately.
I wrote up this class based on some examples I found online for Data Streams and I'm getting an EOFException at the end of each run. When I looked it up it said the end of the stream had been reached unexpectedly. It does appear to work on the console (at least it spits out the correct sequence of numbers). The text file is just gibberish though when I inspect the contents after running.
public class DataStreamExample {
public static void main(String args[]) {
int choice = 0;
int[] numbers = { 25, 4, 19, 70, 12, 28, 39, 30 };
System.out.println("This program will provide an example on how the Data Stream works.");
System.out.println("Note: Data Streams only work with primative data types.");
System.out.println();
System.out.println();
try {
System.out.println("1. For write Data operation");
System.out.println("2. For read Data operation");
System.out.println("Enter the number for the operation of your choice: ");
BufferedReader buffRead = new BufferedReader(new InputStreamReader(System.in));
choice = Integer.parseInt(buffRead.readLine());
switch(choice){
case 1:
FileOutputStream fileOut = new FileOutputStream("Example.txt");
BufferedOutputStream buffOut = new BufferedOutputStream(fileOut);
DataOutputStream dOutput =new DataOutputStream (buffOut);
for (int i = 0; i < numbers.length; i ++) {
dOutput.writeInt(numbers[i]);
}
System.out.print("writing data ");
dOutput.close();
case 2:
FileInputStream fileIn = new FileInputStream("Example.txt");
BufferedInputStream buffIn = new BufferedInputStream(fileIn);
DataInputStream dInput = new DataInputStream (buffIn);
while (true){
System.out.print(dInput.readInt());
}
default:
System.out.println("Invalid choice");
}
}
catch (Exception e) {
System.err.println("Error in read/write data to a file: " + e);
}
}
}
Does anyone have any advice or observations that can help clean this up so I don't get gibberish in the file and so it doesn't catch the exception? How should I be ending the operation and closing the stream?
For your input operation, you are reading forever while(true), so the only way that loop will complete is by throwing EOFException. if you don't want the operation to complete that way, you will have to know how many ints you are reading before you start (and use that to limit the loop).
the reason the file looks like gibberish is because you are writing the values as binary. if you want to read the ints in the file, you would have to write them as text.
also, you should put break; statements at the end of each case.
Some things:
When you enter 1 to "write Data operation", you don't have a break; in your case statement, thus when you try to write the data, the integers gets written into the file, then the second case gets executed and you try to read from it. Not sure if this is your intention. But you can add a break to keep that from happening:
case 1:
FileOutputStream fileOut = new FileOutputStream("Example.txt");
BufferedOutputStream buffOut = new BufferedOutputStream(fileOut);
DataOutputStream dOutput =new DataOutputStream (buffOut);
for (int i = 0; i < numbers.length; i ++) {
dOutput.writeInt(numbers[i]);
}
System.out.print("writing data ");
dOutput.close();
break;
When you try to read from your data file, you loop indefinitely:
while (true){
System.out.print(dInput.readInt());
}
That means it'll keep attempting to read serialized integers until the end of the file is reached. And when the end of the file has been reached, the stream throws an EOFException`. You can try changing your loop to this to prevent the exception:
while (dInput.available()>0){
System.out.print(dInput.readInt());
}
break;
When you print the integers, they're going to be all jumbled up.
The text file is gibberish because it's not text. When you use a DataOutputStream the objects (or primitives) that you write into the stream gets processed so that the data is portable.
Well, instead of using
while (true){
System.out.print(dInput.readInt());
}
you should use
while(dInput.available()>0){
System.out.print(dInput.readInt());
}
Because when you use while(true), it's alway read from Stream, include when stream reach EOF (End Of File)
After all, you should close all your stream using close() method