Hello. I wrote a code and it works, but it doesn't pass... could you help me? ;)

/ Calculate a sum Write a program that reads from keyboard numbers and calculates their sum. If the user enters -1, the program should display the sum and terminate. -1 should be included in sum. /

public class Solution { public static void main(String[] args) throws Exception
{

    Scanner skaner = new Scanner(System.in);
    int sum=0;

    while (true)
    {
        int a = skaner.nextInt();
        if (a != (-1))
        { sum+=a;
            System.out.println(sum);
        } 
         else{
            System.out.println(sum+a);
            break;
        }
    }
}

}

asked 02 Aug, 13:07

Angban94's gravatar image

Angban94
11
accept rate: 0%

edited 02 Aug, 13:15


Maybe you should do it without "if".Try with something like

 while(!a.equals("-1"))

and here is my solution:

public class Solution
{
public static void main(String[] args)   throws Exception
{
    int B = 0;
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    for(; true ;){
        String a = reader.readLine();
        int A = Integer.parseInt(a);
        B = B+A;
        if(a.equals("-1")){
            System.out.println(B);
            break;
        }

    }

}

}

link

answered 02 Aug, 14:31

artux's gravatar image

artux
11
accept rate: 0%

edited 02 Aug, 14:43

Level three:

Sometimes it’s convenient to use Scanner, but mostly it doesn’t help much. It is better to use BufferedReader and InputStreamReader. I’ve just shown Scanner class for you to know that it exists. We are not going to use it.

link

answered 02 Aug, 15:16

YourDoom's gravatar image

YourDoom
1811
accept rate: 35%

edited 02 Aug, 15:19

I did it:) This is my soluion.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    int num = Integer.parseInt(reader.readLine());
    int sum = num;
    while(num != -1){
        num = Integer.parseInt(reader.readLine());
        sum = sum + num;
    }
    System.out.print(sum);
link

answered 28 Nov, 17:33

Javier%20Pe%C3%B1a's gravatar image

Javier Peña
1
accept rate: 0%

Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×34
×7
×4

Asked: 02 Aug, 13:07

Seen: 162 times

Last updated: 28 Nov, 17:33