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.