I'm writing a simple program in dr java to read a string and then compare the first and last characters. I tried to put some validation into it, but I'm having trouble with the syntax:
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
Error is about the if statement checking for spaces within the while loop:
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);
} }
This line:
if (word.charAt(charactercount) == " "){
is using ==
to compare 2 different things, left is a char, and right is a String. So they can't be equal even if they're both spaces. The char version of a space looks like ' '
.
There's other problems which will stop that code from working, but that's the one you're asking about at the moment.