2013-10-23 20 views
1

我試圖使用Scanner從用戶輸入中捕獲整數。這些整數表示座標和介於0和1000之間的半徑。它是2D平面上的一個圓。從Java中的字符串中捕獲整數

要做的是以某種方式從一行分別捕獲這些整數。因此,舉例來說,用戶輸入

5 100 20 

因此,x座標爲5時,y座標爲100,半徑爲20

用戶必須輸入所有這些值上同一行,我必須以某種方式將程序中的值捕獲到三個不同的變量中。

所以,我嘗試使用這樣的:

Scanner input = new Scanner(System.in); 
String coordAndRadius = input.nextLine(); 

int x = coordAndRadius.charAt(0); // x-coordinate of ship 
int y = coordAndRadius.charAt(2); // y-coordinate of ship 
int r = coordAndRadius.charAt(4); // radius of ship 

一個數字字符,作爲測試。沒有那麼好。

有什麼建議嗎?

回答

3

那麼最簡單的方法(不是最好的之一)只是其拆分成使用數組String方法:

public static void filesInFolder(String filename) { 
    Scanner input = new Scanner(System.in); 
    String coordAndRadius = input.nextLine(); 
    String[] array = coordAndRadius.split(" "); 

    int x = Integer.valueOf(array[0]); 
    int y = Integer.valueOf(array[1]); 
    int r = Integer.valueOf(array[2]); 
} 

您還可以使用nextInt方法,它看起來像這樣:

public static void filesInFolder(String filename) { 
    Scanner input = new Scanner(System.in); 
    int[] data = new int[3]; 
    for (int i = 0; i < data.length; i++) { 
     data[i] = input.nextInt(); 
    }    
} 

您的輸入將被空間被存儲在陣列data

3

使用coordAndRadius.split(" ");創建一個字符串數組,並提取每個數組元素的值。

3

您必須將輸入拆分爲3個不同的字符串變量,每個字符串變量可以分別進行分析。使用split method返回一個數組,每個元素包含一個輸入。

String[] fields = coordAndRadius.split(" "); // Split by space 

然後你就可以使用Integer.parseInt分析每件爲int

int x = Integer.parseInt(fields[0]); 
// likewise for y and r 

只要確保你有你的陣列中的3個元素訪問它之前。

1

拆分值

爲INT使用
String[] values = coordAndRadius.split(" "); 

然後得到每個值:

int x = Integer.parseInt(values[0]); 
int y = Integer.parseInt(values[1]); 
int radious = Integer.parseInt(values[2]); 
2

試試這個:

Scanner scanner = new Scanner(System.in); 

System.out.println("Provide x, y and radius,"); 
int x = scanner.nextInt(); 
int y = scanner.nextInt(); 
int radius = scanner.nextInt(); 

System.out.println("Your x:"+x+" y: "+y+" radius:"+radius); 

它會工作,要麼你就輸入 「10 20 24」 或「10 \ N20 \ n24「,其中\ n當然是一個換行符。

以防萬一你想知道你的方法在這裏不起作用的原因是解釋。

int x = coordAndRadius.charAt(0); 

的charAt(0)返回您的字符串,然後被隱式澆鑄成INT的第一個字符。假設你的coordAndRadius =「10 20 24」。所以在這種情況下,第一個字符是'1'。所以上面的語句可以寫成: int x =(int)'1';

相關問題