Java 将字符读入程序

Java 将字符读入程序,java,compiler-errors,Java,Compiler Errors,我是新手!我被困在这里了。不知道为什么代码不起作用。这里有什么帮助吗 import java.util.Scanner; public class apples { public static void main(String[] args){ System.out.print("Enter the first letter of the color "); Scanner scan = new Scanner(System.in);

我是新手!我被困在这里了。不知道为什么代码不起作用。这里有什么帮助吗

import java.util.Scanner;

public class apples {

    public static void main(String[] args){
        System.out.print("Enter the first letter of the color ");
        Scanner scan = new Scanner(System.in);
        char color = scan.next();

        switch(color){
            case 'r': 
                    System.out.println("Red");
                    break;

            case 'g': 
                    System.out.println("Green");
                    break;

            case 'b': 
                    System.out.println("Blue");
                    break;

            case 'w': 
                    System.out.println("White");
                    break;

            default: 
                    System.out.println("NO Color");
                    break;
        }
    }       
}
你需要

char color = scan.next().charAt(0);
scan.next()
返回所需的
字符串

char color = scan.next().charAt(0);

scan.next()
返回一个
字符串

好吧,我不太使用java,但是如果我不得不大胆猜测:

char color = scanner.next();
这是不正确的。
next()
函数返回字符串,而不是字符。所以,你可以这样做:

char color = scanner.next().charAt(0); // get the first char in the string
或者您可以将
color
设置为字符串:

String color = scanner.next();

嗯,我不太使用java,但如果我不得不大胆猜测:

char color = scanner.next();
这是不正确的。
next()
函数返回字符串,而不是字符。所以,你可以这样做:

char color = scanner.next().charAt(0); // get the first char in the string
或者您可以将
color
设置为字符串:

String color = scanner.next();
scan.next()返回一个字符串。快速修复方法是从中获取第一个字符,如: scan.next().charAt(0)

scan.next()返回一个字符串。快速修复方法是从中获取第一个字符,如:
scan.next().charAt(0)

是什么让你认为代码不起作用?只是想让你知道:每次你这样格式化代码,上帝都会杀死一只小猫:(我第二次看到你在几分钟后发布小猫的评论。虽然很有趣,但这是吹毛求疵……他的代码格式化有什么不好?@Steve-我把它作为一个友好的提示给了一个新用户ie“帮助我们帮助你。请正确格式化你的代码。”是什么让你认为代码不起作用?只是想让你知道:每次你这样格式化代码,上帝都会杀死一只小猫:(我第二次看到你在几分钟后发布小猫的评论。虽然很有趣,但这是吹毛求疵……他的代码格式有什么不好?@Steve-我把它作为一个对新用户友好的提示,即“帮助我们帮助你。请正确格式化你的代码。”