Using the Scanner class in Java to get specific digits of an integer [duplicate]

这一生的挚爱 提交于 2019-12-02 10:22:44

You can use a delimiter with the scanner. You can use an empty string as delimiter for this case.

String input = "8919";
Scanner s = new Scanner(input).useDelimiter("");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
d = s.nextInt();
s.close(); 

you should read the integer as whole number and store it in a variable. after you stored it you can split it up. other way is so store it as string and then split the string. what you should choose depends on what youwant to do with it afterwards

Try this:

import java.util.Scanner;

public class ScannerToTest {

    public static void main(String[] args) {

        int a,b,c,d;

        System.out.print("Please enter a 4 digit number : ");
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();

        String numberToString = String.valueOf(number);

        if(numberToString.length() == 4) {
            String numberArray [] = numberToString.split("");
            a = Integer.parseInt(numberArray[1]);
            b = Integer.parseInt(numberArray[2]);
            c = Integer.parseInt(numberArray[3]);
            d = Integer.parseInt(numberArray[4]);
            System.out.println("Value of a is : " + a);
            System.out.println("Value of b is : " + b);
            System.out.println("Value of c is : " + c);
            System.out.println("Value of d is : " + d);
        }else {
            System.out.println("Numbers beyond 4 digits are disallowed!");
        }

    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!