2016-03-05 47 views
-2
//varible int time won't display the numeric value entered 

聲音 的速度下表顯示了聲音在空氣,水和鋼的近似速度: 中速 空氣1100每秒 英尺水4,900英尺每秒 鋼16,400英尺每秒 編寫一個程序,要求用戶輸入「空氣」,「水」或「鋼」,以及聲波在介質中傳播的距離。然後該程序應顯示所需時間的數量。您可以通過以下公式計算出在空中傳播聲音所需的時間: 時間5距離/ 1,100 您可以使用以下公式計算聲音在水中行走的時間量: 時間5距離/ 4900 可以計算所花費的時間的聲音在鋼鐵旅行用下面的公式量: 時間5距離/ 16400/varible INT時間將不顯示的數字值輸入

C:\Users\DeLaCruz\Desktop\j2

V:\CSC106-Spring 2016\j3

import java.util.Scanner; 

public class ProgramSpeedOfSound{ 

public static void main(String [] args){ 

    Scanner keyboard = new Scanner(System.in); 

    String input; 


    System.out.println("Enter Air, water or steel "); 
    input = keyboard.nextLine().toUpperCase(); 

if(input.equals("Air")){ 


System.out.println("what is the Distance? "); 
int Distance = keyboard.nextInt(); 
int var = 1100; 
double time = Distance/var; 

System.out.println("it would take " + time); 

} 
else if(input.equals("Water")){ 


System.out.println("what is the Distance? "); 
int Distance = keyboard.nextInt(); 

    double time = (((Distance/ 4900))); 

System.out.println("it would take " + time); 
} 
else{ 

System.out.println("what is the Distance? "); 


    int Distance = keyboard.nextInt(); 

    double time = Distance/ 16400; 

System.out.println("it would take " + time); 

    } 
    } 
} 
+1

確保您比較兩個字符串也全部大寫。例如。將'Air'改爲'AIR'和'Water'改爲'WATER' – 4castle

回答

1

在分割兩個整數時,需要將分母或分子的類型轉換爲浮點數。你得到0.0作爲答案的原因是因爲除以兩個整數給整數值爲0,後來轉換爲雙0.0。例如,請參閱下面的代碼中的第3行。你也可以增加一倍。

 System.out.println("what is the Distance? "); 
     int Distance = keyboard.nextInt(); 
     double time = (float)Distance/16400; 
     System.out.println("it would take " + time); 

下面是鑄字量之後的輸出浮

 Enter Air, water or steel 
     Air 
     what is the Distance? 
     100 
     it would take 0.006097560748457909 
1

嘗試使用equalsIgnoreCase()而不是equals()

在您的程序中,如果沒有以您檢查的格式輸入input的值,控件將不會輸入任何條件塊。

您的代碼將無法正常工作爲:

  • 水,空氣,水等

因此,使用equalsIgnoreCase()避免情況sentivity。

注:

進行以下校正:

Double Distance=keyboard.nextDouble(); 

司類型整數/整數的可能導致精度損失當被除數是不是由除數完全除盡。

  • 5/3將返回1,您將丟失小數部分。
  • 3/5將返回0

所以最好聲明DistanceDouble而不是int