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

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

问题描述

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.

可能的解决方案:在之外移动返回,而

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(循环) - 缺少返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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