This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?

(19个回答)


6个月前关闭。





import java.util.*;
public class Hello {
    public static void undoOper(String str) {
        List<Character> lis = new ArrayList<>();
        char[] arr = str.toCharArray();
        for (char ch : arr) {
            lis.add(ch);
        }
        for (int i = 0; i < lis.size(); i++) {
            if (lis.get(i) == '^') {
                lis.remove(i);
                lis.remove(i - 1);
                i = i - 2;
            }
        }
        if (lis.size() == 0)
            System.out.print("-1");
        for (int i = 0; i < lis.size(); i++) {
            System.out.print(lis.get(i));
        }

        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        String[] str = new String[N];
        for (int i = 0; i < N; i++) {
            str[i] = sc.nextLine();
        }
        for (int i = 0; i < N; i++) {
            undoOper(str[i]);
        }
    }
}


该程序用于撤消操作
该程序接受N个字符串值。字符^表示撤销操作以清除最后一个上一个字符。

输入:

Hey ^goooo^^glee^
ora^^nge^^^^


输出:

Hey google
-1(since all char gets erased)


我的输出:

-1
Hey google

最佳答案

final static Pattern pattern = Pattern.compile("\\^", Pattern.MULTILINE);

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt(); //because \n is appended with previous nextInt
        sc.nextLine();
        String[] outPut = new String[N];
        for (int i = 0; i < outPut.length; i++) {
            String input = sc.nextLine();
            Matcher matcher = pattern.matcher(input);
            input = matcher.replaceAll("");
            outPut[i] = input;
        }
        sc.close();
        System.out.println(Arrays.asList(outPut));
    }


看看这是否对您有帮助

10-06 12:52
查看更多