rickyhitman10
rickyhitman10

Reputation: 59

result errors using array io java

Contents of file patch.txt:

1
2
3
4
5

My code:

int sum = 0;
Scanner s = new Scanner (new File("patch.txt"));
while (s.hasNextLine()){
            String [] str = s.nextLine().split("/r");
            for (int i=0; i<str.length; i++){
            sum+=Integer.parseInt(str[i]);
            }
            System.out.print(sum); //the result is 15
        }
        s.close();
    }
}

When I sum the data must be 15, but why do I always get an error?

Upvotes: 1

Views: 81

Answers (4)

Johny
Johny

Reputation: 2188

Solution using for loop and array:

String[] str = new String[10];
for(int i = 0; s.hasNextLine(); i++) {
    str[i] = s.nextLine();
    sum += Integer.parseInt(str[i]);
}
System.out.print(sum);

But for this problem given below is a better solution:

 while (s.hasNextLine()) {
        String str = s.nextLine();
        sum += Integer.parseInt(str);
 }
 System.out.print(sum);

Upvotes: 2

brb tea
brb tea

Reputation: 343

int sum = 0;
Scanner s = new Scanner (new File("patch.txt"));
while (s.hasNextLine()){
    String [] str = s.nextLine().split("\r");
    for (int i = 0; i < str.length; i++){
        if(!str[i].trim().isEmpty){
            sum+=Integer.parseInt(str[i]);
        }
    }
}
s.close();
System.out.print(sum); //the result is 15

Try this.

Edited above code.

Upvotes: 0

Benjamin
Benjamin

Reputation: 2286

Try This : Use a try catchfor Scanner otherwise it shows the error unreported exception java.io.FileNotFoundException;

        import java.io.*;
        import  java.util.*;

        class Entry1 
        {
        static  Scanner s ;
        public static void main( String[] args )
        {
         int sum = 0;
          try
           {
             s = new Scanner (new File("patch.txt"));
           }
          catch(Exception e)
          {
            System.out.print(e);
          }
          while (s.hasNextLine())
          {      
            String [] str = s.nextLine().split("/r");
            for (int i=0; i<str.length; i++){
            sum+=Integer.parseInt(str[i]);
          }   
         }
        System.out.print(sum);
        s.close();
       }
      }

Upvotes: 1

badjr
badjr

Reputation: 2286

You don't have to do String [] str = s.nextLine().split("/r"), it is not needed. You were also printing the sum from within the while loop, but it should be outside the while loop. Try this:

while (s.hasNextLine()){
    String str = s.nextLine();          
    sum+=Integer.parseInt(str);         
}
System.out.print(sum); //the result is 15
s.close();

Upvotes: 1

Related Questions