Skip to content
Sign upLog in
← Back to Community

Using Scanner Class (Newbie struggles)

Profile icon
BatuhanBatuhan

I am trying to write a program that will ask the user to enter integers between 0 and 1000 and the program is supposed to count how many of each number is entered. When the user enters a number larger than 1000 the program will printout how many of each number was entered and will exit.

I am struggling using Scanner class.

Is using a loop necessary for this task?

Scanner x = new Scanner(System.in); a = x.nextInt(); if(a<1001) { sayac[a]++; }

My question is let's assume the user entered 8 88 888.
Does Scanner.nextInt take only 8 and ignore the rest
or
does only take the last number entered and assign it to a?

I thought maybe (wishful thinking :) the program would skip back and run the if condition everytime a new number was entered until nextInt was closed.

I guess I could do it by using a loop but I wanted to ask anyway how exactly nextInt works and what it does.

Answered by TheDrone7 [earned 5 cycles]
View Answer
Voters
Profile icon
leonardngandeu
Profile icon
JasmineKLee
Profile icon
BatuhanBatuhan
Comments
hotnewtop
Profile icon
TheDrone7

Looping is used when you want to run a same block of code multiple times, of course you can copy-paste the code you want to repeat multiple times but that is very time consuming and inefficient. That's why looping is recommended but not necessary.

Scanner.nextInt() will take whatever the input is given by the user and store it in a.
For example:-
If user enters 88 it will store 88 in a.
If the user enters 8088 then it will store 8088 in a. Also, if user enters 8 88 it will give an error because nextInt only allows numerical values.

Please mark this as the correct answer if this helps.

Profile icon
BatuhanBatuhan

@TheDrone7
Wow that was quick. Thanks a billion.

Profile icon
TheDrone7

@BatuhanBatuhan
you're most welcome.