34

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 conversion.

I was wondering if there's an input conversion method akin to C's scanf in Java?

4
  • juse behind you [a link] stackoverflow.com/questions/2506077/…
    – beyrem
    Jun 7, 2013 at 9:59
  • 3
    Java have the String.format(format, args) (what It's pretty simmilar to printf) It's understandable that someone wants to know if there's a scanf equivalent. I don't know why this question is down voted.
    – 4gus71n
    Oct 14, 2013 at 23:22
  • 3
    There is Scanner.next(Pattern pattern) which can be used with Scanner.hasPattern(Pattern pattern) for validation. Reference: docs.oracle.com/javase/7/docs/api/java/util/… This is a pertinent question, please reopen it people ! Nov 13, 2013 at 13:51
  • @AndrewG.H. I made a drastic edit and submitted for reopen. FWIW, I concur. Mar 22, 2015 at 3:14

7 Answers 7

20

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.

Following code is taken from cited website:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

Regards.

2
  • @Gopichand There isn't an exact match in java, but take a look at the Scanner doc, you can read specific type of data from stdin. For example: int i = scanIn.nextInt(); for reading an int.
    – wizard
    Jun 7, 2013 at 10:37
  • 6
    @Gopichand Sadly there's no exact method like scanf in java. The better approach that you could do is split a String and then take the tokens and cast them. If someone differs with me, then show me an example of scanf("%d %d %s %f",a,b,c,d), one liner equivalent in java!
    – 4gus71n
    Oct 14, 2013 at 23:26
12

There is not a pure scanf replacement in standard Java, but you could use a java.util.Scanner for the same problems you would use scanf to solve.

0
3

Not an equivalent, but you can use a Scanner and a pattern to parse lines with three non-negative numbers separated by spaces, for example:

71 5796 2489
88 1136 5298
42 420 842

Here's the code using findAll:

new Scanner(System.in).findAll("(\\d+) (\\d+) (\\d+)")
        .forEach(result -> {
            int fst = Integer.parseInt(result.group(1));
            int snd = Integer.parseInt(result.group(2));
            int third = Integer.parseInt(result.group(3));
            int sum = fst + snd + third;
            System.out.printf("%d + %d + %d = %d", fst, snd, third, sum);
        });
0
2

C/C++ has a notion of variable references, which makes creating something like scanf much easier. However, in Java, everything is passed by value. In the case of objects, their references are passed by value.

So, it's essentially impossible to have a concise equivalent to scanf. However, you can use java.util.Scanner, which does things similar to scanf.

So this C/C++:

int a;
float b;

scanf("%d %f", &a, &b);

is (roughly) equivalent to this Java:

int a;
float b;
try (Scanner sc = new Scanner(System.in)) {
  a = sc.nextInt();
  b = sc.nextFloat();
}
1

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<Integer> nums = new ArrayList<Integer>();
    ArrayList<String> strings = new ArrayList<String>();

    // 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.size(); i++){
        System.out.println(nums.get(i) + " " + strings.get(i));
    }
}

// get line from system
public static void scanf(ArrayList<String> strings, ArrayList<Integer> 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<String> strings, ArrayList<Integer> 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<datatypehere>() methods; and then storing the input.

0

Java always takes arguments as a string type...(String args[]) so you need to convert in your desired type.

  • Use Integer.parseInt() to convert your string into Interger.
  • To print any string you can use System.out.println()

Example :

  int a;
  a = Integer.parseInt(args[0]);

and for Standard Input you can use codes like

  StdIn.readInt();
  StdIn.readString();
1
  • StdIn isn't a class in java. I believe it's a class that the folks at Princeton wrote link. However, it would work if you had that class in your project. If you look at the code for StdIn they just use a Scanner to read all of the input. Jul 5, 2017 at 23:13
0

THERE'S an even simpler answer

import java.io.BufferedReader;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        String myBeautifulScanf = new Scanner(System.in).nextLine();
        System.out.println( myBeautifulScanf );

    }
}
2
  • 3
    This is not simpler than the accepted answer, it is the same.
    – BitByteDog
    Dec 7, 2017 at 8:09
  • It's way less code, that makes it simpler. All the unimportant parts from the accepted answer were cleaned away Dec 7, 2017 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.