Java won't read an int from a file - java

i tried reading a string from a file and it worked just fine but it won't work with an integer. i can't seem to find the problem
public static void main(String[] args) throws FileNotFoundException {
File in = new File ("FCITsamba.in.rtf");
Scanner scanner = new Scanner(in);// Scanner variable to read from the input file
File outFile = new File("FCITsamba.txt");// the out file
PrintWriter out = new PrintWriter(outFile); // Printwriter to write to the file
int maxAccounts = 0;//maximum number of accounts that can be in the bank
int maxTransactions = 0;//maximum number of transactions in a given day
int accNum = 0;
int transNum = 0;
int d = 0;
int k = 0;
int dayNo = 1;
if (!in.exists()) {
System.out.println("Input file, " + in + ", does not exist.");
System.exit(0);
}
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
it gives me 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.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at fcitsamba.FCITsamba.main(FCITsamba.java:43)
Java Result: 1
i tried putting an inputMismatchException but it didn't work i also tried putting it in an if statement as shown below:
if(scanner.hasNextInt()){
maxAccounts = scanner.nextInt();
maxTransactions = scanner.nextInt();
d = scanner.nextInt(); //representing the number of days for the simulation
k = scanner.nextInt();
}
but it didn't work as well
this is the input File :
200
10000
2
11
OPENACCOUNT 1485 Aslam Saeed 2000.0
DEPOSIT 1485 1000.0
...

When you read from a file, it won't recognize whether it is reading numbers or strings, hence everything will be treated as strings including what is shown in your data file (200, 10000, 2, 11).
Instead of writing:
d = scanner.nextInt();
Try this:
d = Integer.parseInt(scanner.nextLine());

Scanner reads 1 value at a time, so if the next value you are trying to read is not an int it will throw an error.
I used your data and the following worked for me:
public static void main(String[] args) {
//Replace FILE_PATH with your file path.
try {
Scanner reader = new Scanner(new File("FILE_PATH/fromFile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/toFile.txt"));
int maxAccounts = reader.nextInt();
int maxTransactions = reader.nextInt();
int d = reader.nextInt();
int k = reader.nextInt();
writer.println("maxAccounts: " + maxAccounts);
writer.println("maxTransactions: " + maxTransactions);
writer.println("d: " + d);
writer.println("k: " + k);
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}

Related

need help about reading numbers inside file

First I create a txt file (a.txt) -- DONE
create 10 random number from - to ( like from 5 -10 ) --DONE
I write this number in txt file --DONE
I want to check its written or not -- DONE
Now I need to find: how many number, biggest, smallest, sum of numbers
But I can not call that file and search in the file (a.txt). I am just sending last part. Other parts work. I need some help to understand. It is also inside another method. not main
Scanner keyboard = new Scanner(System.in);
boolean again = true;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int a = 0;
int count = 0;
System.out.println("Enter the filename to write into all analysis: ");
outputFileName = keyboard.nextLine();
File file2 = new File(outputFileName);
if (file2.exists()) {
System.out.println("The file " + outputFileName +
" already exists. Will re-write its content");
}
try {
PrintWriter yaz = new PrintWriter(file2);
// formulas here. created file a.txt need to search into that file biggest smallest and sum of numbers
yaz.println("Numeric data file name: " + inputFileName);
yaz.println("Number of integer: " + numLines);
yaz.println("The total of all integers in file: " + numLines); //fornow
yaz.println("The largest integer in the set: " + max);
yaz.println("The smallest integer in the set " + min);
yaz.close();
System.out.println("Data written to the file.");
} catch (Exception e) {
System.out.printf("ERROR reading from file %s!\n", inputFileName);
System.out.printf("ERROR Message: %s!\n", e.getMessage());
}
So you want a code to read a text file and give you the biggest, smallest and the average.
You can use Scanner class for that and use hasNextInt() to find integers
File f = new File("F:/some_text_file.txt"); // input your text file here
if(f.exists()){
try{
Scanner sc = new Scanner(f);
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int temp=0, i=0;
double sum=0;
while(sc.hasNextInt()){
temp = sc.nextInt();
if(temp>max) max = temp;
if(temp<min) min =temp;
sum+=(double) temp;
i++;
}
System.out.println("average : " +sum/i);
System.out.println("large : "+max);
System.out.println("small :"+min);
sc.close();
}catch(Exception e){
e.printStackTrace();
}
}
See if this works
You need to read the file into memory. One way to do that is to move the text of the file into a String.
This post will help you: Reading a plain text file in Java
Here's the relevant code:
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}

(Java) Trying to figure out how to read from a .txt file

I'm quite new to Java and I have a project, I'm trying to create my own text file and then print numbers from my program to the textfile.
Then I want the software to read the numbers afterwards again and show what of the numbers that is the biggest one.
So far this is what I've done:
String fil = "C:\\Java\\Test.txt";
BufferedWriter fout = new BufferedWriter(new FileWriter(fil, true));
Scanner in = new Scanner(System.in);
System.out.print("Skriv in tre tal: ");
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
fout.write(x + " " + y + " " + z);
fout.newLine();
fout.flush();
BufferedReader fin = new BufferedReader(new FileReader(fil));
String s = fin.readLine();
System.out.println(s);
I just don't know how to make my software find the biggest number in the code and then print it out.
Thanks in advance
/Fsociety1337
A complete solution would be:
public class LargestNumberFinder {
public static final String FILENAME = "C:\\Java\\Test.txt";
public static void main(String[] args) throws IOException {
BufferedWriter fout = new BufferedWriter(new FileWriter(FILENAME, true));
Scanner in = new Scanner(System.in);
System.out.print("Skriv in tre tal: ");
int x = in.nextInt();
int y = in.nextInt();
int z = in.nextInt();
fout.write(x + " " + y + " " + z);
fout.newLine();
fout.flush();
BufferedReader fin = new BufferedReader(new FileReader(FILENAME));
String s = fin.readLine();
System.out.println(s);
int largest = getLargestNumberFromFile(FILENAME);
System.out.println("The largest number is: " + largest);
}
private static int getLargestNumberFromFile(String filename) throws FileNotFoundException {
int largest = -1;
Scanner scanner = new Scanner(new File(filename));
scanner.useDelimiter(" |[\\r\\n]+");
while(scanner.hasNext()) {
int currentNumber = scanner.nextInt();
if (currentNumber > largest) {
largest = currentNumber;
}
}
scanner.close();
return largest;
}
}
Split the reponded String into 3 Integer variables and just compare them.

Reading space separated numbers from a file

I'm on my winter break and trying to get my Java skills back up to snuff so I am working on some random projects I've found on codeeval. I'm having trouble opening a file in java doing the fizzbuzz program. I have the actual fizzbuzz logic part down and working just fine, but opening the file is proving problematic.
So presumably, a file is going to be opened as an argument to the main method; said file will contain at least 1 line; each line contains 3 numbers separated by a space.
public static void main(String[] args) throws IOException {
int a, b, c;
String file_path = args[0];
// how to open and read the file into a,b,c here?
buzzTheFizz(a, b, c);
}
You can use the Scanner like so;
Scanner sc = new Scanner(new File(args[0]));
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
By default scanner uses whitespace and newline as seperators, just what you want.
try {
Scanner scanner = new Scanner(new File(file_path));
while( scanner.hasNextInt() ){
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
buzzTheFizz( a, b, c);
}
} catch( IOException ioe ){
// error message
}
Using a loop it reads the whole file, have fun:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a = 0;
int b = 0;
int c = 0;
String file_path = args[0];
Scanner sc = null;
try {
sc = new Scanner(new File(file_path));
while (sc.hasNext()) {
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
System.out.println("a: " + a + ", b: " + b + ", c: " + c);
}
} catch (FileNotFoundException e) {
System.err.println(e);
}
}
}

Prompting a user for file name

I am attempting to learn how to prompt users to enter a file name, rather than predefining it, so that Java can go through with the Scanner and read through it. I have written a program that does what I need it to do, but only when the file in question is predefined.
I have looked around the site for duplicate questions, and found a few, but the scope in which it was asked was a bit more advanced than where I am. Can anyone offer me a bit of guidance on how to prompt a user to enter the file he/she wants, as opposed to predefining it (as code below is set to).
Note - This was written assuming the files read in had integers < 0 and > 0, hence why the min/max functions were done in the way they were...simply trying to teach myself one step at a time.
import java.io.*;
import java.util.*;
public class ProcessNumbers {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("inputdata.txt"));
int max = 0;
int min = 0;
int sum = 0;
int count = 0;
double average = 0;
System.out.println("Enter file name: "); //currently a println for ease of reading via Run
while (input.hasNext()) {
if (input.hasNextInt()) {
int number = input.nextInt();
sum += number;
count++;
average = (double) (sum) / count;
if (number > max) {
max = number;
}
if (number < min) {
min = number;
}
} else {
input.next();
}
}
System.out.println("Maximum = " + max);
System.out.println("Minimum = " + min);
System.out.println("Sum = " + sum);
System.out.println("Count = " + count);
System.out.println("average = " + average);
}
}
Try this:
System.out.println("Enter file name: ");
Scanner fileNameScanner = new Scanner( System.in );
String fileName = "";
if ( fileNameScanner .hasNext() ) {
fileName = fileNameScanner.next();
}
...
Using the fileName string, create a File object and use as per your requirements.
Easiest way would be to replace
new File("inputdata.txt")
with
new File(args[0])
This way the first command-line argument will be treated as a filename.
You can use Scanner to read a input from user (it doesn't only read from a File):
Scanner prompt = new Scanner(System.in);
System.out.print("Enter name of the file: ");
String name = prompt.next(); // enter "inputdata.txt"
Scanner input = new Scanner(new File(name));
// ...
Another approach would be to use the Console.
You substitute your scanner to read from a File returned from a new method:
Scanner input = new Scanner(getFileFromUser());
...
private static File getFileFromUser() {
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String filePathname = c.readLine("Enter file pathname: ");
return new File(filePathname);
}
Also don't forget to close your scanner in the end of main method to avoid resource leak:
input.close();

Java Beginning - Scanner Class Error

I'm doing some homework where we have to use the Scanner class. I was able to use it to read in a String, an int, and a float. When I moved to the next phase (the class below) I suddenly am not able to use scanner the way I had before. I did indeed close any other scanner object I created and opened. Thank you for any help.
Why does this code: (nextLine() also does not work)
import java.io.*;
import java.util.Scanner;
public class Grades {
private int len;
private String [] gradeNames;
private int [] gradeArray;
private int enterGradeNames(){
Scanner input = null;
input = new Scanner(System.in);
for (int i = 0; i < len; ++i){
System.out.println("Enter the type of grades you will be reporting: (" +
(i + 1) + " of " + gradeArray.length + ")" );
gradeNames[i] = new String(input.next() );
}
input.close();
return 0;
}
protected int displayGradeNames(){
System.out.println("Type of Grades tracking");
for (int i = 0; i < len; ++i)
System.out.println(gradeNames[i]);
return 0;
};
public Grades(){
len = 0;
Scanner input = null;
input = new Scanner(System.in);
System.out.println("Enter the size of the grade array to be created");
len = 4;
gradeArray = new int[len];
gradeNames = new String[len];
input.close();
enterGradeNames();
}
}
give me this errror:
Enter the type of grades you will be reporting: (1 of 4)
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Grades.enterGradeNames(Grades.java:14)
at Grades.(Grades.java:34)
at Demo1.main(Demo1.java:32)
** Oh.. i should mention that it doesn't even give the option to input data before throwing the error
The problem is in your enterGradeNames() method with:
input.next()
You have to first call input.hasNext();
From documentation:
Throws:
NoSuchElementException - if no more tokens are available.
EDIT: as per comments
I am unable to reproduce the problem, but there are many unnecessary lines in your code, so try running this edited code and see whether it changes anything.
public class Grades {
private int len;
private String [] gradeNames;
private int [] gradeArray;
private int enterGradeNames(){
Scanner input = new Scanner(System.in);
for (int i = 0; i < len; i++){
System.out.println("Enter the type of grades you will be reporting: (" +
(i + 1) + " of " + gradeArray.length + ")" );
gradeNames[i] = new String(input.next());
}
return 0;
}
public Grades(int length){
this.len = length;
gradeArray = new int[len];
gradeNames = new String[len];
}
It's not generally good choice to call non-static methods inside constructor as the object isn't finished yet. You could do this in a (factory) method instead:
public static Grades buildGrades(){
Scanner s = new Scanner(System.in);
System.out.println("Enter size:");
int size = s.nextInt();
Grades grades = new Grades(size);
grades.enterGradeNames();
return grades;
}
EDIT2:
I searched a bit and the problem might be with your closing of the Scanner. Because if you call close on the Scanner, it will look whether its stream implements Closeable and if so it will close it as well. I never thought System.in would be closeable, but it is.
So the best option? Possibly use one Scanner for the whole program OR just don't close it if you dont want its stream to be closed. More can be read here.
try it with this:
public Grades(){
len = 0;
Scanner input = null;
input = new Scanner(System.in);
System.out.println("Enter the size of the grade array to be created");
len = 4;
gradeArray = new int[len];
gradeNames = new String[len];
enterGradeNames();
input.close();
}
I removed from your "Grades" Constructor the input reference because it is useless to do it twice (at enterGradeNames you initilize it again).
The problem was you closed the resource at the constructor and then tried to recreate it again.
public Grades(){
len = 0;
System.out.println("Enter the size of the grade array to be created");
len = 4;
gradeArray = new int[len];
gradeNames = new String[len];
enterGradeNames();
}

Categories

Resources