当前位置: 首页 > news >正文

ACM代码模式笔记

系列博客目录


文章目录

  • 系列博客目录
  • 1.换行符


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

相关文章:

  • 学透Spring Boot — 011. 一篇文章学会Spring Test
  • 操作系统——2.4 (管程与死锁的基本概念)
  • 第六章:分布式共识_《凤凰架构:构建可靠的大型分布式系统》
  • 解码 __iter__ 和 itertools.islice - 迭代的艺术
  • 数据结构(5)——栈
  • 【Python爬虫高级技巧】BeautifulSoup高级教程:数据抓取、性能调优、反爬策略,全方位提升爬虫技能!
  • cpp自学 day19(多态)
  • 一周学会Pandas2 Python数据处理与分析-NumPy数据类型
  • 【JavaWeb-Spring boot】学习笔记
  • 通过枚举、AOP、注解、反射填充公共字段
  • MySQL的进阶语法8(SQL优化——insert、主键、order by、group by、limit、count和update)
  • k8s pod security context 总结笔记
  • 自旋锁(C++实现)
  • js中一些便捷用法
  • 记一次表格数据排序优化(一)--排序30000条数据有多卡
  • MySQL基础 [一] - Ubuntu版本安装
  • Cribl 创建Dataset
  • NDK开发:JNI编程基础
  • 【C++】从零实现Json-Rpc框架(2)
  • 基于SpringBoot+Vue实现的二手交易市场平台功能一