Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在多行输入中使用正则表达式_Java_Regex_String - Fatal编程技术网

Java 如何在多行输入中使用正则表达式

Java 如何在多行输入中使用正则表达式,java,regex,string,Java,Regex,String,/* Bit++语言中的语句是一个序列,只包含一个操作 和一个变量x。语句没有空格,也就是说,它只能 包含字符“+”、“-”、“X”。 执行语句意味着应用它包含的操作 Operation++将变量x的值增加1 操作--将变量x的值减少1。 */ 输入 二, ++x --x 输出应为0。我的代码将输出为-2 代码282A import java.util.regex.*; import java.util.Scanner; public class Bit{ public static

/* Bit++语言中的语句是一个序列,只包含一个操作 和一个变量x。语句没有空格,也就是说,它只能 包含字符“+”、“-”、“X”。 执行语句意味着应用它包含的操作

Operation++将变量x的值增加1

操作--将变量x的值减少1。 */

输入

二,

++x

--x

输出应为0。我的代码将输出为-2

代码282A

import java.util.regex.*;
import java.util.Scanner;

public class Bit{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        sc.nextLine();
        int x = 0;
        
        while(n-->0){
            Pattern p1 = Pattern.compile("[+]{2}[X]");  // Change
            
            Matcher m1 = p1.matcher(sc.nextLine());
            
            boolean b1 = m1.matches();
            
            if(b1){
                ++x;
            }else{
                --x;
            }
        }
        System.out.println(x);
    }
}
更新了你的代码。您忘记在++之后添加[X],因此您的模式不匹配,每次b1变为false并导致
--X

你也需要考虑X++,否则你会得到WA

它写得很明智:

我选择用正则表达式解决一个问题。现在我有两个问题

如果不必执行以下操作,请不要使用正则表达式:

while (n-->0) {                
    if (sc.nextLine().contains("++")) {
        ++x;
    } else {
        --x;
    }
}

[X]是如何工作的。
while (n-->0) {                
    if (sc.nextLine().contains("++")) {
        ++x;
    } else {
        --x;
    }
}