简体   繁体   English

Java新手,需要帮助

[英]New to java, need assistance

I am trying to make a endless loop pig Latin translator until the user enters a "q" to quit the program. 我正在尝试制作一个无穷循环的猪拉丁翻译器,直到用户输入“ q”退出程序为止。 I am having issues finalizing the while statement. 我在完成while语句时遇到问题。 The error that I am getting is as followed. 我得到的错误如下。

PigLatin.java:27: error: cannot find symbol } while (word != "q"); PigLatin.java:27:错误:在(word!=“ q”)时找不到符号}; ^ symbol: variable word location: class PigLatin ^符号:可变词的位置:class PigLatin

Here is my source code: 这是我的源代码:

import java.util.Scanner;

public class PigLatin {
    public static void main(String[] args) {
        System.out.println("Welcome to the pig latin convertor.");
        do {
            Scanner in = new Scanner(System.in);
            String word, pig;
            char first;

            System.out.print("enter word or press 'q' to quit: ");
            word = in.next();
            word = word.toLowerCase();
            System.out.println(word);

            first = word.charAt(0);
            if (first == 'a' ||  first == 'e' || first == 'i' || 
                first == 'o' || first == 'u')  // vowel
                pig = word + "way";      
            else
                pig = word.substring(1) + word.charAt(0) + "ay";
            System.out.println("pig-latin version: " + pig);
        } while (word != "q");
    }
}

Your variable word has been declared in the wrong place, ie. 您的可变word已在错误的位置声明,即。 within the do..while loop, rather than before. do..while循环内,而不是之前。 This is causing the compilation error. 这导致编译错误。

Once you fix that, you still have a bug because String comparisons should use equals() not != (or == ). 修复此错误后,您仍然会遇到错误,因为String比较应使用equals()而不是!= (或== )。

Try something like: 尝试类似:

String word;
do {
    ...
} while (!word.equals("q"));

You could also use word.equalsIgnoreCase("q") if you don't care whether they enter "q" or "Q" . 如果您不在乎他们输入"q"还是"Q"也可以使用word.equalsIgnoreCase("q")

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

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