gpt4 book ai didi

java - 如何输出代码正在运行的循环的哪一次迭代

转载 作者:行者123 更新时间:2023-12-01 18:11:13 25 4
gpt4 key购买 nike

我有一个关于循环的问题。我正在创建一个计算 Assets 弃用的程序(未知),并且我正在循环它,因此它运行 4 次。整个代码如下所示

import java.io.*;
import java.util.*;

class Program108b{

public static void main(String[] args){
int [] numbers = {1, 2, 3, 4};
for(int x: numbers){
Scanner kb = new Scanner(System.in);

System.out.print(" Enter price ");
double price = kb.nextDouble();

System.out.print("Enter salvage value ");
double salValue = kb.nextDouble();
System.out.print("Enter estimated life in years ");
int years = kb.nextInt();
double anws = ((price- salValue)/years);
System.out.print("Here is the depreciated value: " + (Math.round((anws)*100)/100.0));
}
}
}

当特定的运行发生时,我试图让它在代码顶部说“运行#1”,然后“运行#2”,然后“运行#3”,然后“运行#4”。所以现在的输出是

Enter price 2500
Enter salvage value 350
Enter estimated life in years 23
Here is the depreciated value: 93.48 Enter price 23
Enter salvage value
32
Enter estimated life in years 3
Here is the depreciated value: -3.0 Enter price 2
Enter salvage value 32
Enter estimated life in years 3
Here is the depreciated value: -10.0 Enter price 23
Enter salvage value 2
Enter estimated life in years 3
Here is the depreciated value: 7.0

(输入完全是随机的,我只是想显示输出是什么)我想让输出看起来像这样:

run #1    
Enter price 2500
Enter salvage value 350
Enter estimated life in years 23
Here is the depreciated value: 93.48
run #2
Enter price 23
Enter salvage value
32
Enter estimated life in years 3
Here is the depreciated value: -3.0
run #3
Enter price 2
Enter salvage value 32
Enter estimated life in years 3
Here is the depreciated value: -10.0
run #4
Enter price 23
Enter salvage value 2
Enter estimated life in years 3
Here is the depreciated value: 7.0

所以我的问题是 - 我如何让它说“run #_”,并将每个循环更改为“run #1”、“run #2”等,直到第四次运行?另外,我如何使新的运行开始于新行(此代码中的“输入价格”部分)?

最佳答案

只需在循环开头添加一个System.out.println

for (int x: numbers) {
System.out.println("run #" + x);
// Rest of code
}

关于java - 如何输出代码正在运行的循环的哪一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845515/

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