【发布时间】:2020-10-20 13:33:17
【问题描述】:
这是我正在尝试执行的代码,但无论输入是什么,我都会得到相同的结果,即“ 不是关键字”。
这里是关键字列表:{break, case, continue, default, defer, else, for, func, goto, if, map, range, return, struct, type, var}
如果我的输入字符串出现在关键字列表中,我想打印 " is a keyword"; else print " 不是关键字".
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package word.is.key;
/**
*
* @author JagritSharma
*/
import java.util.*;
public class WordIsKey {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input= new Scanner(System.in);
String s= "break, case, continue, default, defer, else, for, func, goto, if, map, range, return, struct, type, var";
String[] keywords= s.split(",", 16);
String n= input.nextLine();
String res= n+" is not a keyword";
for(int i=0;i<keywords.length;i++){
if(keywords[i].equals(n)){
res= n+" is a keyword";
break;
}
}
System.out.println(res);
}
}
【问题讨论】:
-
尝试拆分
", "而不是","。 Python不会自动删除空格,你必须自己做。 -
您还可以使用 trim() 函数删除开头和结尾的空格。一个简单的
keywords[i].trim().equals(n)应该可以让您的代码按预期工作
标签: java if-statement