繁体   English   中英

在Java中运行charAt时发生意外类型错误

[英]Unexpected type error while running charAt in java

尝试在Java中运行小程序时,出现以下错误:

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

我尝试阅读此网站上发布的类似问题的答案,但似乎仍然无法理解如何解决程序给我的错误。

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("_");
            }
         }
      }
  }

}

有两个错误:

public char charAt(int index)方法返回char

您需要使用==代替赋值运算符=

因此使用:

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

您的错误在这里:

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

改成这个

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

使用==比较intchar

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

错误有两种类型=" "

要比较char值,请使用' '==

像这样 :

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM