2014-09-25 46 views
0

我正在嘗試編寫一個程序,要求用戶輸入兩點。每個點一次輸入一個。然後我需要x座標小於或等於5,大於或等於-5。爲什麼我的程序沒有返回正確的字符串值

我需要遵循相同的邏輯,但2.5和-2.5。出於某種原因,它不會在檢查後返回字符串語句。我沒有任何語法錯誤,所以我不確定問題是什麼。

import java.util.Scanner; 
public class coordinates { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 

     //prompt user to enter coordinates 
     System.out.println("Enter a X coordinate: "); 
     double x = input.nextDouble(); 

     System.out.println("Enter a Y coordinate: "); 
     double y = input.nextDouble(); 

     //check x coordinate to see if it is less or equal to 5 and greater than or equal to -5 
     if (x <= 5 && x >= -5){ 
      if (y <= 2.5 && y >= -2.5) 
       System.out.println("Yes"); 
     }else 
      System.out.println("no"); 
    } 
} 
+1

只是一個提示 - 總是使用'{}'字符與'if/else'語句;否則它會弄清楚每個'if'的範圍是多麼混亂。不這樣做是一個巨大的錯誤來源。 – 2014-09-25 22:36:21

+0

好吧,我的另一個問題是如何打印出來的:點(x,y)在範圍內。 – 2014-09-25 22:45:02

回答

0

如果您x值在範圍內,但你y值不在範圍內,那麼什麼都不會被打印,因爲第一if的操作但是第二if不被採納。將您的if條件更改爲一個更大的條件,這樣如果任一條件失敗,則將遵循else

if ((x <= 5 && x >= -5) && (y <= 2.5 && y >= -2.5)) { 
    System.out.println("Yes"); 
}else { 
    System.out.println("no"); 
} 
+0

非常感謝。我還有一個問題,如果我想讓它說:Point(x,y)在 – 2014-09-25 22:37:26

+0

@ user3240208的範圍內,那麼我該如何形成我的打印輸出行:使System.out.println(「Point(」+ x +「,」+ y +「)在範圍」);'而不是「是」文本。這就是所謂的串聯(如果你想Google瞭解更多信息以及它的工作原理)。 – Frakcool 2014-09-25 23:20:49

相關問題