循环通过一个数组

时间:2015-11-21 07:19:34

标签: java arrays

我正在尝试为用户设置输入法,为每种类型的树输入多个树种子。有三种不同的树类型。我只是想让用户在我创建的这个方法中输入所有三个的金额,如果他们输入无效条目(空字符串或字符串或数字<0),它将发出错误。

我的&#34; for&#34;循环适合这里?我想增加desiredYield数组和treeTypes数组的数量,以便值是并行的。在该计划的后期,我需要计算种子死亡所需的树木数量。

任何建议都有帮助。

  import javax.swing.JOptionPane;

  public class TreeCalc{

     public static void main(String[] args){

      String[] treeTypes = new String[] {"Fir", "Pine", "Spruce"};
      int[] desiredYield = new int [treeTypes.length];
      double[] decayRate = new double[] {0.07, 0.12, 0.08};
      desiredYield[] = getYield();
      getCalculate(decayRate[], treeTypes[], desiredYield[]);
      printMessage();

  }

     //Asks user to input # of trees for each tree type
     public static int getYield(){
        int index= 0;
        do{
           for(int i=0;i<=treeTypes.length;i++){
             try{
             desiredYield[index] = Integer.parseInt(JOptionPane.showInputDialog("Please enter your desired yield for: " +treeTypes[i]));
        }catch(NumberFormatException e){
           if(desiredYield[index]==("") || desiredYield[index]<0){
              JOptionPane.showMessageDialog(null, "Error: Please enter your desired yield for "+treeTypes[i]);
          }else{
              index++
        }
       }
     }
    }while(desiredYield[index]<0 || desiredYield[index]==(""));
   }
  }

1 个答案:

答案 0 :(得分:0)

for(int i=0;i<=treeTypes.length;i++){
             try{
             desiredYield[index] = Integer.parseInt(JOptionPane.showInputDialog("Please enter your desired yield for: " +treeTypes[i]));
        }catch(NumberFormatException e){
           if(desiredYield[index]==("") || desiredYield[index]<0){
              JOptionPane.showMessageDialog(null, "Error: Please enter your desired yield for "+treeTypes[i]);
          }else{
              index++
        }
       }

您需要从for循环中删除'='。

更新的代码应为:

for(int i=0;i < treeTypes.length;i++){
             try{
             desiredYield[index] = Integer.parseInt(JOptionPane.showInputDialog("Please enter your desired yield for: " +treeTypes[i]));
        }catch(NumberFormatException e){
           if(desiredYield[index]==("") || desiredYield[index]<0){
              JOptionPane.showMessageDialog(null, "Error: Please enter your desired yield for "+treeTypes[i]);
          }else{
              index++
        }
   }