【问题标题】:New to java, don't understand why my while loop program will not runjava新手,不明白为什么我的while循环程序不会运行
【发布时间】:2013-03-06 16:55:55
【问题描述】:

这是我要解决的问题。

“墨西哥人口6200万,年增长率7%。美国目前人口2.8亿,年增长率2%。如果这两个国家保持现在的速度增长,多少年后墨西哥的人口将超过美国的一半?你的程序应该回答这个问题。”

好的,这就是我目前的代码。当我运行程序时,我得到了这个错误。

不确定如何解决。任何人都可以帮忙吗? :/

import java.util.Scanner;

public class Whatever {

 public static void main (String [] args){

    Scanner in = new Scanner (System.in);

  int mex = 62000000;
  int usa = 280000000;
  int years = 0;
  double t = 0 ;

   while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
   {
       t++;
       years = t;
       if (mex > (usa * 0.5));
          break;
  }   

       System.out.println ("Mexicos population is half of America in " + years + "years");
    }   

   }

编辑

对于任何想知道我最终让代码工作的人。这是代码。


导入 java.util.Scanner;

公共类随便{

public static void main(String [] args){

Scanner scan = new Scanner (System.in);

double mex = 62000000;
double usa = 280000000;
double years = 0;

    while(mex <= usa/2) 
    {   
        years++;
    mex = mex * 1.07;
    usa = usa * 1.02;

    }       
    System.out.println ("Mexicos population is half of America in " + years + " years ");
    }   

}

【问题讨论】:

  • mexusa 应该是什么? (在你的while循环条件下)
  • 供将来参考 - 我们不希望将错误作为屏幕截图。请将输出复制/粘贴到您的问题中,并确保格式可以接受。
  • 如果您不知道如何从命令提示符复制文本,一种方法是右键单击窗口 -> 标记。然后突出显示文本并再次在窗口中单击鼠标右键进行复制。
  • mex = 墨西哥人口 usa = 美国人口
  • 您没有跟踪人口增长。你的mexusa 永远不会改变,所以你一直在比较相同的值。

标签: java loops while-loop percentage


【解决方案1】:

mex 是一个整数。

我认为你是在尝试繁殖。

如果你想乘法,请使用 mex * (Math.pow(1.07, t)。

【讨论】:

  • 这是基本的答案 - 我认为其他一些答案只是在谈论方法,因为他们没有等到思考一下 OP 试图做什么。
  • 好吧,出于某种原因,我只是假设你可以说 usa(Math.pow(whatever))。我很轻松地解决了这个问题
  • @AntonPipenbacher 仍然没有修复代码,这只是一个开始。就像已经说过的那样,您在循环中不断比较相同的值。
【解决方案2】:

你的问题在这里:

while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))

在变量后面加上括号会向 Java 发出信号,表明您正在尝试使用该名称调用函数(在本例中为 mexusa)。 实际上想要做的是乘以这些值,因此您需要在其中添加星号:

while(mex*(Math.pow(1.07, t)) <= usa*(Math.pow(1.02, t)))

【讨论】:

    【解决方案3】:

    在您的代码中,您定义了几个变量:

    int mex = 62000000;
    int usa = 280000000;
    int years = 0;
    double t = 0 ;
    

    但是,您尝试将这些用作函数:

    while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
    

    在Java中,这些变量被用作函数的参数;不是相反!

    【讨论】:

      【解决方案4】:

      您在 while 循环中对“mex”表达式应用了括号(就好像它是一个函数一样),其中“mex”只是一个常规变量。你对“美国”的使用也是如此..

      while(mex(Math.pow(1.07, t)) <= usa(Math.pow(1.02, t)))
               ^^^               ^
      

      【讨论】:

        【解决方案5】:

        要进行乘法运算,您需要使用*,即

         while(mex * (Math.pow(1.07, t)) <= usa * (Math.pow(1.02, t)))
        

        【讨论】:

          猜你喜欢
          • 2019-06-10
          • 1970-01-01
          • 2022-12-10
          • 2012-11-07
          • 2021-12-26
          • 1970-01-01
          • 2016-01-24
          • 2015-03-25
          • 1970-01-01
          相关资源
          最近更新 更多