Java servlet, reading from file, array out of Bound - java

I'm making a java servlet, and my task is to get the sum cost of products written in file:
category1 1 10 101 1 good1
category6 2 11 105 2 good5
category1 5 13 103 3 good4
category3 6 14 102 4 good2
category5 3 12 107 2 good1
The cost is in column 4. I have written:
public int Sum_of_Elements()throws IOException{
int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("/Data.txt"));
String line = "";
while((line=br.readLine())!=null){
String[] columns = line.split(" ");
sum = sum + Integer.parseInt(columns[4]);
}
System.out.println(sum);
return sum;
}
And it doesn't work. When i go to servlet page I get
java.lang.ArrayIndexOutOfBoundsException: 4
What's wrong ? and how to fix it ?

This code will fail if there is e.g. an empty line in the file, or a line formatted differently, or if the spaces are actually tabs (maybe there are more reasons). If you want to program defensively, you should do:
while((line=br.readLine())!=null) {
String[] columns = line.split(" ");
if( columns != null && columns.length >= 5 ) {
sum = sum + Integer.parseInt(columns[4]);
}
else {
// do what you must here; it may be an error to encounter such a line:
throw new IllegalArgumentException("malformatted line: " + line);
// or it may be OK to swallow the exceptional case
// or you may only need to silently log it:
logger.warn("malformatted line: " + line);
// etc...
}
}

I ran your code as following and it was fine. make sure that your Data file is ASCII
import java.io.*;
public class Test{
public static void main(String[] args){
try{
int sum = 0;
BufferedReader br = new BufferedReader(new FileReader("Data.txt"));
String line = "";
while((line=br.readLine())!=null){
String[] columns = line.split(" ");
sum = sum + Integer.parseInt(columns[4]);
}
System.out.println("Sun:" + sum);
}catch(Exception e){
System.out.println("error:" + e.getMessage());
}
}
}

There is no index 4 in your columns array. Check your length of columns array. It will be lesser than 5, ArrayIndexOutOfBoundException is thrown when an illegal index of the array is accessed. Check the array length like this
if( columns != null && columns.length >= 5 )
sum = sum + Integer.parseInt(columns[4]);

Related

How to count how many natural and decimal numbers there are in a text file

I want to count how many words, line, characters, and how many natural number and how many decimal numbers there are. The words, lines and character is easy, but how many natural and decimal number is the hard part, and I can't figure it out because I can't use hasNextInt, because there are words in the file that we need to read from.
The problem:
Write a java code that Print out some information about a document and put them in a file called Counts.txt.
✓ number of Rows
✓ number of Words (in general)
✓ number of Characters
✓ number of Natural numbers
✓ number of decimal numbers
The source file:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The sum of the second diagonal is: 220
The sum of the odd elements from the 0th line is: 25
The sum of the odd elements from the 1th line is: 110
The sum of the odd elements from the 2th line is: 75
The sum of the odd elements from the 3th line is: 220
The sum of the odd elements from the 4th line is: 125
The sum of the odd elements from the 5th line is: 330
The sum of the odd elements from the 6th line is: 175
The sum of the odd elements from the 7th line is: 440
The sum of the odd elements from the 8th line is: 225
The sum of the odd elements from the 9th line is: 550
16.2 to 23.5 change = 7.300000000000001
23.5 to 19.1 change = -4.399999999999999
19.1 to 7.4 change = -11.700000000000001
7.4 to 22.8 change = 15.4
22.8 to 18.5 change = -4.300000000000001
18.5 to -1.8 change = -20.3
-1.8 to 14.9 change = 16.7
The Highest Temperature is: 23.5
The Lowest Temperature is: -1.8
My code so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class Exercice4 {
public static void main(String[] args) {
// n3arif counters
int countline = 0;
int countchar = 0;
int countword = 0;
int countnum = 0;
int countdec = 0;
File file = new File("Document.txt");
// count of lines
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
input.nextLine();
countline++;
}
System.out.println("the count of Lines is:\t\t" + countline);
input.close();
} catch (Exception e) {
System.err.println("File not found");
}
// count of characters
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String str = input.nextLine();
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) != ' '){
countchar++;
}
}
}
System.out.println("the count of Characters is:\t" + countchar);
input.close();
} catch (Exception e) {
System.err.println("File not found");
}
// count of words
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
input.next();
countword++;
}
System.out.println("the count of Words is:\t\t" + countword);
input.close();
} catch (Exception e) {
System.err.println("File not found for count Words");
}
/*
// count of numbers
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
input.next();
countnum++;
}
System.out.println("the count of numbers is:\t" + countnum);
input.close();
} catch (Exception e) {
System.err.println("File not found");
}*/
/*
// count of decimals
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
input.nextDouble();
countdec++;
}
System.out.println("the count of Decimal is:\t" + countdec);
} catch (Exception e) {
System.err.println("File not found");
}
*/
// Print to a counts.txt
try {
PrintStream output = new PrintStream(new File("Counts.txt"));
output.println("Total Number of Lines:\t\t" + countline);
output.println("the count of Characters is:\t" + countchar);
output.println("the count of Words is:\t\t" + countword);
output.println("the count of numbers is:\t" + countnum);
output.println("the count of Decimal is:\t" + countdec);
} catch (FileNotFoundException e) {
System.err.println("File not found");
}
}
}
You can determine if an input is an integer or a double:
String str = input.next();
float number = Float.parseFloat(str);
if(number % 1 == 0){
//is an integer
} else {
//is not an integer
}
Rather than scan the entire file separately for each different thing that you need to count, you can scan the file once only and update all the counts. See below code. Explanations after the code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Counters {
private static void display(int count, String unit) {
String plural = count == 1 ? "" : "s";
String verb = count == 1 ? "is" : "are";
System.out.printf("There %s %d %s%s.%n", verb, count, unit, plural);
}
private static boolean isDecimalNumber(String word) {
boolean isDouble = false;
try {
Double.parseDouble(word);
isDouble = true;
}
catch (NumberFormatException x) {
// Ignore.
}
return isDouble;
}
private static boolean isNaturalNumber(String word) {
boolean isInt = false;
try {
Integer.parseInt(word);
isInt = true;
}
catch (NumberFormatException x) {
// Ignore.
}
return isInt;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("srctexts.txt"))) {
int chars = 0;
int lines = 0;
int wordCount = 0;
int naturalNumbers = 0;
int decimals = 0;
String line;
String[] words;
while (scanner.hasNextLine()) {
line = scanner.nextLine().replace(':', ' ').replace('=', ' ').trim();
lines++;
chars += line.length();
words = line.split("\\s+");
if (words.length > 0 && words[0].length() > 0) {
for (String word : words) {
wordCount++;
if (isNaturalNumber(word)) {
naturalNumbers++;
}
else if (isDecimalNumber(word)) {
decimals++;
}
}
}
}
display(lines, "line");
display(chars, "character");
display(wordCount, "word");
display(naturalNumbers, "natural number");
display(decimals, "decimal number");
}
catch (FileNotFoundException xFileNotfound) {
xFileNotfound.printStackTrace();
}
}
}
I wrote a file named srctexts.txt that contains your sample data.
The file contains colon character (:) and equals sign (=) which I assumed are not considered words but are considered characters.
Words are delimited by spaces. That's why I replaced the colon characters and equals signs with spaces.
Note that method split() creates a single element array that contains an empty string for an empty line. Hence empty lines are counted as lines but not added to the word count.
I assumed that natural numbers are actually ints and decimal numbers are actually doubles.
Here is the output I get when I run the above code:
There are 34 lines.
There are 1262 characters.
There are 273 words.
There are 111 natural numbers.
There are 23 decimal numbers.
Scanner next() will return String variable. By getting the variable, you can parse it to Double or Integer. If it can be parsed into an integer, then it is a natural number, or if the variable can be parsed into a double, then it is a decimal number.
You can modify your code by adding this:
String word = input.next();
try {
int number = Integer.parseInt(word);
countNumber++;
} catch (NumberFormatException ex){
ex.printStackTrace();
}
and
String word = input.next();
try {
double number = Double.parseDouble(word);
countDouble++;
} catch (NumberFormatException ex){
ex.printStackTrace();
}
import java.io .*; // for File
import java.util .*; // for Scanner
public class ex03_ {
public static void main(String[] args) {
Scanner input;
PrintStream output;
try {
output = new PrintStream (new File ("Countsssssssssss.txt"));
input = new Scanner( new File("Document.txt"));
String myLine;
int CountLines=0, CountChar=0, CountWords=0,CountNumeral=0,CountDecimal=0;
while(input.hasNextLine()){
myLine=input.nextLine();
CountLines+=1;
CountChar+=myLine.length();
if(!myLine.isEmpty())
CountWords++;
for(int i=0;i<myLine.length();++i)
{
if(myLine.charAt(i)==' ' || myLine.charAt(i)=='\t')
CountWords++;
}
}
//input.close();
input = new Scanner( new File("Document.txt"));
while(input.hasNextLine()){
if(input.hasNextInt())
CountNumeral++;
if(input.hasNextDouble())
CountDecimal++;
myLine=input.next();//next string or number ...
//When we reach the end of line it go to the next line
}
String data;
data= "the count of Lines is: "+CountLines;
System.out.println(data);
output.print(data);
data= "\nthe count of Characters is: "+CountChar;
System.out.println(data);
output.print(data);
data = "\nthe count of Words is: "+CountWords;
System.out.println(data);
output.print(data);
data = "\nthe count of numbers is: "+CountNumeral;
System.out.println(data);
output.print(data);
data = "\nthe count of Decimal is: "+(CountDecimal-CountNumeral);
System.out.println(data);
output.print(data);
}catch (FileNotFoundException e ){
System.out.println ("File not found.");}
}
}

Java-ArrayIndexOutOfBoundsException Error

When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}
You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");
Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.
You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}

Finding duplicate values in two arrays

I have stored two text files into two separate arrays. Now, I am trying to compare both arrays to find duplicate values. I am having issues with my logic, and I am unable to print out the number of times a duplicate value appears.
file1 contains:
1913 2016 1 1913 186
2016 1711 32843 2016 518
3 1913 32843 32001 4
250 5 3500 6 7
8 27 73 9 10
1711 73 11 2 1.4
1.4 12 33.75278 84.38611 1913
19 1930 20 21 1947
22 1955 23 1961 23
1969 27 1995 26 27
1962 28 29 30 1970
31 31
file2 contains:
1913 2016 32843 31 27 1.4 4 7 2 23
I am trying to find values in file2 that are duplicated in file1, and how many times.
I have the following code:
public static void findDuplicates() {
// array for first file
for (int n = 0; n < nums.size(); n++) {
// matches are false by default
boolean match = false;
int count = 0;
String v = nums.get(n);
// array for second file
for (int k = 0; k < nums1.size(); k++) {
String p = nums1.get(k);
// second file contains values from first file
if (p.contains(v)) {
// there is a match
match = true;
// when there is a match print out matched values and the number of times they appear in second file
if (match) {
count++;
System.out.println( p + " " + "is duped" + " " + count + " " + "times");
}
}
}
}
}
When I compile and run this code, this is the output:
31 is duped 1 times
Could someone let me know what I am doing wrong here?
EDIT
Here is the rest of my code:
public static ArrayList<String> nums;
public static ArrayList<String> nums1;
//Create a main method to start the program.
//Add FileNot FoundException in case the file can't be found by computer.
public static void main(String[] args) throws FileNotFoundException{
//The while will help us read the content into our computer piece by piece. It will not stop until the end of assignment.csv.
while(FILE1.hasNext()){
//Create a String variable - TempString. We use TempString to store each piece temporarily.
String TempString = FILE1.next();
String temp1 = TempString.replaceAll("[\\,]", "");
String pattern1 = "[0-9]+\\.{1}[0-9]+";
//Compile the Regular Expression into Pattern and store it in r1 so that the computer can understand the Regular Expression.
Pattern r1 = Pattern.compile(pattern1);
Matcher m1 = r1.matcher(temp1);
String pattern2 = "[0-9]+";
//Compile the Regular Expression into Pattern and store it in r2 so that the computer can understand the Regular Expression.
Pattern r2 = Pattern.compile(pattern2);
Matcher m2 = r2.matcher(temp1);
nums = new ArrayList<String>();
//Recollect, m1 is used to match decimal numbers.
if(!(m1.find())){//if a decimal number CAN'T be found
//We use while statement instead of if statement here.
//If there is only one piece per line, we can use either while statement or if statement.
//However, we have to use while statement if there is more than one piece per line.
while(m2.find()) {//if an integer number CAN be found
//If an Integer is found, we add 1 to Variable count.
count++;
//Even though the number (i.e., m2.group(0)) is an Integer, its data type is String. So we store it to a String variable - number.
String number = m2.group(0);
nums.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0){
System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.print(number + " ");
}
}
//If we find a decimal number
else{
//We add 1 to Variable count.
count++;
//Even though the number (i.e., m1.group(0)) is a decimal number, its data type is String. So we store it to a String variable - number.
String number = m1.group(0);
nums.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0) {
System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.print(number + " ");
}
}
FILE1.close();//Once we finish the task, we close the file.
while(FILE2.hasNext()){
//Create a String variable - TempString. We use TempString to store each piece temporarily.
String TempString = FILE2.next();
//So I use replaceAll function to eliminate comma (,) and store the new string in temp1.
String temp1 = TempString.replaceAll("[\\,]", "");
String pattern1 = "[0-9]+\\.{1}[0-9]+";
//Compile the Regular Expression into Pattern and store it in r1 so that the computer can understand the Regular Expression.
Pattern r1 = Pattern.compile(pattern1);
//Match the Regular Expression with the piece (temp1) we read from assignment.csv.
Matcher m1 = r1.matcher(temp1);
String pattern2 = "[0-9]+";
//Compile the Regular Expression into Pattern and store it in r2 so that the computer can understand the Regular Expression.
Pattern r2 = Pattern.compile(pattern2);
//Match the Regular Expression with the piece (temp1) we read from assignment.csv.
Matcher m2 = r2.matcher(temp1);
nums1 = new ArrayList<String>();
//We have two types of numbers - Integer and Decimal
//Let's start us Integer.
//Recollect, m1 is used to match decimal numbers.
if(!(m1.find())){//if a decimal number CAN'T be found
//We use while statement instead of if statement here.
//If there is only one piece per line, we can use either while statement or if statement.
//However, we have to use while statement if there is more than one piece per line.
while(m2.find()) {//if an integer number CAN be found
//If an Integer is found, we add 1 to Variable count.
count++;
//Even though the number (i.e., m2.group(0)) is an Integer, its data type is String. So we store it to a String variable - number.
String number = m2.group(0);
nums1.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0){
//System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.println(/*number + " "*/);
}
}
//If we find a decimal number
else{
//We add 1 to Variable count.
count++;
//Even though the number (i.e., m1.group(0)) is a decimal number, its data type is String. So we store it to a String variable - number.
String number = m1.group(0);
nums1.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0){
//System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.println(/*number + " "*/);
}
findDuplicates();
}
FILE2.close();//Once we finish the task, we close the file.
}
I tried to delete as much unnecessary code as I could.
EDIT
Expected output should be:
1913 is duplicated 3 times.
2016 is duplicated 2 times.
32843 is duplicated 1 times.
31 is duplicated 2 times.....
EDIT
So I believe i've found the problem. For some reason,
String p = nums.get(k)
in my findDuplicates() method is only returning the value 31, and not the other values. I am working on solving the problem, and will post an answer when I do.
I think the biggest issue is that the printline is inside the second for loop.Furthermore I would remove the boolean and just compare the 2 Strings (p==v).
So the code would look more like this:
public static void main(String[] args) {
// array for second file
for (int n = 0; n < nums1.size(); n++) {
// matches are false by default
int count = 0;
String v = nums1.get(n);
// array for first file
for (int k = 0; k < nums.size(); k++) {
String p = nums.get(k);
// second file contains values from first file
if (p==v) {
count++;
}
}
System.out.println( v + " " + "is duped" + " " + count + " " + "times");
}
}
}
With the changes I made the code runs as intended.You can check out a live demo here.
Output:
1913 is duped 4 times
2016 is duped 3 times
32843 is duped 2 times
31 is duped 2 times
27 is duped 3 times
1.4 is duped 2 times
4 is duped 1 times
7 is duped 1 times
2 is duped 1 times
23 is duped 2 times
You should use the System.out.println statement outside inner loop so that first whole of second arraylist get iterated before number of times the number is duplicated is printled.
You also need to make a few other changes to run the program correctly
for (int n = 0; n < nums.size(); n++) {
// matches are false by default
boolean match = false;
int count = 0;
String v = nums.get(n);
// array for second file
for (int k = 0; k < nums1.size(); k++) {
String p = nums1.get(k);
// second file contains values from first file
if (p.contains(v)) {
// there is a match
match = true;
// when there is a match print out matched values and the number of times they appear in second file
if (match) {
count++;
match = false;
}
}
System.out.println( p + " " + "is duped" + " " + count + " " + "times");
count = 0;
}
}
But still then your logic will not work all case because you are not comparing how many times a number is repeated in first file. You are only comparing second file numbers with first file ones. For the case which you gave in question interchanging the two files after modifying the code as I have mentioned it will work.
please try it on.
package stackoverflow.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public List<Integer> list = new ArrayList<Integer>();
public List<Integer> dup = new ArrayList<Integer>();
public Map<Integer, Integer> hashDup = new HashMap<Integer, Integer>();
public void fileReader() {
File file = new File("/home/john/Documents/file1.txt");
List<Integer> list1 = this.output(file);
File file2 = new File("/home/john/Documents/file2.txt");
List<Integer> list2 = this.output(file2);
for (int i = 0; i < list1.size(); i++) {
int counter = 0;
for (int j = 0; j < list2.size(); j++) {
if (list1.get(i) == list2.get(j)) {
counter++;
}
}
if (!hashDup.containsKey(list1.get(i))) {
hashDup.put(list1.get(i), counter);
System.out.println(" dup " + list1.get(i) + " :" + counter);
}
}
}
public List<Integer> output(File file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
// System.out.println( text);
String[] str = text.split(" ");
for (String string : str) {
list.add(Integer.parseInt(string));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
// print out the list
// System.out.println(list.toString());
return list;
}
public static void main(String args[]) {
Test t = new Test();
t.fileReader();
}
}

I have a file with 3 columns and 7 rows, I need to make 3 arrays out of each column in the file

I have been trying to figure this out for days and I feel that I am just stuck on something that is so easy from over thinking it. I need to read the file, (contents of what text file looks like are right below)... create 3 arrays out of each column.
My issue is when splitting the String under " " conditions into a String [] Array, takes the last row of my txt and puts that into the new String [] Array, not the entire contents of string that i made from file...
my txt file looks like this...
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
my code so far after days of manipulation, deletion, starting over from scratch...all to come to this small piece.
PLEASE HELP ME!!!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
try {
File input = new File("Lab1File.txt"); //reads file and names it input to refer back later
Scanner klg = new Scanner(input); //creates scanner that reads the file named input
String [] b = new String [7]; //creating breakfast, lunch and dinner Strings (To Split later)
String [] l = new String [7];
String [] d = new String [7];
String fileLine = null;
System.out.println("TEST 1: Contents of file are as follows: ");
while (klg.hasNextInt()) { //Puts file contents into string
fileLine = klg.nextLine();
System.out.println(fileLine);
}
System.out.println("");
System.out.println("TEST 2 BELOW");
String strArr[] = fileLine.split(" "); //temporary array to hold all numbers and split
for(int i = 0; i < strArr.length; i++){ //Trying to split String into individual elements and put into string array.
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("--------");
for(int k = 0; k < strArr.length;k++) {
b[k] = strArr[k]; //Assigns contents into 3 arrays
l[k] = strArr[k];
d[k] = strArr[k];
System.out.println(b[k]);
System.out.println(l[k]);
System.out.println(d[k]);
}
OUTPUT:
TEST 1: Contents of file are as follows:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900
TEST 2 BELOW
675 400 900
--------
675
675
400
400
900
900
Use a 3x7 matrix and two for loops, saving each int value separately:
File input = new File("Lab1File.txt");
Scanner scanner = new Scanner(input);
int[][] matrix = new int[7][3];
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 3; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
scanner.close();
After the while loop finishes which has fileLine = klg.nextLine();, fileLine will have only the last line. You are not concatenating the strings.
You are replacing fileLine with the line that you read every time. So you only have the last line after the loop.
You probably need to do:
fileLine = fileLine + " " + klg.nextLine();
instead of:
fileLine = klg.nextLine();
Edit:
You need to initialize String fileLine = ""; with this approach.
Your problems are in :
fileLine = klg.nextLine(); fileLine will have only one line
for(int k = 0; k < strArr.length;k++)
Better you move the code in for loop to the while (klg.hasNextInt()):
int k = 0;
while (klg.hasNextInt()) {
fileLine = klg.nextLine();
System.out.println(fileLine);
String strArr[] = fileLine.split(" ");
b[k] = strArr[0];
l[k] = strArr[1];
d[k] = strArr[2];
k++;
}
Or you can do it the way you initially planned as shown in the runnable below:
package weeklycaloriecount;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class WeeklyCalorieCount {
public static void main(String[] args) {
// Declare and initialize string variables to hold
// the values from each column of each file line as
// they are read in.
String colA = "";
String colB = "";
String colC = "";
try {
File input = new File("Lab1File.txt");
Scanner klg = new Scanner(input);
// Read each line of file until the end.
while (klg.hasNextInt()) {
// Place the line read into a String Array
String[] fileLine = klg.nextLine().split(" ");
// Take each element of the array and place them into
// their respective column variable and delimit them
// with a whitespace...
colA+= fileLine[0] + " ";
colB+= fileLine[1] + " ";
colC+= fileLine[2] + " ";
}
klg.close(); // Close the scanner.
}
catch(FileNotFoundException ex) {
// Trap the File Not Found Exception
System.out.println("Whoops! File Not Found!");
}
// Display each String variable...
System.out.println("The colA Variable: " + colA);
System.out.println("The colB Variable: " + colB);
System.out.println("The colC Variable: " + colC);
// You can at this point use each variable (colA, colB, and colC)
// as your separated columns or you can place the contents of each
// variable and place them into individual arrays as done below...
String[] b = colA.trim().split(" ");
String[] l = colB.trim().split(" ");
String[] d = colC.trim().split(" ");
// Display our Arrays (b[], l[], and d[])
// Breakfast...
System.out.println("");
System.out.println("The b[] Array: " + Arrays.toString(b));
// Lunch...
System.out.println("The l[] Array: " + Arrays.toString(l));
// Dinner...
System.out.println("The d[] Array: " + Arrays.toString(d));
}
}

How to count row values from file?

i am trying to read the txt file and add up row values i.e i am passing the parameters to java code. it should print the line numbers of added values
i am passing filename and int value to java program.
for ex: read.txt contains
2
2
3
4
4
6
7
7
8
8
9
0
now i am passing parameter as 5, so it should add up the rows and print the line number and it should print the line number if the sum >= 5
for ex
2+2+3 = 7 is > 5
because the last number added up is 3 and it is in line number 3
so it should print line number 3
4+4 = 8 is > 5
so it should print line number 3
6 is > 5
so it should print line number 6
because its in line number 6
and so on..
how can i do this?
here is what i have tried
code:
import java.io.*;
class CountR
{
public static void main(String args[])
{
setForSum("read.txt",3);
}
public static void setForSum(String filename,int param2)
{
try
{
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int i = 0;
while ((strLine = br.readLine()) != null)
{
i++;
if(param2 == Integer.parseInt(strLine))
{
System.out.println(i);
}
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
First thing I've noticed, is this if statement is only going to work if you land on your specified number, exactly.
if(param2 == Integer.parseInt(strLine))
{
System.out.println(i);
}
Should be:
if(param2 >= Integer.parseInt(strLine))
{
System.out.println(i);
}
Secondly, you're not totalling up the values, are you? You're just reading each value, so declare some value outside of the loop:
int currentTotal = 0;
then in the loop:
currentTotal += Integer.valueOf(strLine);
THEN use currentTotal in your statement:
if(currentTotal >= Integer.parseInt(strLine))
{
System.out.println("Line Number " + i);
}
And as Heuster mentioned, make sure you're resetting currentTotal back to 0 inside your if statement!

Categories