I've been having stressful issues all day on this program to read a text file for integers and storing the integers into an array. I thought I finally got the solution with the code below.
But unfortunately.. I have to loop through the file with the method hasNextLine().
Then using nextInt() to read integers from the file and store them into an array.
So using scanner constructor, hasNextLine(), next(), and nextInt() methods.
Then use try and catch to determine which words are integers and which are not by using the InputMismatchException. Also a exception for blank lines in the file?
Problem is I did not use a try and catch and exceptions, as I just skipped over none-ints.
Also, I'm using a int array so I want to do this without list.
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]);
ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
int i = 0;
//connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
//If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
//if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
}
else {
inputFile.next();
}
}
}
finally {
inputFile.close();
}
System.out.println(i);
for (int v = 0; v < i; v++) {
System.out.println(array[v]);
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//print number of integers
//print all integers that are stored in array
}
}
Then I'll be printing everything in my 2nd method, but that I can worry about later. :o
Example Content of Text File:
Name, Number
natto, 3
eggs, 12
shiitake, 1
negi, 1
garlic, 5
umeboshi, 1
Sample Output Goal:
number of integers in file "groceries.csv" = 6
index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1
Sorry for the similar question. I'm very stressed out, and even more that I was doing it all wrong... I'm completely stuck at this point :(
You can read Your file in this way.
/* using Scanner */
public static Integer[] getIntsFromFileUsingScanner(String file) throws IOException {
List<Integer> l = new ArrayList<Integer>();
InputStream in = new FileInputStream(file);
Scanner s = new Scanner(in);
while(s.hasNext()) {
try {
Integer i = s.nextInt();
l.add(i);
} catch (InputMismatchException e) {
s.next();
}
}
in.close();
return l.toArray(new Integer[l.size()]);
}
/* using BufferedReader */
public static Integer[] getIntsFromFile(String file) throws IOException {
List<Integer> l = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
try {
l.add(Integer.parseInt(line.split(",")[1]));
} catch (NumberFormatException e) {
}
}
return l.toArray(new Integer[l.size()]);
}
And with Your code:
public static void main(String[] commandlineArgument) {
Integer[] array = getIntsFromFileUsingScanner(commandlineArgument[0]);
ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
Here is one way to meet your new requirements,
public static Integer[] readFileReturnIntegers(
String filename) {
Integer[] temp = new Integer[1000];
int i = 0;
// connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
// If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
// if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
try {
while (inputFile.hasNext()) {
try {
temp[i] = inputFile.nextInt();
i++;
} catch (InputMismatchException e) {
inputFile.next();
}
}
} finally {
inputFile.close();
}
Integer[] array = new Integer[i];
System.arraycopy(temp, 0, array, 0, i);
return array;
}
return new Integer[] {};
}
public static void printArrayAndIntegerCount(
Integer[] array, String filename) {
System.out.printf(
"number of integers in file \"%s\" = %d\n",
filename, array.length);
for (int i = 0; i < array.length; i++) {
System.out.printf(
"\tindex = %d, element = %d\n", i, array[i]);
}
}
Outputs
number of integers in file "/home/efrisch/groceries.csv" = 6
index = 0, element = 3
index = 1, element = 12
index = 2, element = 1
index = 3, element = 1
index = 4, element = 5
index = 5, element = 1
Maybe you can resolve this issue by brief code as I post below.
public static List<Integer> readInteger(String path) throws IOException {
List<Integer> result = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = null;
line = reader.readLine();
String input = null;
while(line != null) {
input = line.split(",")[1].trim();
matcher = pattern.matcher(input);
if(matcher.matches()) {
result.add(Integer.valueOf(input));
}
line = reader.readLine();
}
reader.close();
return result;
}
Enclose try catch for below code:
try
{
if (inputFile.hasNextInt()) {
array[i] = inputFile.nextInt();
i++;
}
else {
inputFile.next();
}
}catch(Exception e)
{
// handle the exception
}
Related
I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}
i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]
Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc
I'm working on a class assignment. I need to read in a file containing lines of input. Every block of three lines is a structured set: The first is one polynomial, the second is another polynomial, the third is a text string that indicates the algebraic operation for the polynomial arithmetic. I've set my program up so that it reads each line into an array, and then I parse the two array indices containing integers into my polynomial term. I call the appropriate function based on the third line. My struggle is finding a way to get the process to reset after each third line. Here is the code for my main function. I thought I would use an i-loop (k-loop here) somehow, but I can't get it to work. Any insight or suggestions greatly appreciated.
Example of input:
3 2 4 5
5 7 4 6
subtract
4 3 5 1
1 2 3 4
add
Here is my code:
public static void main(String[] args) throws IOException {
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
int lines = 0;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader("Test.txt"));
String line=null;
while((line = reader.readLine()) != null) {
list.add(line);
lines++;
} // end while
} catch (FileNotFoundException e){
e.printStackTrace();
}
System.out.println("lines " + lines);
for (int k=0; k<lines; k++){
String[] stringArr = list.toArray(new String[0]);
System.out.println(stringArr[k+0]);
System.out.println(stringArr[k+1]);
System.out.println(stringArr[k+2]);
String[] nums1 = stringArr[k+0].split(" ");
String[] nums2 = stringArr[k+1].split(" ");
for (int i=0; i<nums1.length; i+= 2) {
p1.addTerm(Integer.parseInt(nums1[i]), Integer.parseInt(nums1[i+1]));
}
for (int i=0; i<nums2.length; i+= 2) {
p2.addTerm(Integer.parseInt(nums2[i]), Integer.parseInt(nums2[i+1]));
}
if (stringArr[k+2].equalsIgnoreCase("add")) {add(p1,p2);}
else if (stringArr[k+2].equalsIgnoreCase("subtract")) {subtract(p1,p2);}
else if(stringArr[k+2].equalsIgnoreCase("multiply")) {multiply(p1,p2);}
else {
System.out.println("Bad input");
}
nums1=null;
nums2=null;
}
}
Suggestion: Try something like the Scanner class? Catch the NoSuchElementException if it should run out of lines in the file.
Scanner scanner = new Scanner(new String("input"));
while(scanner.hasNextLine()) {
String lineOne = scanner.nextLine();
String lineTwo = scanner.nextLine();
String lineThree = scanner.nextLine();
calculateSomething(lineOne, lineTwo, lineThree);
}
It can be used to read strings to (space-delimited by default)
private static int[] getPolynomialFactors(String line) {
Scanner splitter = new Scanner(line);
int[] p = new int[4];
int counter=0;
while (splitter.hasNextInt()){
p[counter] = splitter.nextInt();
counter++;
}
return p;
}
With a good night's sleep, I was able to figure it out. I used a for-loop and just had to modify the incrementing of the loop counter. I nulled the pointers to the integer arrays I was using to store the integers parsed from the first two lines of the code block, which effectively reset them. Here is my updated code that works:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
int lines = 0;
List<String> list = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader("Test.txt"));
String line=null;
while((line = reader.readLine()) != null) {
list.add(line);
lines++;
} // end while
} catch (FileNotFoundException e){
e.printStackTrace();
}
System.out.println("lines " + lines);
String[] stringArr = list.toArray(new String[0]);
for (int k=0; k<lines; k+=3){
System.out.println(stringArr[k+0]);
System.out.println(stringArr[k+1]);
System.out.println(stringArr[k+2]);
String[] nums1 = stringArr[k+0].split(" ");
String[] nums2 = stringArr[k+1].split(" ");
for (int i=0; i<nums1.length; i+= 2) {
p1.addTerm(Integer.parseInt(nums1[i]), Integer.parseInt(nums1[i+1]));
}
for (int i=0; i<nums2.length; i+= 2) {
p2.addTerm(Integer.parseInt(nums2[i]), Integer.parseInt(nums2[i+1]));
}
if (stringArr[k+2].equalsIgnoreCase("add")) {add(p1,p2);}
else if (stringArr[k+2].equalsIgnoreCase("subtract")) {subtract(p1,p2);}
else if(stringArr[k+2].equalsIgnoreCase("multiply")) {multiply(p1,p2);}
else {
System.out.println("Bad input");
break;
}
nums1=null;
nums2=null;
}
}
}
If I have a file that contains for example:
results1: 2, 4, 5, 6, 7, 8, 9
results2: 5, 3, 7, 2, 8, 5, 2
I want to add the integers from each line to a array. One array
for each line. How can I do this with code that does only read the integers?
Here's what I got this far
String data = null;
try {
Scanner in = new Scanner(new File(myFile));
while (in.hasNextLine()) {
data = in.nextLine();
numbers.add(data);
}
in.close();
} catch (Exception e) {
}
Easy.
One line per array, not two as you have it. New line after each one.
Read each line as a String, discard the leading "resultsX:", and split what remains at a delimiter of your choosing (e.g. comma). Parse each into an integer and add it to a List.
I don't think that leading "results1: " is adding any value. Why do you have that?
public static void main(String[] args) throws IOException {
BufferedReader reader=null;
try {
reader = new BufferedReader(new FileReader(new File("PATH TO FILE")));
// Only works if File allways contains at least two lines ... all lines after the second
// will be ignored
System.out.println(String.format("Array 1 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
System.out.println(String.format("Array 2 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
} finally {
if (reader!=null) {
reader.close();
}
}
}
private static Integer[] stringArray2IntArray(String[] numStrings) {
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < numStrings.length; i++) {
result.add(Integer.parseInt(numStrings[i].trim()));
}
return result.toArray(new Integer[numStrings.length]);
}
private static String[] readNextLine(BufferedReader reader) throws IOException {
return reader.readLine().split(":")[1].split(",");
}
Assuming you have an input file, like this:
2,4,5,6,7,8,9
5,3,7,2,8,5,2
here is a code snippet to load it:
String firstLine = "";
String secondLine = "";
File file = new File("path/to/file");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
firstLine = br.readLine();
secondLine = br.readLine();
} catch(Exception e){
e.printStackTrace();
}
String[] firstResult = firstLine.split(",");
String[] secondResult = secondLine.split(",");
int[] firstIntegers = new int[firstResult.length];
for(int i = 0; i <= firstResult.length ; i++){
firstIntegers[i] = Integer.parseInt(firstResult[i]);
}
int[] secondIntegers = new int[secondResult.length];
for(int i = 0; i <= secondResult.length ; i++){
firstIntegers[i] = Integer.parseInt(secondResult[i]);
}
Open the file with a BufferedReader br and then read it line by line.
Store each line in an int array and add all those int arrays to a list. At the end, this list will contain all the int arrays that we wanted, so iterate this list to do whatever you want to do next.
String filePath = "/path/to/file";
BufferedReader br = null;
List<Integer[]> arrays = new ArrayList<>(); //this contains all the arrays that you want
try {
br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf(":")+2); //this starts the line from the first number
String[] stringArray = line.split(", ");
Integer[] array = new Integer[stringArray.length];
for (int i = 0; i < stringArray.length; ++i) {
array[i] = Integer.parseInt(stringArray[i]);
}
arrays.add(array);
}
} catch (FileNotFoundException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
Since ArrayLists keep insertion order, then, e.g., arrays.get(3) will give you the array of the fourth line (if there is such a line) and arrays.size() will give you the number of lines (i.e., int arrays) that are stored.