How to count row values from file? - java

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!

Related

Getting infinite loop when reading file from method

I am trying to refactor my code, and adding methods where possible. When I read a file from a method and return the result of the computation, the code goes into extreme memory consumption, infinite loop.
My modification looks like this:
import java.util.Scanner;
public class NumberOfLines {
public static int compute () {
// read this file
String theFile = "numbers.txt";
Scanner fileRead = null;
if (NumberOfLines.class.getResourceAsStream(theFile) != null) {
fileRead = new Scanner(NumberOfLines.class.getResourceAsStream(theFile));
}
else {
System.out.print("The file " + theFile + " was not found");
System.exit(0);
}
System.out.println("Checkpoint: I am stuck here");
// count number of lines
int totalLines = 0;
while(fileRead.hasNextInt()) {
totalLines++;
}
fileRead.close();
return totalLines;
}
public static void main (String[] args) {
System.out.println("The total number of lines is: " + compute());
}
}
If instead of writing the method, and placing the code on main, then it works. Why is this?
EDIT
Contents of numbers.txt is:
5
2
7
4
9
1
5
9
69
5
2
5
6
10
23
5
36
5
2
8
9
6
So I expect out put to be:
The total number of lines is: 22
The reason you are getting stuck in an infinite loop is because you are reading the file but not incrementing the scanners token in the while loop. So the while condition is always true.
while (fileRead.hasNextInt()) {
totalLines++;
fileRead.nextInt(); // change made here only
}

Java input random numbers and keep a counter for each number

So I am trying to create a loop that accepts number "0 - 10". If it is less than "0" than the loop exits and the program prints out all the numbers and the number of times each was entered. So Lets say you enter values like 1 2 3 4 5 1 It will print out something like Number:1 Times Entered:2 then next line will print out Number:2 Times Entered:1. If it goes higher than 10 I will just give them an input error. If someone can just help me out creating the correct variables and format I think I can take it from there. Here is what I have thus far... I know it's not correct but this is the idea I am trying to do.
import java.io.*;
public class test {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
Integer[] numbers = new Integer[1000]
int count = 0;
str = input.readLine();
while(str != null){
numbers[count] = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(numbers < 0)
break;
else if(numbers >= 0 || numbers <= 50)
numbers[count]++;
else
System.out.print("You must enter a value less than 51");
} // Close while loop here
System.out.println("Number:" + number + " Times Entered:" + count);
}
}
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);
String str;
int i,number;
Integer[] numbers = new Integer[10];
int count = 0;
for(i=0;i<10;i++)
numbers[i]=0;
str = input.readLine();
while(str != null){
number = Integer.parseInt(str);
// Here I will create some [if else] statements like
if(number == 0)
break;
else if(number >= 0 && number <= 10)
numbers[number-1]++;
else
System.out.print("You must enter a value less than 11");
str = input.readLine();
} // Close while loop here
for(i=0;i<10;i++)
System.out.println("Number:" + (i+1) + " Times Entered:" + numbers[i]);
}
}
This should work.And put some efforts form your side so that you can learn

Im having trouble getting this txt.file to print 1-100 integers correctly

Im trying to have this code print 1-10 on first line, then 11-20 on the second, 21-30 on the third, etc.
But with the code now Its printing 1-10 on first line, then 10-20 on the second, 20-30 on the third, etc.
Basically I'm stuck here and have been doing trial and error to try and fix it but nothings working.
import java.util.Scanner;
import java.io.*;
public class P4C {
public static void main ( String [] args )throws IOException {
PrintWriter writer = new PrintWriter ( new File ( "Write100Project" )); //creates a PrintWriter object to allow us to create and write to a file.
int integer = 1;
int margin = 1;
int counter = 1;
while ( margin <=100){
if ( margin == 10*counter ){
System.out.println ( integer + " ");
counter+=1;
integer = integer+1;
}
System.out.print ( integer + " " );
integer+=1;
margin++;
}
}
}
When you loop over an array and want to treat certain elements differently there basically are two approaches:
Do something for the special element. Do something else for everything but the special element. In code this means an if-else in your while loop.
Do something generic for every element and do something extra for the special elements.
Which approach to choose depends on the amount of overlap. If the code for the special element is very different from the code for the other elements, use 1. If the code is almost the same, use 2.
You seem to do a hybrid of these, which is why every multiple of 10 is printed twice. Translating your problem two these approaches:
Print the number and a new line for every multiple of 10. Print the number for every other element. Code snippet of the while body (using %, I hope you got is meaning from the other answers):
if (margin % 10 == 0) {
System.out.println(margin + " ");
margin++;
} else {
System.out.print(margin + " ");
margin++;
}
Print the number for every element. Additionally, print a new line for every multiple of 10 (note how I need to reorder your code; you first want to print the multiple of 10, then the new line, then increment margin):
System.out.print(margin + " ");
if(margin % 10 == 0) {
System.out.println();
}
margin++;
Besides, notice how I don't need integer and counter any more?
With this type of thing the modulus % which shows you the remainder. Here you want a new line after every 10 so #MadProgrammer 's (margin % 10 == 0) is saying when the remainder after dividing it by 10 is 0
You can do this all with one variable instead of using three which should make it a bit simpler. The logic is while your number is less than 100, add one to it then print it out. If it is the 10th number in the row print a new line.
import java.util.Scanner;
import java.io.*;
public class P4C {
public static void main ( String [] args )throws IOException {
PrintWriter writer = new PrintWriter ( new File ( "Write100Project" )); //creates a PrintWriter object to allow us to create and write to a file.
int integer = 0;
while ( integer <100){
if ( integer % 10 == 0 ){ //If integer is divisible by 10
System.out.println (); //Time to go onto a new line
}
integer++;
System.out.print ( integer + " " );
}
}
}
The '%' is modulus.
Modulus basically returns the remainder; for example:
5 % 4 = 1;
3 % 2 = 1;
8 % 3 = 2;
10 % 10 = 0;
i++ is the same as saying either;
i = i + 1;
or
i += 1;
import java.util.Scanner;
import java.io.*;
public class IntegerCounting {
public static void main ( String [] args )throws IOException {
PrintWriter writer = new PrintWriter ( new File ( "Write100Project" ));
int i = 0;
while(i < 100){
if(i % 10 == 0 && i != 0){
System.out.println(i++ + "");
}
System.out.print(i++ + " ");
}
}
}
This may help...
int integer = 1;
while(integer<=100){
System.out.print(" "+integer++);
if(integer%10==0){
System.out.println(" "+integer++);
//System.out.println();
}
}

Java servlet, reading from file, array out of Bound

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]);

Cannot print out read integers: java

I am creating a program that will print out digits of pi up to a number specified by the user. I can read the input from the user, I can read the text file, but when I print the number of digits, it prints out the wrong number.
"Pi.txt" contains "3.14159".
Here is my code:
package pireturner;
import java.io.*;
import java.util.Scanner;
class PiReturner {
static File file = new File("Pi.txt");
static int count = 0;
public PiReturner() {
}
public static void readFile() {
try {
System.out.print("Enter number of digits you wish to print: ");
Scanner scanner = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new FileReader(file));
int numdigits = Integer.parseInt(scanner.nextLine());
int i;
while((i = reader.read()) != -1) {
while(count != numdigits) {
System.out.print(i);
count++;
}
}
} catch (FileNotFoundException f) {
System.err.print(f);
} catch (IOException e) {
System.err.print(e);
}
}
public static void main(String[] args ) {
PiReturner.readFile();
}
}
This will print out "515151" if the user inputs 3 as the number of digits they wish to print. I do not know why it does this, and I am not sure what I am doing wrong, as there are no errors and I have tested the reading method and it works fine. Any help would be gladly appreciated. Thanks in advance.
By the way, casting integer 'i' to a char will print out 333 (assuming input is 3).
The value 51 is the Unicode code point (and the ASCII value) for the character '3'.
To display 3 instead of the 51 you need to cast the int to char before printing it:
System.out.print((char)i);
You also have an error in your loops. You should have a single loop where you stop if either you reach the end of the file, or if you reach the required number of digits:
while(((i = reader.read()) != -1) && (count < numdigits)) {
Your code also counts the character . as a digit, but it is not a digit.
Your inner loop is not left before outputting numdigit times 3
while (count != numdigits) {
System.out.print(i);
count++;
}
instead ...
int numdigits = Integer.parseInt (scanner.nextLine ());
// for the dot
if (numdigits > 1)
++numdigits;
int i;
while ((i = reader.read ()) != -1 && count != numdigits) {
System.out.print ((char) i);
count++;
}
You only read one character from the file - '3' (character code 51, as Mark Byers points out) and then you print it 3 times.
int i;
while((count < numdigits) && ((i = reader.read()) != -1)) {
System.out.print((char)i);
count++;
}
If the user says they want 4 digits of pi, are you intending to print 3.14 or 3.141?
The above code would print 3.14 for 4 - because it's 4 characters.

Categories