2010-10-18 100 views
3

這是我的情況:循環距離,並退出

我需要的代碼在一個循環中運行,一遍又一遍的問同樣的問題(一個或多個)用戶,直到用戶鍵入任意點的「q」來終止/退出循環,從而退出程序。

問題是我試圖使用do-while/while循環,並且只有當條件成立時才執行這些循環。但我需要條件(「q」)爲假,以便它可以繼續循環。如果條件爲真(input.equals(「q」)),那麼它並不是什麼都不是,因爲它不會使用整數/雙精度來使用字符串(「q」)來計算距離。

我已經想出瞭如何獲得距離,代碼效果很好,但有沒有解決方法,我可以讓循環繼續而條件爲假?

順便說一句,我只是勉強學習java以防萬一......

」。

import java.*; 
public class Points { 
public static void main(String[] args){ 

    java.util.Scanner input = new java.util.Scanner(System.in); 

    System.out.print("Enter the first X coordinate: "); 
    double x1 = input.nextDouble(); 
    System.out.print("Enter the first Y coordinate: "); 
    double y1 = input.nextDouble(); 
    System.out.print("Enter the second X coordinate: "); 
    double x2 = input.nextDouble(); 
    System.out.print("Enter the second Y coordinate: "); 
    double y2 = input.nextDouble(); 
    System.out.println("(" + x1 + ", " + y1 + ")" + " " + "(" + x2 + ", " + y2+ ")"); 

    double getSolution = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1))); 
    System.out.println(getSolution); 
    } 
}' 
+2

最後一門功課的問題在用戶實際嘗試:) – 2010-10-18 20:47:55

+1

你知道'!'操作符嗎? – nmichaels 2010-10-18 20:48:02

回答

1

的解決方案是使用String line = input.nextLine()代替nextDouble()。然後你就可以有一個方法,如:

public static boolean timeToExit(String input) { 
    return input.equalsIgnoreCase("q"); 
} 

這種方法需要每個用戶提供輸入的時間被稱爲:

if (timeToExit(line)) break; 

這將退出循環。

現在,由於您有double的字符串表示,因此您需要使用Double.parseDouble(line)將String轉換爲數字。

然後,所有你需要做的是一個無限循環包圍的一切 - >while(true) { }

而且,只有時間會退出循環是,如果timeToExit方法返回true,並且你打破循環。

這一切都變成一樣的東西:

while (true) { 
    ... 
    System.out.print("Enter the first X coordinate: "); 
    String x1 = input.nextLine(); 
    if (timeToExit(x1)) break; 
    double x1_d = Double.parseDouble(x1); 
    ... 
} 
+0

謝謝,它的工作原理。我還必須將getSoulition變量更改爲parseDouble ...以及聖潔!我需要更多練習。我知道解析概念,從來沒有意識到它。 – 2010-10-19 19:12:34

+0

@carlos,很高興我能幫上忙,並且很高興你能工作。 – jjnguy 2010-10-19 19:29:03

1

只是一些僞代碼:

while (! input.equals("q")) 
// do something 

如果用戶輸入Q,input.equals( 「Q」)返回true,然後否定和打破循環。

否則,用戶輸入另一個數字,比如44,input.equals(「q」)等於false,否定並且循環繼續。

+0

我不是一個java程序員,但應該允許你循環直到用戶鍵入'q' – 2010-10-18 20:52:54

+0

需要做更多更改才能完成這項工作。 – jjnguy 2010-10-18 20:53:31

+1

嗯,我不擅長java,所以我試圖保持它有點語言獨立:(什麼會改變,使其工作?只是好奇!謝謝!編輯:啊,我明白了......數字到字符串轉換部分? – 2010-10-18 21:00:17

0

我沒有看到你的代碼的循環...:■

但是,你爲什麼不試試這個:

while(true) 
{ 
    string input = // I don't remember the code to create a stream for standard input 
    if(input == "q"){ 
    break; 
    } 
    else{ 
    java.util.Scanner inputWithNumbers = new java.util.Scanner(input); 
    //---! All math operations here 
    } 
} 
+0

如果用戶輸入一個數字,此解決方案將錯過輸入。 – jjnguy 2010-10-18 20:57:06