Java中的类问题

时间:2013-04-15 06:38:05

标签: java class switch-statement

我有点困惑,因为我无法弄清楚我在这里做错了什么。我几乎尽我所能,但它仍然无法正常工作。我现在对如何从这里前进毫无头绪。请帮忙,我非常感谢您的解决方案。感谢

public class Example {


public static void main(String[] args) {


    String cafescan;

    Scanner scan= new Scanner (System.in);   

       System.out.print ("Please enter the name of the cafe :" );
       cafescan = scan.nextLine();

       Cafe naam = new Cafe();
       naam.name = (cafescan);//THIS WORKS FINE 
       Cafe thau = new Cafe();
      thau.location = (location1);//THIS IS WHERE ERROR IS
              System.out.println (naam.setName());
          System.out.print   (thau.setLocation());

在我的Cafe.jave文件中,我有这个:

public class Cafe{
String name;
String location;



    public String setName(){

        name=name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase()+ " Cafe";
        return name;
    }   

    public String setLocation(){
        char location1 = name.charAt(0);
      //SWITCH IS SUPPOSED TO WORK ACCORDING TO FIRST ALPHABET OF cafescan

        switch (location1)
        {
        case 'E':
            System.out.println("Rosedale");
            break;
        case 'M':
            System.out.println ("Parkville");
            break;
        case 'T':
            System.out.println ("Towson");
            break;
            default:
                System.out.println("Baltimore");


        }
        return location;
    }

}

帮帮我大佬:)

2 个答案:

答案 0 :(得分:1)

首先你必须声明location1。他们从您的扫描仪中读取它

String location1= scan.nextLine();

答案 1 :(得分:0)

在main方法中,将Cafe对象设置如下:

 Cafe naam = new Cafe(cafescan); 

按如下方式修改您的咖啡馆课程:

public class Cafe{
   String name;
   String location;


public Cafe(String name){
    setName();
    setLocation();
}

public String setName(){

    name=name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase()+ " Cafe";
    return name;
}   

public String setLocation() {
    char location1 = name.charAt(0);
    // SWITCH IS SUPPOSED TO WORK ACCORDING TO FIRST ALPHABET OF cafescan

    switch (location1) {
        case 'E':
            System.out.println("Rosedale");
            location = "Rosedale";
            break;
        case 'M':
            System.out.println("Parkville");
            location = "Parkville";
            break;
        case 'T':
            System.out.println("Towson");
            location = "Towson";
            break;
        default: {
            System.out.println("Baltimore");
            location = "Baltimore";
        }

    }
    return location;
}

}