Jeśli ktoś naprawdę chciał mogliby zrobić tam własną wersję scanf()
tak:
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());
}
}
}
}
Oczywiście moje metody tylko sprawdzić, łańcuchów i liczb całkowitych, jeśli chcesz, aby różne typy danych były przetwarzane, dodaj odpowiednie listy i sprawdź je. Ponadto, hasNext()
powinien prawdopodobnie znajdować się na dole sekwencji if-else if
, ponieważ od hasNext()
zwróci wartość true dla wszystkich danych w łańcuchu.
wyjściowa:
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
nie
Prawdopodobnie najlepszym przykładem; ale chodzi o to, że Scanner
implementuje klasę Iterator
.Ułatwianie iteracji poprzez wejście skanerów za pomocą metod hasNext<datatypehere>()
; a następnie przechowywanie danych wejściowych.
juse za sobą [link] http://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the- standard-input-in-java – beyrem
Dlaczego Downvotes ...? Myślę, że jest po prostu początkującym użytkownikiem języka Java. Czego możemy się spodziewać od początkującego, On po prostu chce znaleźć jakiś związek między C a Javą –
Java ma 'String.format (format, args)' (co jest całkiem podobne do printf). Zrozumiałe jest, że ktoś chce wiedzieć czy jest odpowiednik 'scanf'. Nie wiem, dlaczego to pytanie jest przegłosowane. – 4gus71n