初学者 Java(循环)- 缺少 return 语句 [英] Beginners Java (Loops) - Missing return statement

查看:29
本文介绍了初学者 Java(循环)- 缺少 return 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.Scanner;

public class Vending {
    public double vend(double balance) {
        Scanner in = new Scanner(System.in);
        balance = 0;
        System.out.print("Enter a command = ");
        String command = in.nextLine();

        while (in.hasNext()) {
            if (command.equals("penny")) {
                balance = balance + 0.01;
                System.out.println("balance = " + balance);
            }
            return balance;
        }
    }
}

嗨!我已经尝试了一切来弄清楚为什么 return 语句没有被识别.如果我将返回余额"放在其他任何地方,它会说 system.out.println 无法访问......你们中的任何人都可以帮助我解决为什么这可能不起作用?谢谢!!

Hi! I have tried everything to figure out why the return statement is not being recognized. If I put the "return balance" anywhere else it says that the system.out.println is unreachable... Can any of you kindly help me out as to why this may not be working?? Thank you!!

推荐答案

return 语句位于 while 循环内部和 if 外部条件段,因此代码在第一次迭代时打破了循环.

The return statement is inside the while loop and outside the if condition segment, so the code its breaking the loop on the first iteration.

可能的解决方案:将 return 移到 while

Possible solution: move the return outside the while

while (in.hasNext()) {
    if (command.equals("penny")) {
        balance = balance + 0.01;
        System.out.println("balance = " + balance);
    }
}
return balance;

这篇关于初学者 Java(循环)- 缺少 return 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆