2014-02-14 62 views
0

我正在寫一個簡單的java程序來讀取一個字符串,然後比較第一個和最後一個字符。我試圖把一些驗證了進去,但我有與語法的麻煩: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); 

}}

+0

提示:「string」由'c''h''a''r''' – BRFennPocock

回答

1

這條線:

if (word.charAt(charactercount) == " "){ 

使用==到c ompare 2個不同的東西,左邊是一個字符,右邊是一個字符串。所以即使它們都是空間,它們也不可能是平等的。空間的char版本看起來像' '

還有其他問題會阻止代碼的工作,但這是你現在要詢問的問題。