Read from file not Printing to Output - java

Could anyone possibly be able to tell me why this code is not printing out to the output? I am not receiving any errors but it is just not printing. It is reading from a .txt file (which is below the code below).
Code:
public class ReadFromFile {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("CarInfo.txt");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNext()) {
String carTab = sc.next();
// Looking for tag 'Station:'
if (!carTab.equals("Car:")) continue;
if (!sc.hasNext()) {
break;
}
Car = sc.next();
if (!sc.hasNextInt()) {
continue;
}
int x = sc.nextInt();
if (!sc.hasNextInt()) {
continue;
}
int y = sc.nextInt();
System.out.println(car + " " + x + " " + y);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}

use nextLine() other than next(). nextLine() can consume carriage returns
next() may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
every time you invoke nextInt(), it only reads the number, and it will not consume anything after the number

Related

NoSuchElementException Problem in User Input Java

I'm confused while using an Java program I created.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
System.out.println("Your first input is " + input1);
}
Initially, when a user Ctrl+D during the input, it will promptly end the program and display an error in the form of this,
Your first input integer? ^D
Class transformation time: 0.0073103s for 244 classes or 2.9960245901639343E-5s per class
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651);
at Playground.Test1.main(Test1.java:13)
Doing a bit of research I note that Ctrl+D terminates the input of sort. Therefore, I tried add few more lines to my codes to prevent the error from appearing again and instead printing a simple "Console has been terminated successfully!" and as far as my skills can go.
public static void main(String[] args) {
Scanner scanner1 = new Scanner(System.in);
int input1 = 0;
boolean Input1Real = false;
System.out.print("Your first input integer? ");
while (!Input1Real) {
String line = scanner1.nextLine();
try {
try {
input1 = Integer.parseInt(line);
Input1Real = true;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.print("Your first input integer? ");
}
}
catch (NoSuchElementException e) {
System.out.println("Console has been terminated successfully!");
}
}
System.out.println("Your first input is " + input1);
}
In the end, I still got the same error.
Got it!, the code hasNext() will ensure that the error will not appear. This method is to check whether there is another line in the input of the scanner and to check if its filled or empty. I am also using null to check my statement after passing the loop so the program stops if the input value is still null while keeping the function of Ctrl+D.
public static void main(String[] args) {
Integer input1 = null;
System.out.println("Your first input integer? ");
Scanner scanner1 = new Scanner(System.in);
while(scanner1.hasNextLine()) {
String line = scanner1.nextLine();
try {
input1 = Integer.parseInt(line);
break;
}
catch (NumberFormatException e) {
System.out.println("Use an integer! Try again!");
System.out.println("Your first input integer? ");
}
}
if (input1 == null) {
System.out.println("Console has been terminated successfully!");
System.exit(0);
}
System.out.println(input1);
}
This solution is not prefect of course but I would appreciate if there were much simpler options.

How to get class variable file check to print line rather than throw exception

I'm trying to get a method to check for the existence of a file, and print a message that the file doesn't exist, but it also has to be a class variable rather than an instance variable.
I had it working when it was only in subString method, was not a class variable and without infix/suffix/prefix code.
Here is my code. It's still a little bit messy and no conforming to formatting convention.
Appreciate your help.
package wordgames;
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class WordGames {
private static final String DICTIONARY = "dictionary.txt";
private static String[] wordsCollection;
private static int wordCount = 0;
public static void main(String[] args) throws Exception {
wordsCollection = new String[100];
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
getSelection();
}
static String getSelection() throws FileNotFoundException {
Scanner keyboardInput = new Scanner(System.in);
System.out.println("Welcome to the Word Games program menu.");
System.out.println("Select from one of the following options.");
System.out.println("1. Substring problem.");
System.out.println("2. Points problem.");
System.out.println("3. Exit.");
System.out.println("Enter your selections: ");
String selection = keyboardInput.next();
switch (selection) {
case "1":
subStringProblem();
case "2":
pointsProblem();
case "3":
System.out.println("Good Bye!");
System.exit(0);
default:
System.out.println("Invalid option. Try again.");
getSelection();
}
return null;
}
static void subStringProblem() throws FileNotFoundException {
File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
} else {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
System.out.println("Substring problem.");
System.out.println("Enter a Substring:");
Scanner keyboardInput = new Scanner(System.in);
String subString = keyboardInput.next();
System.out.print(subString);
System.out.println();
String notFound = " - not found";
String infixFound = " - infix";
String prefixFound = " - prefix";
String suffixFound = " - suffix";
for (int i = 0; i < wordCount; i++) {
String temp = wordsCollection[i];
boolean found = false;
if (wordsCollection[i].startsWith(subString)) {
found = true;
temp = temp + prefixFound;
}
if (wordsCollection[i].endsWith(subString)) {
found = true;
temp = temp + suffixFound;
}
if (wordsCollection[i].contains(subString)) {
found = true;
temp = temp + infixFound;
}
if (!found) {
System.out.printf(" " + wordsCollection[i] + notFound + "\n");
} else {
System.out.printf(" " + temp + "\n");
}
}
getSelection();
}
private static void pointsProblem() throws FileNotFoundException {
System.out.println("Points problem.");
getSelection();
}
}
I've noticed that you have put throws FileNotFoundException in the signature of all of your functions. You only do this if you don't want to catch the exception in that function, and want the caller to be responsible for handling the exception. In your program, that is never the case, you always want to handle it immediately by exiting, so remove it from everywhere.
The part of your code that is crashing:
File fileReader = new File("DICTIONARY.txt");
Scanner fileScanner = new Scanner(fileReader);
if (fileReader.isFile() == true) {
else {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
This code will work if you remove the fileScanner. It throws an exception if the file doesn't exist, but since you're not actually using it for anything, you can just remove it. The fileReader.isFile() check will then do the job. (fileReader.exists() is closer to)
The corrected code:
File fileReader = new File("DICTIONARY.txt");
if (fileReader.exists() == false) {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
You're also reading a file in the main() function. There you're actually using the fileScanner, so this gives you a choice of either using the same check as above, or you can actually catch the FileNotFoundException this time, you could try that at least to give it a try.
try {
File fileReader = new File(DICTIONARY);
Scanner fileScanner = new Scanner(fileReader);
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
wordsCollection[wordCount] = line;
wordCount++;
}
} catch (FileNotFoundException e) {
System.out.println("File doesn't exist. Exiting.");
System.exit(0);
}
It would be good practice if within the try/catch block you actually called a function, that would make stop it from looking ugly.

About some simple exception handling in Java

There are several questions I would like to ask, please refer the comment part I have added in the code, Thanks.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
/* Task:
prompt user to read two integers and display the sum. prompt user to read the number again if the input is incorrect */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a;
int b;
while (accept_a == false) {
try {
System.out.print("Input A: ");
a = input.nextInt(); /* 1. Let's enter "abc" to trigger the exception handling part first*/
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine(); /* 2. I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it? */
}
}
while (accept_b == false) {
try {
System.out.print("Input B: ");
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) { /*3. Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception? */
System.out.println("Input is Wrong");
input.nextLine();
}
}
System.out.println("The sum is " + (a + b)); /* 4. Why a & b is not found?*/
}
}
I am still not familiar with nextLine() parameter after reading the java manual, would you mind to explain more? All I want to do is "Clear Scanner Buffer" so it wont loop for the println and ask user to input A again, is it a correct way to do it?
The use of input.nextLine(); after input.nextInt(); is to clear the remaining content from the input stream, as (at least) the new line character is still in the buffer, leaving the contents in the buffer will cause input.nextInt(); to continue throwing an Exception if it's no cleared first
Since this is similar to the above situation, is it possible to reuse the try-catch block to handling b (or even more input like c d e...) exception?
You could, but what happens if input b is wrong? Do you ask the user to re-enter input a? What happens if you have 100 inputs and they get the last one wrong?You'd actually be better off writing a method which did this for, that is, one which prompted the user for a value and returned that value
For example...
public int promptForIntValue(String prompt) {
int value = -1;
boolean accepted = false;
do {
try {
System.out.print(prompt);
value = input.nextInt();
accepted = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.nextLine();
}
} while (!accepted);
return value;
}
Why a & b is not found?
Because they've not been initialised and the compiler can not be sure that they have a valid value...
Try changing it something more like.
int a = 0;
int b = 0;
Yes, it's okay. And will consume the non-integer input.
Yes. If we extract it to a method.
Because the compiler believes they might not be initialized.
Let's simplify and extract a method,
private static int readInt(String name, Scanner input) {
while (true) {
try {
System.out.printf("Input %s: ", name);
return input.nextInt();
} catch (InputMismatchException ex) {
System.out.printf("Input %s is Wrong%n", input.nextLine());
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = readInt("A", input);
int b = readInt("B", input);
System.out.println("The sum is " + (a + b));
}
I have put comment to that question line.
package test;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean accept_a = false;
boolean accept_b = false;
int a=0;
int b=0;
System.out.print("Input A: ");
while (accept_a == false) {
try {
a = input.nextInt(); // it looks for integer token otherwise exception
accept_a = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next(); // Move to next other wise exception // you can use hasNextInt()
}
}
System.out.print("Input B: ");
while (accept_b == false) {
try {
b = input.nextInt();
accept_b = true;
} catch (InputMismatchException ex) {
System.out.println("Input is Wrong");
input.next();
}
}
System.out.println("The sum is " + (a + b)); // complier doesn't know wheather they have initialised or not because of try-catch blocks. so explicitly initialised them.
}
}
Check out this "nextLine() after nextInt()"
and initialize the variable a and b to zero
nextInt() method does not read the last newline character.

Why is my PrintWriter class not working as expected?

I have this application which prompts the user for a text file for input, from this text file, it contains strings of integers and text. And from there, it supposed to write to another text file, result.txt. Right now, as I'm still new to IO I am having problems with writing to the file although the file successfully created. The application stops right at the part after the user inputs the text file's name. So could you guys give me some help on that please? Thanks in advance!
import java.util.*;
import java.io.*;
class FileReadingExercise3 {
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do
{
try
{
System.out.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if(a.equals("QUIT"))
{
System.exit(0);
}
fileInput = new Scanner(new File(a));
}
catch(FileNotFoundException e)
{
System.out.println("Error " + a + " does not exist.");
}
}while(fileInput == null);
PrintWriter output = null;
try
{
output = new PrintWriter(new File("result.txt"));
}
catch(IOException g)
{
System.out.println("Error");
System.exit(0);
}
while(fileInput.hasNext())
{
if(fileInput.hasNextInt())
{
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
}
}
fileInput.close();
output.close();
}
}
It is stuck because you have to call the next() method after calling hasNext()so the pointer goes to next line of your input file.
Also you are not using sum so check if you need this variable.
Here is the code that works:
public static void main(String[] args) throws FileNotFoundException {
Scanner userInput = new Scanner(System.in);
Scanner fileInput = null;
String a = null;
int sum = 0;
do {
try {
System.out
.println("Please enter the name of a file or type QUIT to finish");
a = userInput.nextLine();
if (a.equals("QUIT")) {
System.exit(0);
}
fileInput = new Scanner(new File(a));
} catch (FileNotFoundException e) {
System.out.println("Error " + a + " does not exist.");
}
} while (fileInput == null);
PrintWriter output = null;
try {
output = new PrintWriter(new File("result.txt"));
} catch (IOException g) {
System.out.println("Error");
System.exit(0);
}
while (fileInput.hasNext()) {
if (fileInput.hasNextInt()) {
int num = fileInput.nextInt();
sum += num;
String str = Integer.toString(num);
output.println(str);
} else {
fileInput.next();
}
}
fileInput.close();
output.close();
}
}
Update:
As per java doc for Scanner.hasNext() method:
Returns true if this scanner has another token in its input. This
method may block while waiting for input to scan. The scanner does not
advance past any input.
So to go to the next position, you need to call the next() method, otherwise the Scanner will be at same position and the program gets stuck in infinite loop.

I'm having an issue with the delimiters in this java code?

What I'm trying to do is have this code ask for 2 integer inputs, read data from a file called 'temps.txt', and output the number of days processed, along with the average temperature processed. The problem is I'm getting this error
Input the maximum temperature.
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at TempReader.main(TempReader.java:15)
You did not input a valid integer.
whenever I try to run it. So far my code looks like this:
import java.util.Scanner;
import java.io.File;
public class TempReader{
public static void main(String[] args) throws Exception {
File myFile = new File("temps.txt");
Scanner input = new Scanner(myFile).useDelimiter(",");
while (true){
System.out.println("Input the maximum temperature.");
try {
int maxTemp = input.nextInt();
}
catch (Throwable t) {
t.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = input.nextInt();
}
catch (Throwable t) {
t.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
}
}
}
And the temps txt file looks like this
04/01/2013,10
04/02/2013,20
04/03/2013,30
04/04/2013,40
04/05/2013,50
04/06/2013,60
I've tried using both / and , as delimiters, and neither works, is it possible to have 2 of them, or am I going to have to do something else?
(Yes, I can make it do the processes I mentioned above, all I need help with is this error, as I don't know whats causing it)
Check your data file and what you are trying to read.
04/01/2013 is not an integer!
UPDATE
Use Date d = new SimpleDateFormat("MM/dd/yy").parse(input.next()); to get your date THEN get your temperature with nextInt. Also, you seem to be looking for max AND min temps in the file, but there is only one temp per day. Your attempt to read min temp will always throw an exception because it doesn't exist.
public static void main(String[] args) throws Exception {
File myFile = new File("C:/temps.txt");
Scanner input = new Scanner(myFile);
String linrread = null;
try {
while ((linrread = input.nextLine()) != null) {
System.out.println("linrread ."+ linrread);
if (linrread.indexOf(",") != -1) {
String[] split = linrread.split(",");
String date = split[0];
String temp = split[1];
System.out.println("date :" + date + " temp: " + temp);
}
}
} catch (NoSuchElementException t) {
t.printStackTrace();
System.out.println("Reached end of the file.");
}
}
this code will read your file and get the elements from the file. you have to modify this to fit into your requirement.
I know nothing about Scanner, but I know about the old-fashioned way of doing this, and, more importantly, I know how to make it work. Here's the code:
public class TempReader {
public static void main(String[] args) throws IOException {
File myFile = new File("temps.txt");
BufferedReader input = new BufferedReader(new FileReader(myFile));
String line;
while ((line = input.readLine()) != null) {
StringTokenizer tok = new StringTokenizer(line, ",");
System.out.println("Input the maximum temperature.");
try {
int maxTemp = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
System.out.println("Input the minimum temperature.");
try {
int minTemp = Integer.parseInt(tok.nextToken());
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("You did not input a valid integer.");
break;
}
}
}
}
This is a straightforward modification of your program, with BufferedReader, StringTokenizer, and Integer.parseInt used in place of Scanner, which I could never understand that well.

Categories

Resources