简体   繁体   English

使用 .equals (Java) 遍历一个字符串并将结果与​​另一个字符串进行比较

[英]Iterating through a string and comparing result to another string using .equals (Java)

import java.util.Scanner;

public class Main {

    public static void main(String[] args){

        Landscape landscape = new Landscape();

        Scanner keyboardScanner = new Scanner(System.in);

        System.out.println("Enter your terrain: ");

        String TerrainInput = keyboardScanner.nextLine();

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

            char j = TerrainInput.charAt(i);

            if j.**equals(**"m") {
                //landscape.mountain(int [j+1])
            }

            if j.**equals**("f"){
                //landscape.flat(int [j+1])
            }
            if j.**equals**("h"){
                //landscape.hill(int [j+1])
            }
        }

    landscape.print();

The program should receive some input string like f3,m3,f2,m0,f4,h1,f1 my plan is to iterate through each character and check if it is equal "f,m, or h" and if it is then i will call the appropriate method and use the number after "f,m, or h" as an argument by calling the method with the index of the letter character found + 1.程序应该接收一些输入字符串,如f3,m3,f2,m0,f4,h1,f1我的计划是遍历每个字符并检查它是否等于“f、m 或 h”,如果是,那么我将调用适当的方法并使用“f、m 或 h”之后的数字作为参数,方法是调用带有找到的字母字符索引 + 1 的方法。

for (int i = 0; i < TerrainInput.length(); i++){
    char j = TerrainInput.charAt(i);

    if j.**equals(**"m") {
        //landscape.mountain(int [j+1])
    }
}

The issue is the .equals isn't working, its saying Cannot resolve method 'equals(java.lang.String)'问题是 .equals 不起作用,它说Cannot resolve method 'equals(java.lang.String)'

j is a char, not a String. j是一个字符,而不是一个字符串。 Chars are compared using == , not equals使用==比较字符,而不是equals

if (j == 'm')

Java is different than Python and JavaScript. Java 不同于 Python 和 JavaScript。 charAt doesn't return a String , it returns a char (exclusively a character). charAt不返回String ,它返回一个char (仅一个字符)。 Therefore you can't compare it to a String .因此,您无法将其与String进行比较。 If you write a character in single quotes, that will be a char like this: 'a' .如果你用单引号写一个字符,那将是一个像这样的char'a' Also, char is a primitive type, so you can compare with == .此外, char是一种原始类型,因此您可以与==进行比较。

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

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