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

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.

Related

Exception in thread ... : null - trying to convert String from file to Integer

like in the title , I'm stuck with this error for a while .I get the value from the file normally but when I try to convert it the error poops out. I read many topics ,but couldn't find any similar case to mine(with file) or any good tips. I tried adding an assert ,but it didn't help. The full description of error is :
Exception in thread "main" java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:620)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at EnergyMeasure_needs_to_be_completed.main(EnergyMeasure_needs_to_be_completed.java:85)
Also I'm beginner (but I guess you already know that heh ;))
import java.util.Scanner;
import java.io.*;
public class EnergyMeasure_needs_to_be_completed {
public static void main(String[] args) throws IOException {
//int work_of_energy;
Scanner input = new Scanner(System.in);
System.out.println("\t\t\t\t Hi , this program will count how many kWh you're using");
//asks about number of devices
System.out.println("First of all, how many the same devices do you have in your house ?");
int devices = input.nextInt();
boolean bool = false;
do {
if (devices < 0) {
System.out.println("You can't have less than 0 devices in your home!\nMake input once again :");
devices = input.nextInt();
} else {
System.out.println("Okay, so you've got " + devices + " same devices.");
bool = true;
break;
}
}while(bool = true);
//asks about time of use
System.out.println("\nHow many hours you use them per day?");
int time_use = input.nextInt();
do {
if (time_use > 24 || time_use < 0) {
System.out.println("Wrong!\nMake input once again :");
time_use = input.nextInt();
}
else{
System.out.println("You use your devices for " + time_use + "h");
bool = true;
break;
}
}while(bool = true);
/*else if(!input.hasNextInt()){
System.out.println("Invalid input! \nEnter an integer : ");
time_use = input.nextInt();
} */
//downloads value of power from file
String power_dev; //path to the file
power_dev = null; //reference to one line at a time
try {
FileReader fileReader = //reads text files in the default encoding
new FileReader("power_monitors");
BufferedReader bufferedReader = //deal with a line at a time
new BufferedReader(fileReader);
while((power_dev = bufferedReader.readLine()) != null) {
System.out.println("\nThe power of your devices is " + power_dev + "W");
}
bufferedReader.close(); //close file
}
catch (FileNotFoundException e) { //if file doesn't exist catch the except
System.out.println("Unable to open file");
}
//assert power_dev != null;
int power_dec = Integer.parseInt(power_dev); //change the String ,to Integer
int power_of_devices = power_dec * devices; //summary devices power
//count the cost of work (W = P * t) [kWh]
int work_of_energy = (power_of_devices / 1000) * time_use;
System.out.println("The work of energy equals : " + work_of_energy);
}
}
If you print power_dev, what do you get? What format is it? Because the readLine() returns a textual line, so depending on the source you are reading from, you might get more than an int.
Why not use the read() method? It returns an int, so you wouldn't have to parse power_dev.
Again, hard to answer your question without seeing the file or having a reproductible code, but my best guess is that power_dev returns null or something that can't be parsed by Integer.parseInt() method.

Read from file not Printing to Output

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

Exception Handling Help (Java)

Trying to grasp exception handling, but I'm not sure I understand just yet. What SHOULD be happening is if the user inputs something other than an integer, the mismatchexception should execute and print that friendly message. Also, on the topic of exception handling, if my code has any useless exceptions in it, let me know (and why if you don't mind). Full code linked below. Thanks!
public static void addRecords() {
System.out.print("Hello, welcome to my magical program!\n");
for (int i = 0; i < 10; i++) {
System.out.printf("Please enter integer no. %d: ", i + 1);
numbers[i] = input.nextInt();
System.out.println();
{
try {
output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
} catch (FormatterClosedException formatterClosedexception) {
System.err.println("Error writing to the file. Terminating.");
break;
} catch (InputMismatchException inputMismatchException) {
System.err.println("Please restart the program and enter integers ONLY.");
break;
} catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
}
}
}
Full code here:
http://pastebin.com/eSGau5ax
I would suggest to throw the exception from the methods and catch them in the main method. The methods should not decide what to do with the exceptions, its upto the caller (main method in this case) to decide whether to print it or log it in a file.
Firstly,
java.util.InputMismatchException happens for your data file numbers.txt not containing integer type data. Please input relative data. It will solve this inputmismatchexception.
For your better understanding, follow the tutorial:
https://examples.javacodegeeks.com/java-basics/exceptions/java-util-inputmismatchexception-how-to-solve-inputmismatchexception/
Next,
Use this code. It may help you.
Actually what you have posted in http://pastebin.com/eSGau5ax.
There are 2 errors.
First one error occurred in
try (BufferedReader br = new BufferedReader (new FileReader("numbers.txt"))){
But I changed it like that because there was some error.
try{
BufferedReader br = new BufferedReader (new FileReader("numbers.txt"));
Another error was related to taking input section must be in try catch. But I have not run your code. All credit goes to other SO helpers.
numbers[i] = input.nextInt();
Now your code is looks like
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.nio.file.NoSuchFileException;
public class Average {
private static Formatter output;
static Scanner input = new Scanner(System.in);
static int[] numbers = new int[10];
public static void main(String[] args) {
openFile();
addRecords();
closeFile();
readRecords();
}
public static void openFile() {
try {
output = new Formatter("numbers.txt");
} catch (SecurityException securityException) {
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} catch (FileNotFoundException fileNotFoundException) {
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
public static void addRecords() {
System.out.print("Hello, welcome to my magical program!\n");
try {
for (int i = 0; i < 10; i++) {
System.out.printf("Please enter integer no. %d: ", i + 1);
numbers[i] = input.nextInt();
System.out.println();
output.format("Inputted integer: %s%n", String
.valueOf(numbers[i]));
}
} catch (FormatterClosedException formatterClosedexception) {
System.err.println("Error writing to the file. Terminating.");
break;
} catch (InputMismatchException inputMismatchException) {
System.err
.println("Please restart the program and enter integers ONLY.");
break;
} catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
}
public static void closeFile() {
{
if (output != null)
output.close();
}
}
public static void readRecords() {
try {
BufferedReader br = new BufferedReader(
new FileReader("numbers.txt"));
String line;
int[] number = new int[10];
int i = -1;
int sum = 0;
double average = 0;
while ((line = br.readLine()) != null) {
i++;
String[] split = line.split(":");
line = split[1].trim();
number[i] = Integer.parseInt(line);
System.out.printf("Integer number %d: %d%n", i, numbers[i]);
sum += number[i];
average = (double) sum / 10;
}
System.out.printf("%nWould your sum happen to be %d? %n", sum);
System.out.printf("Which means your average is: %.2f %n", average);
} catch (NoSuchFileException noSuchFileException) {
System.out
.print("This file was not created properly and cannot be found.");
} catch (FileNotFoundException fileNotFoundException) {
System.out
.print("I can't seem to find your file :( That's too bad...");
} catch (IOException ioexception) {
System.out
.print("Whoopsie daisy, you got yourself an IOException. Better luck next time!");
} finally {
System.out
.print("Check your numbers.txt file and see what ya got!");
}
}
}
You are trying to catch an Exception that happened outside of the try.
Just get the nextInt inside the try
public static void addRecords() {
System.out.print("Hello, welcome to my magical program!\n");
for (int i = 0; i < 10; i++) {
System.out.printf("Please enter integer no. %d: ", i + 1);
System.out.println();
{
try {
numbers[i] = input.nextInt();
output.format("Inputted integer: %s%n", String.valueOf(numbers[i]));
} catch (FormatterClosedException formatterClosedexception) {
System.err.println("Error writing to the file. Terminating.");
break;
} catch (InputMismatchException inputMismatchException) {
System.err.println("Please restart the program and enter integers ONLY.");
break;
} catch (NoSuchElementException elementException) {
System.err.println("Invalid input. Please try again.");
input.nextLine();
}
}
}
}

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.

Java: Beginner using Scanner

I am learning Java and am learning I/O w/ java.util.Scanner. Specifically I am learning Scanner methods.
import java.util.Scanner;
public class ScannerTest {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int result;
while (s.hasNextInt()) {
result += s.nextInt();
}
System.out.println("The total is " + result);
}
}
Because you're checking only
while (s.hasNextInt())
You could use try catch to catch the exception (see documentation here) you get when the program quits, so you can show your error message in the catch block without making the program close.
Perhaps you should try parsing each line:
public static void main(String args[]){
int sum = 0;
final Scanner scanner = new Scanner(System.in);
System.out.println("Enter a series of integers. Press 'q' to quit.");
while(true){
final String line = scanner.nextLine();
if(line.equals("q"))
break;
try{
final int number = Integer.parseInt(line);
sum += number;
}catch(Exception ex){
System.err.printf("Invalid: %s | Try again\n", ex.getMessage());
}
}
System.out.printf("The sum is %,d" , sum);
}
The idea is to read input line by line and attempt parsing their input as an integer. If an exception is thrown (meaning they entered an invalid integer) it would throw an exception in which you could handle in what ever way you want to. In the sample above, you are simply printing the error message and prompting the user to type in another number.
You can do this for the while loop (not tested though):
while (s.hasNextLine()) {
String line = s.nextLine();
int parsedInteger;
try {
parsedInteger = Integer.parseInt(line);
} catch(NumberFormatException numEx) {
if(line.startsWith("q")) break;
else {
System.out.println("please enter valid integer or the character 'q'.");
continue;
}
}
result += parsedInteger;
}
s.close();
Instead of scanning for int's you can scan for lines and then then parse each line as an int. I feel the advantage of this approach is that if any of your int's are malformed you can then handle them appropriately by say displaying an error message to the user.
OR, based on the answer by pinckerman, you can also do this.
while (s.hasNextInt()) {
try {
result += s.nextInt();
} catch(InputMismatchException numEx) {
break;
}
}
s.close();
A smart way you can do it and I've tried before is you use Integer.parseInt(String toParse); This returns an int and will reject all non numerical chars.
while (scanner.hasNextInt()) {
int i = Integer.parseInt(scanner.nextInt());
result += i;
if (result < 2147483648 && result > -2147483648) {
try{
throw new IndexOutOfBoundsException();
catch (Exception e) {e.printStackTrace();}
}
Try the following way:
int result = input.nextInt;
this will define your variable for result.
The only problem in your code is "not initializing" result. Once you initialized code will work properly. However, please do not forget you need to tell compiler EOF. Compiler can only understand the stop of the input on the console by EOF. CTRL Z is EOF for windows Eclipse IDE.

Categories

Resources