我试图编写一个程序,使用扫描仪键盘输入这些值并使用循环来增加它们(2006-2010,年份,价格上涨,90-100等) 。)
输出应该如下所示:
Enter the current Mars bar price in cents: 90 Enter the expected yearly price increase: 15 Enter the start year: 2006 Enter the end year: 2010 Price in 2006: 90 cents Price in 2007: 105 cents Price in 2008: 120 cents Price in 2009: 135 cents Price in 2010: 150 cents
这是我到目前为止的代码:
import java.util.Scanner;
public class Problem_2 {
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the current Mars bar price in cents: ");
int m = keyboard.nextInt();
System.out.print("Enter the expected yearly price increase: ");
int p = keyboard.nextInt();
int a = m+p;
int count = 1;
System.out.print("Enter the start year: ");
int start = keyboard.nextInt();
System.out.print("Enter the end year: ");
int end = keyboard.nextInt();
for (int i = start; i <= end; i++){
System.out.print("Price in " +i+ ": " +m);start++;
}
}
并且它允许我将年份增加到设定的数量(再次像2006-2010)但我仍然坚持价格随着它设定的数量增加,我认为它将是一个嵌套循环,但我不知道如何写它。
(我假设一个嵌套循环,因为那是我们现在正在学习的内容。)
如果有人对我能写的东西有任何建议,我真的很感激!
答案 0 :(得分:0)
我认为你只需要在循环的每次迭代中将expected yearly price increase
加到current price
,它就是这样的:
import java.util.Scanner;
public class Problem_2 {
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the current Mars bar price in cents: ");
int m = keyboard.nextInt();
System.out.print("Enter the expected yearly price increase: ");
int p = keyboard.nextInt();
int count = 1;
System.out.print("Enter the start year: ");
int start = keyboard.nextInt();
System.out.print("Enter the end year: ");
int end = keyboard.nextInt();
for (int i = start; i <= end; i++){
System.out.print("Price in " +i+ ": " +m);
m += p; // sum expected price for each iteration
}
}