0

Find the sum of some integers. The first line of each test case will contain an integer n, which gives the number of integers in the array and the next n line(s) contain the integers

input 1#: 5 1 2 3 4 5

output: 15

input 2#: 2 12 12

output: 24

code:

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

        Scanner scanner= new Scanner(System.in); 
        {
            int n[]= {5,1,2,3,4,5};
            int tempobj=n[0];
            int sum=0;
            for(int i=1;i<=tempobj;i++)
            {
                sum= sum+n[i];
            }
            System.out.println(+sum);
        }
    }
}

This code only satisfies the first output. But not the second one. How should I define the array so that can I satisfy the other output when the same code is complied second time?

Draken
  • 3,134
  • 13
  • 34
  • 54
Priyanka Maurya
  • 413
  • 3
  • 7
  • 18
  • 1
    You need to use a loop to read values. Also, where are you even reading data? – TheLostMind May 26 '16 at 15:19
  • 3
    That code doesn't satisfy what the teacher is asking, you aren't even reading the user's input, you're manually creating the test case in the code. You might need to go back to the drawing board a little bit, read up on how to use the scanner function to read a user's input and then start working from there – Draken May 26 '16 at 15:23
  • Thanks, Draken can give some reference as I do not have any idea about it.. – Priyanka Maurya May 26 '16 at 15:57
  • 1
    You can learn about the [scanner class](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) for a start. See http://stackoverflow.com/questions/18838781/converting-string-array-to-an-integer-array for a related question. – UmNyobe May 26 '16 at 16:13

0 Answers0