系列博客目录
文章目录
- 系列博客目录
- 1.换行符
1.换行符
-
nextInt()
、nextDouble()
等不会消耗换行符:- 当使用
nextInt()
或nextDouble()
读取数字时,它只读取数字部分,不会消耗掉输入后的换行符。
- 当使用
-
nextLine()
会读取并消耗换行符:nextLine()
会读取整行文本并消耗掉换行符,直到遇到换行符为止。
-
问题出现的场景:
- 如果先用
nextInt()
或nextDouble()
读取数字,紧接着使用nextLine()
,nextLine()
会直接读取到之前未被消耗的换行符,导致它返回空字符串。
- 如果先用
解决方案:
- 在读取数字后,调用一个额外的
nextLine()
来消耗掉换行符:int num = sc.nextInt(); // 读取数字 sc.nextLine(); // 清除换行符 String line = sc.nextLine(); // 读取下一行
这样就能避免 nextLine()
读取到空行的问题。
或者
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine()); // 先读取行,再转换为整数
作者:林小白zii
链接:https://www.nowcoder.com/discuss/728691373678878720
来源:牛客网
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
while(num -- > 0){
String string = sc.nextLine();
StringBuilder t = new StringBuilder();
int p = 0;
for(char c : string.toCharArray()){
if(Character.isDigit(c)){
p = p * 10 + c - '0';
}else{
if(t.length() > 1){
p = p % t.length();
}
String rotated = t.toString();
rotated = rotated.substring(p) + rotated.substring(0, p);
t = new StringBuilder(rotated);
p = 0;
if(c == 'R'){
t.reverse();
}else{
t.append(c);
}
}
}
System.out.println(t);
}
}
}
样例输入
2
meRD2o
D0ame3
样例输出
Demo
Dame