【问题标题】:Yearly price increase loop? Stuck on nested loop年度涨价循环?卡在嵌套循环上
【发布时间】:2018-09-27 11:36:05
【问题描述】:

我正在尝试编写一个程序,该程序使用扫描仪键盘输入这些值并使用循环使它们增加(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 年一样),但我坚持让价格随着设定的数量增加,我认为这将是一个嵌套循环但是不知道怎么写。

(我假设是一个嵌套循环,因为这是我们现在正在学习的内容。)

如果有人对我可以写什么有任何建议,我将不胜感激!

【问题讨论】:

  • System.out.print("Price in " +i+ ": " +m);start++; 看起来价格(米)没有变化?
  • 如果你从不使用int a = m+p; 有什么意义?
  • 你可以看看this example。我相信你会自己想办法!
  • @Mohammad,价格没有变化,不。我不确定如何编写它来改变它,这只是我到目前为止允许年份增加的代码,但我不知道如何让价格也增加。跨度>
  • @OH GOD SPIDERS 我仍在试图弄清楚如何改变价格。那是我在搞砸的东西,还没有用过。

标签: java loops nested-loops jcreator


【解决方案1】:

我认为您只需要在循环的每次迭代中将 expected yearly price increasecurrent 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

  }
}

【讨论】:

  • 成功了,谢谢!我现在看着它觉得很愚蠢,哈哈,我把变量放在了所有错误的地方。再次感谢您!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2015-06-05
相关资源
最近更新 更多