[英]Is there a way to split input into 4 int and pass onto a method (int a, int b, int c, int d) in java?
我有這個問題。 假設我想從輸入的第一行開始獲取用戶輸入作為 integer 將確定輸入的數量,並且輸入必須是 4 個類別的數字(天、小時、分鍾、秒)。 作為輸入示例
輸入:
輸入 integer:3
4 5 6 3555
6 11 3 120
1 0 44 11
現在我想要對這些輸入做的是存儲它們並分隔包含 4 個數字的每一行(然后分隔 4 個數字),然后我想將每一行傳遞給一個接受 4 個參數的方法。
可能嗎? 以及如何編碼?
您可以將 BufferedReader 與 InputStreamReader 一起使用,並將每一行讀取為String
並使用 Wrapper class 將其包裝為 int 以將 String 轉換為 int 我們使用此方法Integer.parseInt(<String yourString>)
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int totalLines = Integer.parseInt(br.readLine());
for(int i = 0; i < totalLines ; i++){
String [] num = br.readLine().split(" ");
int num1 = Integer.parseInt(num[0]);
int num2 = Integer.parseInt(num[1]);
int num3 = Integer.parseInt(num[2]);
int num4 = Integer.parseInt(num[3]);
// here call the method you want to call
}
.split(" ")
將根據我們在其中定義的參數拆分行,在您的情況下它是space
並記住 split 返回一個字符串數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.