31

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?

Matthias Braun
  • 24,493
  • 16
  • 114
  • 144
Gopichand
  • 956
  • 1
  • 8
  • 12
  • juse behind you [a link] http://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in-java – beyrem Jun 07 '13 at 09:59
  • 1
    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 '13 at 23:22
  • 3
    There is `Scanner.next(Pattern pattern)` which can be used with `Scanner.hasPattern(Pattern pattern)` for validation. Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28java.util.regex.Pattern%29 This is a pertinent question, please reopen it people ! – andreihondrari Nov 13 '13 at 13:51
  • @AndrewG.H. I made a drastic edit and submitted for reopen. FWIW, I concur. – David J. Liszewski Mar 22 '15 at 03:14

8 Answers8

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.

wizard
  • 1,290
  • 1
  • 9
  • 18
  • @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 07 '13 at 10:37
  • 5
    @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 '13 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.

Aleksander Blomskøld
  • 17,546
  • 9
  • 71
  • 82
2

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);
        });
Matthias Braun
  • 24,493
  • 16
  • 114
  • 144
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.

Jonathan Van Dam
  • 543
  • 7
  • 20
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();
Đēēpak
  • 2,070
  • 5
  • 25
  • 52
  • `StdIn` isn't a class in java. I believe it's a class that the folks at Princeton wrote [link](http://introcs.cs.princeton.edu/java/stdlib/StdIn.java). 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. – Jonathan Van Dam Jul 05 '17 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 );

    }
}
0

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();
}
itzjackyscode
  • 367
  • 3
  • 15
-8

You can format your output in Java as described in below code snippet.

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
   }
}

You can read more here.

kTiwari
  • 1,430
  • 1
  • 14
  • 21