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

拈花ヽ惹草 提交于 2019-12-02 14:49:36

问题


I just started learning Java (two months and counting), and I still have lots of questions and a whole lot to learn. Right now I want to use the Scanner class to "divide" an integer into its digits. I'll explain myself better with an example:

I request the user to type a four-digit integer, say 8919. What I want to do is to use the Scanner class to divide that integer and to assign each one of its digits to a variable; i.e. a = 8, b = 9, c = 1 and d = 9.

I positively know that it can be done and that the Scanner class is the way to go. I just don't know how to properly use it. Can a noob in need get some help here? Thanks!

EDIT:The suggestion that has been made does not match my specific question. In that thread the class Scanner is not used to separate the integer into digits. I specified i wanted to use the Scannerclass because many different methods used there are still way beyond my level. Anyway, there are lots of interesting ideas in that thread that i hope i will be able to use later, so thanks anyway.


回答1:


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(); 



回答2:


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




回答3:


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!");
        }

    }

}


来源:https://stackoverflow.com/questions/40674211/using-the-scanner-class-in-java-to-get-specific-digits-of-an-integer

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