Java的输出还好,输入就很麻烦了。
输出
System.out.print(1); // 输出单个值,不自动带换行
System.out.println(); // 输出单个值,自动带换行。
System.out.printf("", vars); //c风格的格式化输出
public class Main {
public static void main(String[] args) {
System.out.printf("%d %s %.2f",1,"2",123.456);
}
}
好了,接下来我们看输入。
输入
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // 创建Scanner对象
System.out.print("Input your name: "); // 打印提示
String name = scanner.nextLine(); // 读取一行输入并获取字符串
System.out.print("Input your age: "); // 打印提示
int age = scanner.nextInt(); // 读取一行输入并获取整数
System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
}
}
简而言之,就是:
import java.util.*;
***
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt(); //读取一行整数
嗯?什么??用java刷算法题这么麻烦的嘛?读取一行整数??那怎么赋值给想要的变量呢?
以下是经典问题a+b的小demo。
package program;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[3];
for(int i = 0; i < 2; i++){
arr[i] = scanner.nextInt();
}
arr[2] = arr[0] + arr[1];
System.out.println(arr[2]);
}
}
我感觉也就是这样了吧。不行的话日后再说。
String name = scanner.nextLine(); // 读取一行字符串
java读取多组数据
package program;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Solution solution = new Solution();
solution.setAAndB();
}
}
class Solution {
public void setAAndB(){
Scanner scanner = new Scanner(System.in);
int a,b;
while(scanner.hasNext()) {
a = scanner.nextInt();
b = scanner.nextInt();
System.out.println(a+b);
}
}
}
带退出条件的多组输入
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Solution solution = new Solution();
solution.setAAndB();
}
}
class Solution {
void setAAndB(){
Scanner scanner = new Scanner(System.in);
int a,b;
while(scanner.hasNext()) {
a = scanner.nextInt();
b = scanner.nextInt();
if(a == 0 && b == 0){
return;
}
System.out.println(a+b);
}
}
}
甚至单组输入也能这么玩:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Solution solution = new Solution();
solution.setAAndB();
}
}
class Solution {
void setAAndB(){
Scanner scanner = new Scanner(System.in);
int a,b;
while(scanner.hasNext()) {
a = scanner.nextInt();
b = scanner.nextInt();
System.out.println(a+b);
}
}
}
总之啦,java的Scanner对象的next()方法族(比如next(),nextInt(),nextFloat()等等等等)是一个类似于C语言中scanf的一个东西,它只读想要的内容。比如nextInt,只读数字,自动跳过其他字符。 next只读有效内容,自动跳过空格,换行之类的字符。
而nextLine()就相当于C语言中的gets()函数,读取回车之前的所有字符。
所以说在next()方法族后要用nextLine()读点东西怎么办?需要在这两个方法中间再加一个nextLine()来消除next()方法族中留在输入缓冲区中的回车键。