gpt4 book ai didi

Java : Method return Issue

转载 作者:行者123 更新时间:2023-12-01 13:59:36 28 4
gpt4 key购买 nike

您好,我创建了一个类来运行另一个测试类,但我遇到了一些问题。我已将agePremium 和ticketPremium 声明为私有(private) double 。后来我用两种方法分别计算保费。但是当它到达我不想在此处的另一个计算中使用计算变量的部分时

/* 
public double premium() {

if (ticket <4){
return ((BASE_PREMIUM*value) * agePremium) * ticketPremium;
}
else {
System.out.println("Sorry, you have too many tickets !!");
return 0;
}
}
*/

它不会从我的方法中读取值,而是从声明和初始化中读取 1。

私有(private)双倍年龄溢价 =1;私有(private)双人票Premium =1;

它使它们相乘。

我如何让它们相互链接并用新值替换 1 并相乘。谢谢

import java.util.Scanner;

public class Driver {
private int age;
private int ticket;
private double value;
final double BASE_PREMIUM=0.05;
private double agePremium =1;
private double ticketPremium =1;


Scanner scanner = new Scanner(System.in);

public void read() {

System.out.println("Driver’s Age?");
age = scanner.nextInt();
System.out.println("Number of Tickets?");
ticket = scanner.nextInt();
System.out.println("Value of Car?");
value = scanner.nextDouble();
}

public double premium() {

if (ticket <4){
return ((BASE_PREMIUM*value)*agePremium)*ticketPremium;
}
else {
System.out.println("Sorry, you have too many tickets !!");
return 0;
}
}



public void premiumAge() {
if (age > 29) {
agePremium += 0;
}
else if (age <= 29 && age >= 25) {
agePremium += 0.10;
}
else {
agePremium += 0.15;
}
}

public void premiumTicket() {
switch (ticket) {
case '1':
ticketPremium += 0.1;
break;
case '2':
ticketPremium += 0.25;
break;
case '3':
ticketPremium += 0.50;
break;
case '0':
ticketPremium += 0.00;
default:
ticketPremium = 0.00;
break;
}
}
}

最佳答案

你的方法应该有点像这样,返回一个double以便访问另一个类中的私有(private)数据字段

public double premiumAge() {
if ...
return agePremium;
else if ...
return ....
...
}

如果您需要一个值,则需要返回一个值才能在另一个类中使用该方法。另外值得注意的是命名约定。当您希望方法访问私有(private)数据字段时,请使用带有 get 前缀的数据字段名称,例如。 agePremium : getAgePremium();

从另一个类访问

Driver driver = new Driver(); // create a Driver object (instantiate)
System.out.println(driver.premiumAge());

// Or if you follow the naming convention in your Driver class
System.out.println(driver.getAgePremium());

关于Java : Method return Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19416528/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com