Java 识别字符串或数组中字符的有效输入
我们被要求在每行示例中检查字符串的以下输入Java 识别字符串或数组中字符的有效输入,java,arrays,string,Java,Arrays,String,我们被要求在每行示例中检查字符串的以下输入 A = B + C A = 3 + C + 99 B = ( ( 4 + B ) + D ) 现在考虑到这些字符串可能是错误的是 + - :: if two operator are next together A B :: IF two letters are next together 1 2 :: if two numbers are next together all numbers must be integer Letters must
A = B + C
A = 3 + C + 99
B = ( ( 4 + B ) + D )
现在考虑到这些字符串可能是错误的是
+ - :: if two operator are next together
A B :: IF two letters are next together
1 2 :: if two numbers are next together
all numbers must be integer
Letters must only be A B or C
the parenthesis should have endings... ( ) not like ( (
现在我认为其中一个解决方案是if-else,使用isdigit
,isalpha
,检查彼此相邻的字符,如果它们是相同的字符类型isdigit,isspacechar,isalpha示例(当前正在检查[1][3])array[1][5]=['A','B','+','C']
它看起来像是['A'、'='、'B'/*检查*/、'+'、'C'/*检查*/]
因为输入来自文本文件,所以我正在这样做
fR = new FileReader("input.txt");
bR = new BufferedReader(fR);
Inp = new Scanner(fR);
x=0;
while(Inp.hasNextLine()) {
int y=0;
while(Inp.hasNextLine()) {
stringarray[x][y];
y++;
}
x++;
}
我该怎么做呢?
或者我应该继续使用数组字符,但我又不知道如何跳过空格。。所以我想这将是一个不同的讨论。。我不知道如何做括号部分。关于跳过空格,请使用trim()方法使用点连接符删除字符串两侧的空格。看起来这是两个独立的问题 1) 如何读取文件内容并在程序中创建循环内容
2) 如何执行检查 对于(1)我建议如下
List<String> lines = new ArrayList<String>();
fR = new FileReader("input.txt");
bR = new BufferedReader(fR);
inp = new Scanner(fR);
try {
while(inp.hasNextLine()){
lines.add(imp.nextLine());
}
imp.close();
} catch (FileNotFoundException | IOException e) {
e.printStackTrace();
}
List line=new ArrayList();
fR=新文件读取器(“input.txt”);
bR=新的缓冲读取器(fR);
inp=新扫描仪(fR);
试一试{
while(inp.hasNextLine()){
line.add(imp.nextLine());
}
小鬼关闭();
}捕获(FileNotFoundException | IOException e){
e、 printStackTrace();
}
及(二)
String regex=”“;
Pattern=Pattern.compile(regex);
Matcher Matcher=pattern.Matcher(“”);
用于(字符串l:行){
if(matcher.reset.matches()){
//做点什么
}
}
您可以在此处在线测试正则表达式字符串:
可能需要一段时间才能把绳子弄对我现在掌握了大部分。但仍有一些规则我无法应用
String regex = "<regex for checking goes here>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("");
for (String l : lines) {
if (matcher.reset(s).matches()) {
// do something
}
}