Is there an equivalent method to C's scanf in Java?

前端 未结 7 1175
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 11:58

Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversio

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 12:45

    If one really wanted to they could make there own version of scanf() like so:

        import java.util.ArrayList;
        import java.util.Scanner;
    
    public class Testies {
    
    public static void main(String[] args) {
        ArrayList nums = new ArrayList();
        ArrayList strings = new ArrayList();
    
        // get input
        System.out.println("Give me input:");
        scanf(strings, nums);
    
        System.out.println("Ints gathered:");
        // print numbers scanned in
        for(Integer num : nums){
            System.out.print(num + " ");
        }
        System.out.println("\nStrings gathered:");
        // print strings scanned in
        for(String str : strings){
            System.out.print(str + " ");
        }
    
        System.out.println("\nData:");
        for(int i=0; i strings, ArrayList nums){
        Scanner getLine = new Scanner(System.in);
        Scanner input = new Scanner(getLine.nextLine());
    
        while(input.hasNext()){
            // get integers
            if(input.hasNextInt()){
                nums.add(input.nextInt());
            }
            // get strings
            else if(input.hasNext()){
                strings.add(input.next());
            }
        }
    }
    
    // pass it a string for input
    public static void scanf(String in, ArrayList strings, ArrayList nums){
        Scanner input = (new Scanner(in));
    
        while(input.hasNext()){
            // get integers
            if(input.hasNextInt()){
                nums.add(input.nextInt());
            }
            // get strings
            else if(input.hasNext()){
                strings.add(input.next());
            }
        }
    }
    
    
    }
    

    Obviously my methods only check for Strings and Integers, if you want different data types to be processed add the appropriate arraylists and checks for them. Also, hasNext() should probably be at the bottom of the if-else if sequence since hasNext() will return true for all of the data in the string.

    Output:

    Give me input: apples 8 9 pears oranges 5 Ints gathered: 8 9 5 Strings gathered: apples pears oranges Data: 8 apples 9 pears 5 oranges

    Probably not the best example; but, the point is that Scanner implements the Iterator class. Making it easy to iterate through the scanners input using the hasNext() methods; and then storing the input.

提交回复
热议问题