How to put Scanner and size in an Array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to put Scanner and size in an Array

I wanted to have a program that can only calculate positive integers, and only have a size of 4. Example1: Input: 1 2 -5 6 Output: 9 Example2: Input: 1 2 -5 6 3 Output: Error Im quite new to array, so this is what I did so far: https://code.sololearn.com/c4a2a7A15a1A

16th Jun 2021, 8:45 AM
Brianna
3 Answers
+ 5
For taking numbers of input you have to decide the size of the array , you can ask user to give the size of array int size = in.nextInt(); Then make an array of size given by user int arr[] = new int[size]; By default the array arr contains all elements 0, Now you have to change the elements by user input, use loop to do this int sum = 0; for (int i=0 ; i < size-1 ; i++) { arr[i] = in.nextInt(); if (arr[i] > 0) sum += arr[i]; } Now if the number will be positive then it will be added to sum variable , and at last you can print sum. System.out.println(sum);
16th Jun 2021, 9:35 AM
Abhiyantā
Abhiyantā - avatar
+ 3
You said that you are little bit confused in array? AnĀ arrayĀ is a container object that holds a fixed number of values of a single type. The length of anĀ arrayĀ is established when theĀ arrayĀ is created. After creation, its length is fixed. Each item in anĀ arrayĀ is called an element, and each element is accessed by its numerical index. NOTE - ā€¢ You can't change the size of array it's always fixed credit - oracle.com
16th Jun 2021, 9:37 AM
Abhiyantā
Abhiyantā - avatar
+ 3
Hi Brianna I see Rishav Tiwari has given you a good answer already, but I will post mine also, so you may learn from different techniques. // Created by Brianna import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input= new Scanner (System.in); int my_array[] = new int [4]; int sum = 0; for (int i =0; i <4; i++){ my_array[i] = input.nextInt(); if(my_array[i] >=0){ sum += my_array[i]; } } System.out.println(sum); } } I would suggest you review your understanding of loops & array declarations
16th Jun 2021, 9:47 AM
Rik Wittkopp
Rik Wittkopp - avatar