Reputation: 1
I'm a beginner to the Java language. Firstly I want use a Scanner to retrieve data
For example, I enter this: 990921205 v
How can I detect the first 2 numbers for any calculation? How can I detect each numbers for an algorithm?
I tried this:
import java.util.Scanner;
class ID2 {
public static void main(String args[]){
Scanner in=new Scanner (System.in);
int num[]=new int[3];
int A=0;
int B=0;
int C=0;
System.out.println("enter a number " +A);
}
}
Upvotes: 0
Views: 214
Reputation: 159
The answer @bigdestroyer gives this error:
The method parseInt(String) in the type Integer is not applicable for the arguments (char)
You can just do it with char
and not with integers at all.
For example,
Scanner input = new Scanner(System.in);
String numInput = input.next();
char nums[] = new char[numInput.length()];
for (int i = 0;i < numInput.length(); i++){
nums[i] = numInput.charAt(i);
System.out.println("For nums["+i+"] : "+nums[i]);
}
Input:
0123456789
Output:
For nums[0] : 0
For nums[1] : 1
For nums[2] : 2
For nums[3] : 3
For nums[4] : 4
For nums[5] : 5
For nums[6] : 6
For nums[7] : 7
For nums[8] : 8
For nums[9] : 9
Now since you want the first 2,3,4++ digits, you can apply the answer @chsdk gave.
If you use mine you have to parse them to integer using Integer.parseInt()
to be sure that it's an actual number.
Upvotes: 1
Reputation: 32145
Well to get the inputted values you can use Scanner.next()
, but if this inputted value is an int you can also use Scanner.nextInt()
to read it as an integer:
int value1= in.nextInt();
Then you will have an integer in the value1
value.
But if you are entering a string you will use the Scanner.next()
to get this string and then extract the first two elements:
String s=in.next();
int firstTwoval=Integer.parseInt(s.substring(0, 2));
Upvotes: 1
Reputation: 26034
With next()
method of Scanner
you can obtain user standard input.
String userInput = in.next();
int first = Integer.parseInt(userInput.charAt(0));
int second = Integer.parseInt(userInput.charAt(1));
//DO STUFF
Upvotes: 1