Compiler says Java code is invalid

China☆狼群 提交于 2019-12-11 21:24:03

问题


I am working on a Java code:

import java.util.Scanner;

public class main
{
    static Scanner console = new Scanner (System.in);
    public static void main (String aurgs[]) {

        System.out.print("Which function would you like to vist? L for Lottery, R for Random Math");
        char lotto = 'l';
        char rdm = 'b';

        if (console.nextChar() = lotto) /**error is here*/ {
            lottery();
        }
    }
    public static void lottery (String aurgs[]) {
        String announ = "Your lottery numbers for today are: ";
        System.out.print(announ);
        int [] numbers = {15, 68, 25, 66};
        double lucky = 50.2;
        for (int i: numbers )
            System.out.print(i + "\n");

        String announ2 = "Your lucky number is: ";
        System.out.println(announ2 + lucky);
        }
}

When I compile it, BlueJ says:

cannot find symbol - method nextChar()

I do not understand what is wrong.


回答1:


The Scanner class has no nextChar() method. The methods available are listed here, none of which are nextChar(). You can instead use next() and read a single character as a string.




回答2:


I do not understand what is wrong.

It is simple. Scanner doesn't have nextChar() method.

If you want to read characters with Scanner you can change its delimiter to empty string ""

console.useDelimiter("");

and use next() method.


Also you should add one more = in

if (console.nextChar() = lotto)

if you want to compare chars (single = is used for assigning values).




回答3:


In order to get a char from a Scanner you need to use next(), which returns a String. Then just get the first char from that.

char x = console.next().charAt(0);


来源:https://stackoverflow.com/questions/19417813/compiler-says-java-code-is-invalid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!