我的程序符合,但不显示任何信息
问题描述:
我写这个程序来检查,如果{
[
(
"
/*
与}
]
)
"
*/
要求我们忽略的东西在注释块平衡。当我在终端上运行我的代码时,遇到了一个问题,无法打印出来。我知道错误在哪里,但我不知道为什么它是错误的。之后我尝试编写代码无视意见,我开始得到这个奇怪的问题。我们需要写出自己的堆栈类称为MyStack.java不过,所以我不会在这里包含它是非常简单的。我的程序符合,但不显示任何信息
我认为问题发生在这里:
int start = str.indexOf("/*");
int end = str.indexOf("*/");
if(start != -1){
str = str.substring(0,start) + str.substring(end+2);
这里是整个代码:我希望没有任何逻辑上的谬误
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SymbolBalance {
public static void main(String[] args){
if(args.length>0){
try{
Scanner input = new Scanner(new File (args[0]));
MyStack<Character> ms = new MyStack<>();
String str;
char ch;
boolean quoteStart = true;
loop: while(input.hasNext()){
str = input.next();
int start = str.indexOf("/*");
int end = str.indexOf("/*");
if(start != -1){
str = str.substring(0,start) + str.substring(end+2);
for(int i=0;i<str.length();i++){
ch = str.charAt(i);
if(ch == '{'||ch =='(' || ch=='[')
{
ms.push(ch);
}
else if((ch == '/'&&i<str.length() -1&&str.charAt(i+1)=='*')){
ms.push(str.charAt(i+1));
}
else if (ch==')'){
if(ms.isEmpty()||ms.pop()!= '('){
System.out.println(") is mismatched");
break loop;
}
}
else if(ch == ']'){
if(ms.isEmpty() || ms.pop() != '['){
System.out.println("] is mismatched");
break loop;
}
}
else if(ch == '}'){
if(ms.isEmpty() || ms.pop() != '{'){
System.out.println("} is mismatched");
break loop;
}
}
else if(ch == '*' && i<str.length()-1&&str.charAt(i+1) == '/'){
if(ms.isEmpty() || ms.pop() != '*'){
System.out.println("*/ is mismatched");
break loop;
}
}
else if(ch == '"'){
if(quoteStart == true) {
ms.push(ch);
quoteStart = false;
}
else {
if(ms.isEmpty() || ms.pop() != '"'){
System.out.println(" \" is mismatched");
break loop;
}
quoteStart = true;
}
}
}
}
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("Cannot find file");
}
}
else{
System.out.println("No command line argument");
}
}
}
在这里,我有一个例子输入文件:
/* this is to test whether the program ignores imbalances in the comment blocks */
public class Test3 {
public static void main(String[] args) {
boolean haveYouWatchedHamiltonYet = true;
int theSchuylerSisters = 3;
int alexanderhamilton = 1;
int aaronburr = 1;
boolean amIintheroom = theRoomWhereItHappens();
/* this is a commented block. We're testing if your code
can deal with unbalanced things in the comments: /*
that was the test for here */
}
/*just a general comment */
/* this one has some errors /* { [ { [ } ] */
public boolean theRoomWhereItHappens() {
boolean intheRoomWhereItHappens = false;
boolean isHappyAboutThis = false;
return intheRoomWhereItHappens && isHappyAboutThis;
}
}
答
您使用的是相同的字符来评论的开始和结束都:
int start = str.indexOf("/*");
int end = str.indexOf("/*");
结束注释字符串应该是:
int end = str.indexOf("*/");
+0
喜,连这个编辑的代码仍然不工作了。 – Kat
你应该问一个问题前调试代码。 –
“*我认为,问题发生在这里*”你为什么这么想?你怀疑问题*是什么?你有什么尝试?你遇到了什么问题,你不知道如何解决? *是一个问答网站,而不是一个调试服务。 – dimo414
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – EJoshuaS