2

Java:

I want to sum up each line's integers, but don't know how many integers users will key in.

Input:

3
10 20
1 2 3 4 5 6
10 -20 50 -90

Output:

30
21
-50

I wrote:

import java.util.Scanner;

public class Sum2 {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int k = input.nextInt();
        int total = 0;
        for (int i = 0; i <= k;i++){
            while(input.hasNext()){
                   total += input.nextInt();               
            }
        System.out.println(total);
        }
    }
}

but there's no output. (3 means the user will key in 3 lines of integers)

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Vanessa Leung
  • 770
  • 1
  • 10
  • 22

4 Answers4

0

Try this(much coded but it works for any number of input):

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    int count = 0;
    String line;
    ArrayList<Integer> total = new ArrayList<>();
    boolean isNext = true;

    System.out.println("Input a value or 'e' to exit:");
    do{
        try{
            line = scan.nextLine();
            String num[] = line.split("\\s+");

            int sum = 0;
            for(String a : num){
                //if entered value equal to character 'e' print done and sum
                if(a.equals("e")){
                    a = a.replace("e", "0");
                    sum += Integer.parseInt(a);

                    isNext = false;
                    System.out.println("Done!");
                }else{
                    sum += Integer.parseInt(a);
                }
            }
            total.add(sum);
        }catch(NumberFormatException e){
            System.out.println("Wrong input!");
        }

        count++;
    }while(isNext);

    for(Integer i: total){
        System.out.println(i);
    }
}

Output:

Input a value or 'e' to exit:
10 20
1 2 3 4 5 6
10 -20 50 -90 e
Done!
30
21
-50

UPDATE:

Above program is my own one that added according to your question before you update it. In your update you have added your program that you tried. And your updated question is:

there's no output. (3 means the user will key in 3 lines of integers)

When you run your program there is no errors it is running, you cannot see terminal or if IDE console it is asking for a input.

You can add numbers but loop never stop(infinite) even if you add for a three lines.

The reason is while loop:

while(input.hasNext()){
    total += input.nextInt();             
}

Once program hits the while loop it is never going back to for loop. Because the condition hasNext() check for next input and it alsways has(return true).

Another way I can explain it is, compiler look for next token from input and can still collect input while there is input to be collected inside the loop, while that is true, it keeps doing so.

Solution:

If you can keep variable for special character or word("exit") to end loop it is good. But as a solution for your code, you can declare a variable and increment it in each iteration untill it getting equal to your first input number.

Code should look like this:

Scanner input = new Scanner(System.in);
int k = input.nextInt();
int total = 0;
int count = 0;
while(count != k && input.hasNext()){
    count++;
    total += input.nextInt();
}
System.out.println(total);

This will get only one line. To get more lines try my program above. And read this to learn more about hasnext().

Blasanka
  • 21,001
  • 12
  • 102
  • 104
0

You can save each line in a variable then create scanner for this line to read each number at it until newline is entered:

  public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int k = Integer.parseInt(input.nextLine());
        int total;
        for(int i = 0; i < k; i++){
           total = 0; 
           String line = input.nextLine();
           Scanner lineToken = new Scanner(line);
            while(lineToken.hasNextInt()){   
                  total = total + lineToken.nextInt();                     
            }
            System.out.println(total);
        }           
  }

Output:

30
21
-50
Oghli
  • 2,200
  • 1
  • 15
  • 37
  • 1
    I'm sorry but could explain a little more about the line of " Scanner lineToken = new Scanner(line);"? – Vanessa Leung May 30 '17 at 07:51
  • @VanessaLeung - he is reading a Line as a String and then "tokenizing" that line as series of integers by wrapping that line in another Scanner (not needed , really, but it would work) – TheLostMind May 30 '17 at 09:02
  • @VanessaLeung you are welcome.I am glad to see that it worked for you. sorry for being nervous when commenting on your question because I really get upset to take about an hour to solve your problem and There is no even appreciation for that. – Oghli May 30 '17 at 12:17
  • `Scanner lineToken = new Scanner(line);` I create new scanner variable to read each line tokens individually as integer value in the while loop. – Oghli May 30 '17 at 12:24
  • @TheLostMind Thanks for clarifications.but it 's actually needed and it wouldn't work without that line of code. – Oghli May 30 '17 at 12:29
  • 1
    @Colt - What I mean to say is that there are better ways of converting a String o numbers into ints :P – TheLostMind May 30 '17 at 12:37
  • 1
    @Colt Thanks! I got it :D – Vanessa Leung Jun 01 '17 at 02:34
  • @TheLostMind Thanks for your explanation. You mean like 'Integer.parseInt()' method? – Vanessa Leung Jun 01 '17 at 02:36
  • @VanessaLeung - Its one of the methods yes. But for that you need to split the existing line abd then parse each string as an int – TheLostMind Jun 01 '17 at 05:25
0
import java.util.Scanner;
import java.util.InputMismatchException;

public class ScannerSum {
    public static void main(String[] args) {
        try {
            int sum = 0;
            System.out.println("Type numbers to sum: ");
            Scanner in = new Scanner(new Scanner(System.in).nextLine());
            while (in.hasNext()){
                sum += in.nextInt();
            }
            System.out.println(sum);
        } catch(InputMismatchException e){
            System.out.println("Please type only integers " + e);
        }
    }   
}
Seba
  • 1
  • 2
-4

Create looping statement that will generate row and below is the sample program that will sum all the inputs per row.

System.out.print("Input how many number");
int n = reader.nextInt();
int a;

for(int x; x<=n;x++) {
    System.out.print("Enter a number");
    a = reader.nextInt();

    return a+=a;
}
Sky
  • 1,435
  • 1
  • 15
  • 24
Hu66s
  • 53
  • 7