Java具有与format strings in other languages非常相似的format strings概念。它在String#format()
等JDK方法中用于输出转换。
我想知道在Java中是否有类似于C's scanf
的输入转换方法?
发布于 2013-06-07 18:01:24
看看this site,它解释了两种从java控制台读取数据的方法,分别是使用Scanner
或System.in中的经典InputStreamReader
。
以下代码取自引用的网站:
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);
}
}
致以问候。
发布于 2013-06-07 17:58:08
在标准Java中没有纯粹的scanf替代,但是您可以使用java.util.Scanner来解决使用scanf解决的相同问题。
发布于 2019-10-22 22:22:50
不是等效项,但您可以使用Scanner和模式来解析由空格分隔的三个非负数的行,例如:
71 5796 2489
88 1136 5298
42 420 842
下面是使用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);
});
https://stackoverflow.com/questions/16981232
复制相似问题