如何获取自定义输入

第一行包含两个分隔的整数 N 和 M。其中 N 代表建筑物数量,M 代表道路。


接下来是 M 行,每行由 4 个整数 IJKL 组成,分别代表建筑物的楼层、建筑物的窗户、爬楼的时间、过马路的时间。


我已经能够按如下方式接受第一个输入:


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 个输入。I J K L


我该怎么做呢??


第二部分的输入和输出应该是这样的:


输入:


Road:0

12 34 44 56


Road:1

22 76 89 90

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


呼啦一阵风
浏览 135回答 2
2回答

胡子哥哥

我在为第二部分输入时感到震惊,这将包括一个 M 时间循环,每次输入 4 个输入,分别为 IJKL根据您的要求,我建议您创建一个类而不是使用原始类型。这比制作二维数组更容易,而且您可以对数据做更多的事情。由于我不完全知道这个问题,我会假设(建筑物的地板、建筑物的窗户、爬上建筑物所花费的时间、过马路所花费的时间)都是道路的属性。如果没有,那么您可以对建筑物进行同样的操作并将属性从道路移动到建筑物道路类public class Road {&nbsp; &nbsp; private int floorsOfBuilding;&nbsp; &nbsp; private int windowsInBuilding;&nbsp; &nbsp; private int climbTime;&nbsp; &nbsp; private int crossingTime;&nbsp; &nbsp; // Constructor&nbsp; &nbsp; public Road(int floorsOfBuilding, int windowsInBuilding, int climbTime, int crossingTime) {&nbsp; &nbsp; &nbsp; &nbsp; this.floorsOfBuilding = floorsOfBuilding;&nbsp; &nbsp; &nbsp; &nbsp; this.windowsInBuilding = windowsInBuilding;&nbsp; &nbsp; &nbsp; &nbsp; this.climbTime = climbTime;&nbsp; &nbsp; &nbsp; &nbsp; this.crossingTime = crossingTime;&nbsp; &nbsp; &nbsp; &nbsp; // You can do simple calculations here but for more complex it is better&nbsp; &nbsp; &nbsp; &nbsp; // to create a method to maintain readability&nbsp; &nbsp; }&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return "\n" + floorsOfBuilding + " " + windowsInBuilding + "&nbsp; " + climbTime + "&nbsp; " + crossingTime;&nbsp; &nbsp; }}主课int roadsCount = Integer.parseInt(buildingsAndRoadsArray[1]);Road[] roadsArray = new Road[roadsCount];for (int i = 0; i < roadsArray.length; i++) {&nbsp; &nbsp; System.out.println();&nbsp; &nbsp; System.out.println("Road:" + i);&nbsp; &nbsp; System.out.print("Enter I J K L: ");&nbsp; &nbsp; String input = scan.nextLine();&nbsp; &nbsp; String[] inputSplit = input.split(" ");&nbsp; &nbsp; Road road = new Road(Integer.parseInt(inputSplit[0]), Integer.parseInt(inputSplit[1]),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Integer.parseInt(inputSplit[2]), Integer.parseInt(inputSplit[3]));&nbsp; &nbsp; roadsArray[i] = road;}scan.close();System.out.println();for (int i = 0; i < roadsArray.length; i++) {&nbsp; &nbsp; System.out.println("Road: " + i + roadsArray[i] + "\n");}输出Enter Number of Buildings and Roads: 1 2// InputRoad:0Enter I J K L: 12 13 14 15Road:1Enter I J K L: 49 59 69 79// OutputRoad: 012 13&nbsp; 14&nbsp; 15Road: 149 59&nbsp; 69&nbsp; 79

智慧大石

for (int i = 0; i < M; i++) {&nbsp; &nbsp; int I = sc.nextInt();&nbsp; &nbsp; int J = sc.nextInt();&nbsp; &nbsp; int K = sc.nextInt():&nbsp; &nbsp; int L = sc.nextInt();&nbsp; &nbsp; // your code here}由于输入是常数,您可以直接输入数字。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java