ACM代码模式笔记

系列博客目录



1.换行符

  1. nextInt()nextDouble() 等不会消耗换行符

    • 当使用 nextInt()nextDouble() 读取数字时,它只读取数字部分,不会消耗掉输入后的换行符。
  2. nextLine() 会读取并消耗换行符

    • nextLine() 会读取整行文本并消耗掉换行符,直到遇到换行符为止。
  3. 问题出现的场景

    • 如果先用 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值