2012-02-20 82 views
0
  1. 當我輸入的輸入,滿足一切,不會觸發任何我的錯誤,該方案剛剛過去的輸入後退出像它跳過了forif循環。代碼似乎跳過if或for循環

  2. 同樣在System.out.printf("Enter the name of your second species: ");之後它將不允許任何輸入,它只是跳到下一個提示。我不確定這是爲什麼。它上面的部分要求第一個物種的信息工作正常。

import java.util.Scanner; 

public class HW2johnson_pp1 { 

    public static void main(String args[]) { 

     Scanner keyboard = new Scanner(System.in); 

     System.out.printf("Please enter the species with the higher" + 
          " population first\n"); 
     System.out.printf("Enter the name of your first species: "); 
     String Species1 = keyboard.nextLine(); 
     System.out.printf("Enter the species' population: "); 
     int Pop1 = keyboard.nextInt(); 
     System.out.printf("Enter the species' growth rate: "); 
     int Growth1 = keyboard.nextInt(); 

     System.out.printf("Enter the name of your second species: "); 
     String Species2 = keyboard.nextLine(); 
     System.out.printf("Enter the species' population: "); 
     int Pop2 = keyboard.nextInt(); 
     System.out.printf("Enter the species' growth rate: "); 
     int Growth2 = keyboard.nextInt(); 

     if (Pop2 > Pop1) { 
      System.out.printf("The first population must be higher. \n"); 
      System.exit(0); 
     } 


     Species input1 = new Species(); 
     input1.name = Species1; 
     input1.population = Pop1; 
     input1.growthRate = Growth1; 

     Species input2 = new Species(); 
     input2.name = Species2; 
     input2.population = Pop2; 
     input2.growthRate = Growth2; 

     if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <= 
      (input1.predictPopulation(2) - input2.predictPopulation(2))){ 

      System.out.printf(Species2 + " will never out-populate " + 
           Species1 + "\n"); 
     } 
     else { 

      for (int i = 0; input2.predictPopulation(i) <= 
          input1.predictPopulation(i); i++) { 

       if (input2.predictPopulation(i) == input1.predictPopulation(i)) { 
        System.out.printf(" will out-populate \n"); 
       } 
      } 
     } 
    } 
} 

這對於predictPopulation()

public int predictPopulation(int years) 
    { 
     int result = 0; 
     double populationAmount = population; 
     int count = years; 
     while ((count > 0) && (populationAmount > 0)) 
     { 
      populationAmount = (populationAmount + 
          (growthRate/100) * populationAmount); 
      count--; 
     } 
     if (populationAmount > 0) 
      result = (int)populationAmount; 

     return result; 
    } 

回答

1
  1. 這是因爲後種2超越物種1,除非是在非常從來沒有打印任何東西物種2和物種1的特例有正好在同一年的人口。

  2. 這是因爲,當您輸入物種1的增長率時,輸入一個整數,然後按輸入keyboard.nextInt()吞下整數,但在輸入緩衝區中留下換行符,因此後續的keyboard.nextLine()認爲在那裏有一個空行等待它。