簡體   English   中英

如何接受自定義輸入

[英]How to Take custom inputs

第一行包含兩個分開的整數N和M。其中N代表建築物數量,M代表道路。

接下來的M行,每行由4個整數IJKL組成,分別代表建築物的樓層,建築物中的Windows,爬建築物所需的時間,過馬路所需的時間。

我已經能夠接受如下的第一個輸入:

Scanner sc = new Scanner(System.in);
System.out.println("Enter N and M");
String NandM = sc.nextLine();
String [] NandMAsArray = NandM.split(" ");
int N = Integer.parseInt(NandMAsArray[0]);
int M = Integer.parseInt(NandMAsArray[1]);

我在輸入第二部分時感到震驚,這將包括一個M時間循環,每次輸入4次輸入,分別是IJKL

我該怎么做呢??

第二部分的輸入和輸出應如下所示:

輸入:

Road:0
12 34 44 56

Road:1
22 76 89 90

https://i.postimg.cc/28fQ3dVR/Screenshot-20190807-121551-Chrome.jpg

for (int i = 0; i < M; i++) {
    int I = sc.nextInt();
    int J = sc.nextInt();
    int K = sc.nextInt():
    int L = sc.nextInt();

    // your code here
}

由於輸入是恆定的,因此您可以直接輸入數字。

我在輸入第二部分時感到震驚,這將包括M次循環並每次輸入4次輸入,分別為IJKL

根據您的要求,建議您創建一個類,而不要使用原始類型。 這將比制作2D數組容易,而且您可以處理更多數據。

由於我不完全了解問題,因此我將假定(建築物地板,建築物中的Windows,爬建築物所需的時間,過馬路所需的時間)都是道路的屬性。 如果不是,那么您可以對建築物進行相同操作,並將屬性從道路移動到建築物

道路等級

public class Road {

    private int floorsOfBuilding;
    private int windowsInBuilding;
    private int climbTime;
    private int crossingTime;

    // Constructor
    public Road(int floorsOfBuilding, int windowsInBuilding, int climbTime, int crossingTime) {
        this.floorsOfBuilding = floorsOfBuilding;
        this.windowsInBuilding = windowsInBuilding;
        this.climbTime = climbTime;
        this.crossingTime = crossingTime;
        // You can do simple calculations here but for more complex it is better
        // to create a method to maintain readability
    }

    public String toString() {
        return "\n" + floorsOfBuilding + " " + windowsInBuilding + "  " + climbTime + "  " + crossingTime;
    }
}

主班

int roadsCount = Integer.parseInt(buildingsAndRoadsArray[1]);
Road[] roadsArray = new Road[roadsCount];
for (int i = 0; i < roadsArray.length; i++) {
    System.out.println();
    System.out.println("Road:" + i);
    System.out.print("Enter I J K L: ");
    String input = scan.nextLine();
    String[] inputSplit = input.split(" ");
    Road road = new Road(Integer.parseInt(inputSplit[0]), Integer.parseInt(inputSplit[1]),
            Integer.parseInt(inputSplit[2]), Integer.parseInt(inputSplit[3]));
    roadsArray[i] = road;
}
scan.close();
System.out.println();
for (int i = 0; i < roadsArray.length; i++) {
    System.out.println("Road: " + i + roadsArray[i] + "\n");
}

輸出量

Enter Number of Buildings and Roads: 1 2
// Input
Road:0
Enter I J K L: 12 13 14 15

Road:1
Enter I J K L: 49 59 69 79
// Output
Road: 0
12 13  14  15

Road: 1
49 59  69  79

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM