【问题标题】:Using Scanner to read the [closed]使用扫描仪阅读[关闭]
【发布时间】:2013-11-05 02:49:01
【问题描述】:

当我想使用扫描仪读取用户的名称,然后在字符串中分配名称的值,然后调用方法 getName 并给它一个名称参数以打印出我的名称是.. ..,我的代码只是崩溃并且无法工作我试图找出问题,但我无法

 public void getName(String name)
   {
       String s = "your name is: "+name   ;
   }
    public void userInput()
    {
        print();
        Scanner s = new Scanner(System.in);
        String read = s.nextLine();
        String op = read;
        while(!read.equals("Exit"))
        {  
            switch (op){
                case "a" :
                System.out.println("type your name:");
                read = s.nextLine();
                getName(read);
                print();
                read = s.nextLine();
                op = read;
                break;
                case"b" :
                System.out.println("by");
                print();
                read = s.nextLine();
                op = read;
                break;
            }

        }
    }

    public void print()
    {
        System.out.println("press a");
        System.out.println("press b");
    }

【问题讨论】:

  • 它在哪里崩溃?它给出了什么错误?
  • 代码不just crash。你得到什么样的错误?
  • 当我调用方法 userInput() 时,它工作正常,当我输入 a 时,它会要求我写下我的名字,但是当它将字符串名称发送到方法 getName 后,它会进入一个循环并它不会爆发
  • 第一种情况下调用getName方法时不打印名字

标签: java while-loop switch-statement java.util.scanner bluej


【解决方案1】:

要使您的 while 条件为假,请在 switch 中添加 default 语句:

    while (!read.equals("Exit")) {
        switch (op) {
        case "a":
            System.out.println("type your name:");
            read = s.nextLine();
            getName(read);
            print();
            read = s.nextLine();
            op = read;
            break;
        case "b":
            System.out.println("by");
            print();
            read = s.nextLine();
            op = read;
            break;
        default: // Add this to finish loop when you type "Exit"
            read = s.nextLine();
        }

    }

编辑

您对方法 getName(read) 的调用没有用,请尝试以下方法之一:

1. 您可以让getName() 返回一个字符串并将其存储在您的userInput() 中以供以后使用。顺便说一句,getSomething() 方法通常用于返回一些东西。

public static String getName(String name) {
    String s = "Your name is: " + name;
    return s;
}

这在userInput() 方法中:

String name = getName(read);

2. 或者在void getName(String name) 方法中打印一些东西:

System.out.println("Your name is: " + name);

并在userInput()方法中调用getName(read)

getName(read);

【讨论】:

    【解决方案2】:

    您的代码在getName 中没有任何用处。我的猜测是你想打印名字,像这样:

    public void getName(String name) // should rename this method 'printName'
    {
        System.out.println("your name is: "+name);
    }
    

    【讨论】:

    • 在第一种情况下调用getName方法时不会打印出名称,这是我要求的
    • 那么,我希望我的示例代码对您有所帮助。
    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多