我正在 dr java 中编写一个简单的程序来读取字符串,然后比较第一个和最后一个字符。我尝试对其进行一些验证,但我在语法上遇到了问题:
1 error found:
File: /Users/Luke/Documents/University/Programming/Lab/Week 10/wordAnalysis.java [line: 11]
Error: /Users/Luke/Documents/University/Programming/Lab/Week 10/wordAnalysis.java:11: incomparable types: char and java.lang.String
错误与 if 语句检查 while 循环内的空格有关:
import java.util.*;
public class wordAnalysis {
public static void main(String [] args) {
String word;
int charactercount;
Scanner sc = new Scanner(System.in);
System.out.println("Please type a word without spaces, (done to stop) ");
word = sc.next();
while (charactercount <= word.length()) {
if (word.charAt(charactercount) == " "){
System.out.println("your word cannot contain spaces please try again.");
wordAnalysis.main(args);
}
}
if (word == "done"){
System.exit(0);
}
if (word.charAt(0) == word.charAt(word.length() - 1)) {
System.out.print("the words first and last letter are the same!");
}
else {
System.out.println("the words first and last letters dont match, try again...");
}
wordAnalysis.main(args);
} }
最佳答案
这一行:
if (word.charAt(charactercount) == " "){
使用==
来比较两个不同的东西,左边是一个字符,右边是一个字符串。所以即使它们都是空格,它们也不可能相等。空格的字符版本类似于 ' '
。
还有其他问题会阻止该代码工作,但这就是您目前要问的问题。
关于Java字符串字符分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21783037/