我确定这是一个愚蠢的问题,但是我已经解决了很多。.我试图创建一个Java程序,根据用户输入的年数和金额来计算复利。但是我一直收到一个错误,认为void方法无法返回值。所以我将方法切换为double,因为多数民众赞成将返回什么,但是它告诉我double方法必须返回double。甚至在循环中返回双倍...请帮助
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
**strong text**
Scanner reader = new Scanner(System.in); //creates scanner
System.out.println("Enter number of years until retirement: "); //asks user to input number of years until retirement
int Years = reader.nextInt();
if (Years <= 0) {
System.out.println("Please enter a valid number"); //if the number of years was invalid, exits the program and asks to enter a valid number
System.exit(0);
}
System.out.println("Enter amount of money able to save annually: "); //asks user how much money they can input
double MoneySaved = reader.nextInt();
reader.close(); //closes scanner
for(int i=0; i < Years; i++)
{
Total = MoneySaved * 1.05;
return Total;
}
System.out.println("You will have $" + df.format(TotalAmount) + " saved up by retirement");
}
}
答案 0 :(得分:0)
将方法修改为双并更改
def test_data_collection():
with mock.patch('moduleA.classA.send_over_socket') as mock_send_over_socket:
A = classA()
A.send_over_socket.return_value = 1
with mock.patch('socket.socket') as mock_socket:
mock_socket.return_value.recv.decode.return_value = "packet_string"
with mock.patch('moduleA.ClassA.publish') as mock_publish:
d = {}
A.data_collection(d)
A.publish.assert_called_with("0","500","2","1")
到
double MoneySaved = reader.nextInt();
我也看不到您对“总计”的声明;确保将其声明为double。
答案 1 :(得分:0)
为此更改您的
Double total = 0;
for(int i=0; i < Years; i++) {
total += MoneySaved;
total *= 1.05;
}
System.out.println(total);
答案 2 :(得分:0)
首先,主要的Java方法必须为void,并且void方法不能返回值(即使编译器也告诉您),尽管您可以使用return语句中断该方法的执行并返回到调用方法。
因此,要回答您的问题,您必须创建一个返回double的方法,然后将其打印在您的main方法中,或者不返回任何内容而只替换
return Total;
使用
System.out.println("You will have $" + df.format(Total) + " saved up by retirement");
PS:您似乎是Java的新手,所以一开始请阅读一些有关Java的内容,例如offical oracle tutorial