Storing userinputed ints | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Storing userinputed ints

Hey ,i'm new to the java world so i don't know if it is a silly question or not,so please forgive me if it is. ^^ I was just wording if i could make a program that let the user enter an unknown number of ints,and that it will store all of them,kind of like to fill an array. maybe with the help of "..." as in "(int...numbers)". i want to use this loop : and that it will store all the numbers that the user is giving,becuase later i want to so stuff with them ( like sum or put them in an array ) import.java.util.Scanner; public class e5x1 { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); System.out.println("Please enter a number , 0 to exit"); int usernumber = userInput.nextInt(); while (usernumber > 0) { if (usernumber > 0) { System.out.println("thank you"); usernumber = userInput.nextInt(); } } } }

29th Nov 2016, 11:00 PM
Eyal Delarea
Eyal Delarea - avatar
5 Answers
+ 3
well if you want to have a collection of the elements whether these are user inputs or not, you should use a data structure like array,list,variables,... to save them and after that you can access them to any stuff you want.
29th Nov 2016, 11:36 PM
Nima Moradi
Nima Moradi - avatar
+ 3
if you don't know that user input how many exactly, you should use "list" else you can use an array and initialized it's size when you declare it. so for your example, you should declare an arraylist(list) in your code like this: import.java.util.*; public class e5x1 { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); ArrayList<Integer> list=new ArrayList<>(); System.out.println("Please enter a number , 0 to exit"); int usernumber = userInput.nextInt(); while (usernumber > 0) { list.add(usernumber); System.out.println("thank you"); usernumber = userInput.nextInt(); } System.out.println(list); //print the list of numbers } } according to the first line: import java.util.*; which means you import all of the classes of util package to use them in your code ArrayList and Scanner classes (in this sample code)
29th Nov 2016, 11:57 PM
Nima Moradi
Nima Moradi - avatar
+ 1
Thank you very much! that's what i was looking for ^^
30th Nov 2016, 9:54 AM
Eyal Delarea
Eyal Delarea - avatar
+ 1
@Eyal ur wlc ;)
30th Nov 2016, 10:00 AM
Nima Moradi
Nima Moradi - avatar
0
yeah,i'm asking how to do it. like int x[]=[a,b,c,d,e...] which all of them are userinputed. and then i can like print them.
29th Nov 2016, 11:39 PM
Eyal Delarea
Eyal Delarea - avatar