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

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.

Related

How to write on a .txt file? [duplicate]

This question already has answers here:
Write to text file without overwriting in Java
(9 answers)
Closed 3 years ago.
I am new to java and I am working on a program that calculates a binary number to it's base 10 equivalent and saves each valid entry on a .txt file. Problem is that each entry is being overwritten that the only one that's saved is that last one entered. Can anyone point out what i'm doing wrong? and any tips on improving the syntax in general. Much appreciated.
import java.util.Scanner;
import java.io.*;
public class BinaryNum {
public static void main(String[] args) throws IOException //for file writing
{
Scanner keyboard = new Scanner(System.in);
String userEntry;// initial input by user for binary numbers
int ValidUserEntryNum;
int Decimal;
boolean decision = false; //bool to let user choose to continue
boolean bool; //variable to check if the valid string is a binary number
//loops for when the user names a choice
while(!decision)
{
//loops for when the user enters a binary number
do {
System.out.println("Please Enter a Binary Number: ");
userEntry = keyboard.nextLine();
//check to see if input is a string of numbers
userEntry = checkEntry (userEntry);
// convert string to int
ValidUserEntryNum = Integer.parseInt(userEntry);
//bool variable to see if the number is Binary
bool = CheckIsBinary (ValidUserEntryNum);
//check to see if the number is binary
if (!bool)
{
System.out.println("** Invalid.Input Must be a Binary number **");
}
} while(bool == false); //parameter for the loop (whether the number entered was binary)
//convert binary number to decimal number
Decimal = convert(ValidUserEntryNum);
//display on console
System.out.println("You Entered: " + ValidUserEntryNum);
System.out.println("It's base 10 equivilant is: " + Decimal);
System.out.println();
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile();
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));
//to check if there is an existing file
if (fileWR.exists())
{
//writes in the file
output.write("You Entered: " + ValidUserEntryNum +"\r\n");
output.write("It's base 10 equivilant is " + Decimal +"\r\n");
output.close();
}
else //creates a new file if one doesnt already exist.
{
fileWR.createNewFile();
}
//option if the user wants to continue
System.out.println("Do you wish to continue?(yes or no):");
String st = keyboard.nextLine();
if (st.contentEquals("no"))
{
decision = true;
}
}
}
//to check if the user entered only a string of numbers (done)
public static String checkEntry (String userAnswer)
{
int UserLength = userAnswer.length();
int counter = 0;//to iterate through the string
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
while (UserLength == 0)
{
System.out.println("That is a blank");
System.out.println("Try again");
userAnswer = null;
userAnswer = keyboard.nextLine();
UserLength = userAnswer.length();
}
while (counter < UserLength)
{
if (!Character.isDigit(userAnswer.charAt(counter)))
{
System.out.println("That is not a binary number");
System.out.println("Try again");
userAnswer = null;
userAnswer = keyboard.nextLine();
UserLength = userAnswer.length();
counter = 0;
}
else
{
counter++;
}
while (UserLength == 0)
{
System.out.println("That is a blank, again");
System.out.println("Try again");
userAnswer = null;
userAnswer = keyboard.nextLine();
UserLength = userAnswer.length();
}
}
return userAnswer;
}
//method to check if the entered number is binary. (done)
public static boolean CheckIsBinary (int TrueBinary)
{
int temp;
while (TrueBinary > 0)
{
temp = (TrueBinary % 10);
if (temp != 1 && temp != 0)
{
return false;
}
TrueBinary = (TrueBinary/10);
}
return true;
}
//converts user binary to decimal
public static int convert(int ValidUserEntryNum)
{
//creating variables to convert binary to decimals
int temp = 0;
int Decimal = 0;
int power = 0;
//Convert the binary number to a decimal number
while (ValidUserEntryNum != 0)
{
temp = (ValidUserEntryNum % 10);
Decimal += temp * Math.pow(2, power++);
ValidUserEntryNum = (ValidUserEntryNum/10);
} return Decimal;
}
}
You are creating a new FileWriter and a new BufferedWriter each time inside the loop which is not necessary. You can move it outside the loop.
To make your existing code work, change
new FileWriter(fileWR)
to
new FileWriter(fileWR, true)
The second parameter passed is the append flag. From javadocs (emphasis mine)
boolean if true, then data will be written to the end of the file rather than the beginning.
It looks like you have fileWR.createNewFile(); both inside and outside the check.
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile(); <--
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));
//to check if there is an existing file
if (fileWR.exists())
Change this line:
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));
To:
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR), true);
Because the constructor you used for FileWriter defaults to overwriting.
http://tutorials.jenkov.com/java-io/filewriter.html#overwriting-vs-appending-the-file

Exception in thread "main" java.util.NoSuchElementException using java.util.Scanner [duplicate]

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I am currently facing some exceptions with my code and I am not sure how I am able to solve the errors. I am attempting to gather user input using the Scanner class Java but whenever I use it, the console displays:
1. Display Drivers
2. Import Infringement File
3. Generate Suspension Report
4. Save Driver Records
5. Exit Program
Enter a menu choice:
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.nextByte(Unknown Source)
at java.util.Scanner.nextByte(Unknown Source)
at code.Main.validateChoice(Main.java:109)
at code.Main.main(Main.java:84)
I am using Eclipse, and it is displaying that nothing in my class is actually incorrect and there are no resource leaks to my understanding which can be causing this issue. I have spent a lot of time already trying to solve the issue but I can't manage to fix it.
I tested the same code and it works perfectly on another class file, but something is interfering with it in the main file. If I reference the code statically from another class file, the issue is not resolved and the same exception message displays.
Code is below:
public class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// Determine Driver File Location
String fileLocation = "Driver.txt";
File driverFile = new File(fileLocation);
Scanner userInput = new Scanner(System.in);
// If cannot find driver file
while (!driverFile.exists()) {
System.out.println("Cannot find drivers file. \nEnter the correct file location: ");
fileLocation = userInput.nextLine(); // enter user input for file location
}
driverFile = new File(fileLocation);
userInput.close();
// Reading From Drivers
try { // Attempt to read from file
Scanner inputFile = new Scanner(driverFile);
inputFile.useDelimiter(",");
ArrayList<Driver> drivers = new ArrayList<>();
int counter = 0; // Set counter for each iteration
while (inputFile.hasNext()) {
try {
drivers.add(
new Driver(inputFile.nextInt(), inputFile.next(), inputFile.next(), inputFile.next(),
inputFile.next(), inputFile.next(), inputFile.nextShort(), inputFile.nextByte()));
// Enter correct value of last string
String temp = inputFile.nextLine();
if (temp.equals(",Valid")) {
drivers.get(counter).setLicenceStatus("Valid");
}
else if (temp.equals(",Suspended")) {
drivers.get(counter).setLicenceStatus("Suspended");
}
else { // if input was not correct, end input and show an exception has been made
System.out.println("Licence Status incorrect, bad data in file ");
break;
}
// Data check licenceClass
if (drivers.get(counter).verifyLicenceClass() == false) {
System.out.println("Licence Class incorrect, bad data in file ");
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad data in file ");
break;
} // end catch
counter++;
}
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("The driver file was not found");
} // end missing driver file catch
// Menu Items
String[] firstMenuItems = {"Display Drivers", "Import Infringement File",
"Generate Suspension Report", "Save Driver Records", "Exit Program"};
final int firstMinMenu = 1; // menu values
final int firstMaxMenu = 5;
byte choice;
do {
displayMenu(firstMenuItems);
choice = (byte) validateChoice(firstMinMenu, firstMaxMenu);
// System.out.println("Your menu choice was " + choice);
} while (choice != firstMaxMenu);
} // end main
/*
* Methods
*/
public static void displayMenu(String[] menu) {
for (int i = 0; i < menu.length; i++) {
System.out.println((i + 1) + ". " + menu[i]);
}
System.out.println("Enter a menu choice: ");
}
// Determine if choice is in range
public static int validateChoice(int min, int max) {
int input = 0;
do {
input = userInput.nextByte();
if (input < min || input > max) {
System.out.println("Please enter a menu choice in range");
}
} while (input < min || input > max);
return input;
}
}
Would appreciate any help. Thanks.
Edit: Removing the userInput.close(); near the top of the code fixed it. Also will realized I had multiple userInputs. Thanks for the replies!
You are doing numerous inputFile.next() when instantiating a new Driver. Each one consumes an element. Just assign it once to a variable at the beginning and use that one.

Exceptions and File I/O

Hello people I need help, when I run my code it outputs this :
Average = 49.91791791791792
null
empty.txt is empty
Error: notThere.txt (No such file or directory)
Average = 0.0
but my goal is to have it output this:
Average = 49.91791791791792
squeeze.txt does not have numeric data
empty.txt is empty
Error: notThere.txt (No such file or directory)
Average = 0.0
I have problems understanding this step for the assignment:
Throw the following exceptions in the scanDataAndCalculateAverage method
File is empty.
File has non-numeric data. You can assume that the data file does not have non-numeric and numeric data mixed in. This is done by checking if something was read in but the count is 0.
Can you guys help me? Here is the code:http://pastebin.com/33WCBxEf
public class Average {
long total = 0;
int count = 0;
String asd = "";
public Average(String a){
asd = a;}
public double scanDataAndCalculateAverage(){
try {
FileReader f = new FileReader(asd);
Scanner in = new Scanner(f);
while (in.hasNext()){
total += in.nextInt();
count++;
}
if(count==0 && in.hasNext() == true){
throw new IllegalArgumentException(asd + " does not have numeric data");
}
if(count == 0 && total == 0){
throw new ArithmeticException(asd + " is empty");
}
return (double)total/count;
} catch (IOException e){
System.out.println("Error: " + e.getMessage());
return 0;
}
}
}
The problem is in the while loop:
while (in.hasNext()){
total += in.nextInt();
count++;
}
This loop exits only when hasNext returns false, which meanse count==0 && in.hasNext will never be true. Probably, you want the loop to only process ints.
This might work better:
while (in.hasNextInt()){
total += in.nextInt();
count++;
}
The loop will end when there is no int - however hasNext will still be true, since there may be letters, etc in the file.
while (in.hasNextInt()){
total += in.nextInt();
count++;
}
if(count==0 && in.hasNextInt() == false){
throw new IllegalArgumentException(asd + " does not have numeric data");
}
Yeah thats most probably it. Try it!

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.

Java CSV read file validation doesnt work

Background : The code is supposed to go through a csv file (second link), find the username and password and either confirm and display all the info or write error. But now it only says error. Cheers in advance.
http://pastebin.com/YBpKRKe2
http://pastebin.com/9K3nwYG3
import java.io.*;
import java.util.*;
public class CSVRead
{
public static void main(String[] args)
throws Exception
{
BufferedReader CSVFile =
new BufferedReader(new FileReader("test123.csv"));
int invalidvar = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter your email");
String email =input.nextLine();
System.out.println("Enter your password");
String password =input.nextLine();
String dataRow = CSVFile.readLine(); // Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.
while (dataRow != null)
{
String[] dataArray = dataRow.split("\\t");
if ((dataArray[0].equals(email))
&&(dataArray[1].equals(password)))
{
System.out.println("You email is " +dataArray[0]+".");
System.out.println("You password is " +dataArray[1]+".");
System.out.println("You first name is " +dataArray[2]+".");
System.out.println("You second name is " +dataArray[3]+".");
System.out.println("You street name is " +dataArray[4]+".");
System.out.println("You city name is " +dataArray[5]+".");
System.out.println("You postcode is " +dataArray[6]+".");
}
else
{
System.out.println("Error");
break;
}
dataRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
// End the printout with a blank line.
System.out.println();
} //main()
} // CSVRead
You are only checking the first record after the CSV header. You need to continue checking the records until the EOF is reached:
boolean found = false;
while (!found && dataRow != null) {
String[] dataArray = dataRow.split("\\t");
if ((dataArray[0].equals(email)) && (dataArray[1].equals(password))) {
System.out.println("You email is " + dataArray[0] + ".");
...
found = true;
}
dataRow = csvFile.readLine();
}
System.out.println("Result of CSV search: " + found);
Some side notes:
IO Streams should be closed in a finally block.
Java Naming Conventions indicate variables should start with a lowercase letter.

Categories

Resources