2

While trying to run a small program in java, I'm getting the following error:

HangmanSB.java:19: error: unexpected type
            if (sentence.charAt(i) = " "){
                               ^
  required: variable
  found:    value
1 error

I tried reading the answers to a similar question posted on this website, yet I still can't seem to understand how to fix the error the program is giving me.

import java.util.Scanner;

class HangmanSB {

   public static void main(String[] args){

      Scanner keyboard = new Scanner(System.in);

      String sentence = keyboard.nextLine();

      int turns = keyboard.nextInt();

      for (int turnsLeft = turns; turnsLeft > 0; turnsLeft--){

         int length = sentence.length();

         for (int i = 0; i < length; i++){

            if (sentence.charAt(i) = " "){
               System.out.println(" ");
            }

            else {
               System.out.print("_");
            }
         }
      }
  }

}
Abhishek Jain
  • 3,562
  • 2
  • 26
  • 44
Sam
  • 315
  • 1
  • 3
  • 14
  • 1
    Possible duplicate of [How to check if a char is equal to an empty space?](https://stackoverflow.com/questions/4510136/how-to-check-if-a-char-is-equal-to-an-empty-space) – Pavneet_Singh Apr 23 '18 at 14:54
  • 2
    `=` is the assignment operator, `==` is the equality comparision operator. You cannot assign something to a function call. – OH GOD SPIDERS Apr 23 '18 at 14:55
  • Compiler complains about assignation `=` instead of `==`, chars should be enclosed in single quotation too – Klaimmore Apr 23 '18 at 15:00

4 Answers4

3

There are two errors:

public char charAt(int index) method returns char

and

you need to use == instead of assignment operator =

Thus use:

if (sentence.charAt(i) == ' '){
    System.out.println(" ");
}
Ascalonian
  • 14,409
  • 18
  • 71
  • 103
Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23
0

your error is here :

 if (sentence.charAt(i) = " ")

change it to this

if (sentence.charAt(i) == ' ')

use == to compare int or char

Elarbi Mohamed Aymen
  • 1,617
  • 2
  • 14
  • 26
  • If I do so, I get the following error: HangmanSB.java:19: error: incomparable types: char and String if (sentence.charAt(i) == " "){ ^ 1 error – Sam Apr 23 '18 at 14:56
  • 3
    Also the double quotes are wrong. Needs to be `' '` (a char) instead of `" "` (a string). – khelwood Apr 23 '18 at 14:56
0
if (sentence.charAt(i) == ' '){
Johannes
  • 2,021
  • 2
  • 23
  • 40
  • 3
    Correct solution, but it is good to provide an explanation as to why this is the fix, so they can learn and understand and avoid the issues in the future – Ascalonian Apr 23 '18 at 15:02
0

There are 2 types of errors = and " "

To compare char value, use ' ' and ==

Like this :

if (sentence.charAt(i) == ' ')
iLyas
  • 1,047
  • 2
  • 13
  • 30