Int values not reading in from file - java

So I am trying to read values in from a txt file and add them to an ArrayList. I use the following code but immediately after using it the ArrayList is still empty when I use System.out.print(list). Are there any easy to spot mistakes?
ArrayList<Integer> list = new ArrayList<>();
Scanner in = null;
try{
String fname = "p01-runs.txt";
in = new Scanner(new File(fname));
}catch (FileNotFoundException pExcept){
System.out.println("Sorry, the File you tried to open does not exist. Ending program.");
System.exit(-1);
}
while (in.hasNextInt())
{
int x = in.nextInt();
list.add(x);
}
edit: input file is just a txt file with integer values as follows:
2 8 3
2 9
8
6
3 4 6 1 9

A call to hashNextInt() can return false for a number of reasons, including:
there is no more input, or
the next token on the input stream is not a valid integer.
These could be due to an empty input file, or to a mismatch between the file's format and the way you are trying to read it.
In your example, it is also possible that some IOException apart from FileNotFoundException is being thrown.
UPDATE - The problem is something that you are not telling / showing us. Consider this ... using your code and your input file.
[stephen#blackbox tmp]$ cat Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
Scanner in = null;
try{
String fname = "test.txt";
in = new Scanner(new File(fname));
}catch (FileNotFoundException pExcept){
System.out.println("Sorry, the File you tried to open does not exist. Ending program.");
System.exit(-1);
}
while (in.hasNextInt())
{
int x = in.nextInt();
list.add(x);
}
System.out.println("Read " + list.size() + " numbers");
}
}
[stephen#blackbox tmp]$ cat test.txt
2 8 3
2 9
8
6
3 4 6 1 9
[stephen#blackbox tmp]$ javac Test.java
[stephen#blackbox tmp]$ java Test
Read 12 numbers
[stephen#blackbox tmp]$

Related

How to detect line feed in between two Strings or int using scanner?

Question:
I have this set of number in a .txt document, I want to use java.util.Scanner to detect the line feed in between 123, 456, and 789, print out the numbers in between the line feeds, is there any way to do so?
1 2 3
// \n here
4 5 6
// \n here
7 8 9
Output:
456
===========================================================================
Solutions that I tried:
(1) I tried using hasNextLine() method, however, it seems like hasNextLine() will tell me are there tokens in the next line and return a boolean instead of telling me is there \n. if (scan.hasNextLine()) { \\ do something }
(2) I also tried using: (However, using such condition will say "Syntax error on token 'Invalid Character'")
Scanner scan = new Scanner(new File("test.txt"));
// create int[] nums
while (scan.hasNext()) {
String temp = scan.next();
if (temp == \n) {
// nums.add(); something like this
}
}
System.out.print(nums); // something like this
I am thinking using \n as delimiters
ps. I did google and most of the results tell me to use .hasNextLine(), but I want it to identify a line feed (\n)
Scanner scans the next element by using new-line or whitespace as a delimiter by default. To let it read the whole content use scan.useDelimiter("\\Z").
Scanner scan = new Scanner(new File("test.txt"));
scan.useDelimiter("\\Z");
final String content = scan.next(); // content: "1 2 3\r\n\r\n4 5 6"
int index = 0;
System.out.println("Index of \\n");
while (index != -1) {
index = content.indexOf("\n", index);
if (index != -1) {
System.out.println(index);
// Or do whatever you wish
index++;
}
}
Output:
Index of \n
5
7
I'm not sure I understand 100% your question. So I'm assuming your file always will have 2 lines separated by ONLY ONE new line(\n). If I'm wrong please tell it.
String charsAfterNewLine = null;
//try-catch block with resources
//Scanner need to be closed (scan.close()) after finish with it
//this kind of block will do `scan.close()` automatically
try(Scanner scan = new Scanner(new File("test.txt"))){
//consume(skip) first line
if(scan.hasNextLine()){
scan.nextLine();
}else{
throw new Exception("File is empty");
}
//get second line
if(scan.hasNextLine()){
charsAfterNewLine = scan.nextLine();
}else{
throw new Exception("Missing second line");
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("charsAfterNewLine: " + charsAfterNewLine);
If you want simple way, without try-catch:
String charsAfterNewLine = null;
//throws FileNotFoundException
Scanner scan = new Scanner(new File("test.txt"));
if(scan.hasNextLine()){
//consume(skip) first line
scan.nextLine();
if(scan.hasNextLine()){
//get second line
charsAfterNewLine = scan.nextLine();
}else{
System.out.println("Missing second line");
}
}else{
System.out.println("File is empty");
}
scan.close();
System.out.println("charsAfterNewLine: " + charsAfterNewLine);
Results(for both):
Input:
(empty file)
Output:
File is empty
charsAfterNewLine: null
-----
Input:
1 2 3 4 5 6
Output:
Missing second line
charsAfterNewLine: null
-----
Input:
1 2 3\n4 5 6
Output:
charsAfterNewLine: 4 5 6
while (scanner.hasNext()) {
String data = scanner.nextLine();
System.out.println("Data: " + data);
if (data.isEmpty()) {
System.out.println("Found it");
break;
}
}

How can I use a scanner to read in integers, more specifically an integer describing a matrix dimension followed by the integers in the matrix?

I can't get my scanner to read in the integer from a text file.
The file looks something like this (a matrix size followed by a matrix)
3
0 1 1
1 1 1
1 0 0
These two methods belong to ReadMatrix
public void openFile() {
try {
scanner = new Scanner(System.in); // create a scanner object
System.out.println("File to read: ");
fileName = scanner.nextLine(); // get name of file
System.out.println("File " + fileName + " is opened.");
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
System.out.println("can't find the funky file");
}
}
public int readInteger() {
sc = new Scanner(System.in);
// while(sc.hasNextInt()){
// sc.nextLine();
anInt = sc.nextInt();
System.out.println("Trying to read integerrrrrr help");
// }
return anInt;
}
Here are 2 classes
public class MainMethodHere {
public static void main(String[] args) {
// TODO Auto-generated method stub
RunMainMethod running = new RunMainMethod();
}
}
public class RunMainMethod {
ReadMatrix a = new ReadMatrix();
public RunMainMethod(){
a.openFile();
a.createFile();
System.out.println("just createdFile"); //<--- this is where the program ends
a.readInteger();
System.out.println("just readInteger");
a.helpMeWrite();
System.out.println("Just write sample ");
a.closeResources();
}
}
Writing to the file works fine, but I can't get the program to read the given text file to start the manipulation.
I tried finding the solutions in a few SO posts: how to read Integer from a text file in Java
Reading numbers from a .txt file into a 2d array and print it on console
How to read integer values from text file
I also tried ReadFile() and WriteFile(), but when I try to track my code via printing into the console, my simple integers shows up as different values. Is that something related to bytes? So I try reverting back to using a scanner, but somehow it's not working. Please let me know if I should clarify something further. I am new to coding and SO.

Error using Substring : String Index out of range : -1 *Java*

In this program I am just getting input from a file and trying to get the boys name and the girls name out of it, and also put them in separate files. I have done everything just as the book has stated. And I've also searched everywhere online for help with this but cant seem to find anyone with the same problem. Ive seen problems where its not -1 but a positive number because they went to far out of the string calling a substring over the strings length. But cant seem to figure out this giving me -1 since i's value is 1.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Homework_11_1 {
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
int i = 0;
int b = 0;
int g = 0;
while(!Character.isWhitespace(line.charAt(i))){ i++; }
while(Character.isLetter(line.charAt(b))){ b++; }
while(Character.isLetter(line.charAt(g))){ g++; }
String rank = line.substring(i);
String boysNames = line.substring(i, b);
String girlsNames = line.substring(b, g);
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
}
Here is the txt file
1 Jacob Sophia
2 Mason Emma
3 Ethan Isabella
4 Noah Olivia
5 William Ava
6 Liam Emily
7 Jayden Abigail
8 Michael Mia
9 Alexander Madison
10 Aiden Elizabeth
I would have written it an other way, using split.
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
String[] names = line.split(" "); // wile give you [nbr][boyName][GirlName]
String boysNames = names[1];
String girlsNames = names[2];
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
Rather than fuss with loops and substring(), I'd just use String.split(" "). Of course, the assignment may not permit you to do this.
But anyway, without giving you the answer to the assignment, I can tell you that your logic is wrong. Walk through it and find out why. If you try running this code on just the first line of the input file, you'll get these values: i=1, b=0, and g=0. Calling line.substring(1,0) is obviously not going to work.

Java Array parsing

I have read a file into an array but am wondering how to parse certain values from that array.
My code:
...
try{
...
String strLine;
String delims= "[ ]+";
//parsing it
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
System.out.println("Length:" + parsedit.size());
in.close();
...
The files that I am reading in are like this:
a b c d e f g
1 2 3 4 5 6 7
1 4 5 6 3 5 7
1 4 6 7 3 2 5
Which makes the output like this:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
Length:4
I would like to parse out this data and just have the first and fifth values remaining, so that it would read like this instead:
a e
1 5
Does anyone have a recommendation on how to go about it?
EDIT:
Following some of the suggestions I have changed my code to:
public static void main(String[] args) {
System.out.print("How many files will be input? ");
Scanner readIn=new Scanner(System.in);
int input=readIn.nextInt();
int i=1;
while(i<=input){
System.out.println("Hey, please write the full path of the input file number" + i + "! ");
Scanner fIn=new Scanner(System.in);
String fileinput=fIn.nextLine();
try{
FileInputStream fstream=new FileInputStream(fileinput);
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String strLine;
String delims= "[ ]+";
ArrayList parsedit = new ArrayList();
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
String[] splits=strLine.split(delims);
System.out.println("Length:" + splits.length);
in.close();
}
catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
i++;
}
}
}
This doesn't give back any errors but it doesn't seem to be working all the same. Am I missing something silly? The output is this:
How many files will be input? 1
Hey, please write the full path of the input file number1!
/home/User/Da/HA/file.doc
Being read:
a b c d e f g
Being read:
1 2 3 4 5 6 7
...
But despite the fact that I have a line to tell me the array length, it never gets printed, which tells me I just ended up breaking more than I fixed. Do you know what it is that I may be missing/forgetting?
The split() function returns an array of strings representing the tokens obtained from the original String.
So, what you want is to keep only the first and the 5th token (splits[0] & splits[4]):
String[] splits = strLine.split(delims);
//use the splits[0] & splits[4] to create the Strings you want
Regarding your update, replace this:
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
System.out.println(strLine);
parsedit.add(strLine.split(delims));
}
With this:
while((strLine=br.readLine())!=null){
System.out.println("Being read:");
String splits[] = strLine.split(delims);
System.out.println(splits[0]+" "+splits[4]);
parsedit.add(splits);
}
You can try this
String[] line = s.split("\\s+");
This way all your elements will be stored in a sequence in the array line.
This will allow you to access whatever element you want.
You just need to get the first and the fifth value out of the String[] returned by strLine.split(delims).
(I am assuming you know what you are doing in your current code. You are assuming that each line will contains the same number of "columns", delimited by at least 1 space character. It is a fair assumption, regardless.)

java: Read text file and store the info in an array using scanner class

I have a text file include Student Grades like:
Kim $ 40 $ 45
Jack $ 35 $ 40
I'm trying to read this data from the text file and store the information into an array list using Scanner Class. Could any one guide me to write the code correctly?
Code
import java.io.*;
import java.util.*;
public class ReadStudentsGrade {
public static void main(String[] args) throws IOException {
ArrayList stuRec = new ArrayList();
File file = new File("c:\\StudentGrade.txt");
try {
Scanner scanner = new Scanner(file).useDelimiter("$");
while (scanner.hasNextLine())
{
String stuName = scanner.nextLine();
int midTirmGrade = scanner.nextInt();
int finalGrade = scanner.nextInt();
System.out.println(stuName + " " + midTirmGrade + " " + finalGrade);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Runtime error:
Exception in thread "main" 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 writereadstudentsgrade.ReadStudentsGrade.main(ReadStudentsGrade.java:26)
Try useDelimiter(" \\$ |[\\r\\n]+");
String stuName = scanner.next(); // not nextLine()!
int midTirmGrade = scanner.nextInt();
int finalGrade = scanner.nextInt();
Your problems were that:
You mistakenly read whole line to get student name
$ is a regex metacharacter that needs to be escaped
You need to provide both line delimiters and field delimiters
Your while loop is off.
nextLine() will get you all what's left of the line and advance the cursor to there.
nextInt() will then jump delimiters until it finds an int.
The result will be skipping of values.
Assuming Kim and Jack were on different lines you would get:
stuName == "Kim $ 40 $ 45"
midTirmGrade == 35
finalGrade == 40
as your output; which isn't what you want.
Either you need to use the end-of-line as the delimiter or use a StringTokenizer to break each line up and then parse each of the sections as individual tokens.

Categories