【问题标题】:Ask for certain number of inputs based on integer input根据整数输入请求一定数量的输入
【发布时间】:2020-02-06 06:37:59
【问题描述】:

我什至不知道如何正确地提出这个问题,但我被分配了一个任务,要求我向用户询问输入(在这种情况下,它是一些绵羊)。然后,在他们输入一个数字(比如 5)后,我应该要求用户根据他们输入的整数分配一个 x 和 y 坐标值。我目前的理论是将原始数字存储在一个数组中,然后根据它们的值以某种方式询问用户有多少坐标(或一组 2 个数字)。

我真的不知道如何开始,但到目前为止我会附上我的代码。

private int x, y;

public static void main(String[] args) {
    Scanner sheepScanner = new Scanner(System.in); //Allows for user input
    System.out.println("Enter a number of Sheep"); //Asks user for input


    int numSheep = sheepScanner.nextInt(); //reads in number of sheep and stores it in variable numSheep
    int totalSheep[] = new int[numSheep]; //creates an array called totalSheep based on numSheep
    //System.out.println(totalSheep);
        for (int i = 1; i < totalSheep.length; i++) {
            totalSheep[i]=Integer.parseInt(); //literally no idea what's going here

【问题讨论】:

    标签: java arrays loops


    【解决方案1】:

    根据我的理解,您需要做的只是从用户那里获取输入并将其存储在向量/数组中。然后根据输入的值运行一个循环并将其添加到地图中。

    HashMap<Integer,String> map= new HashMap<>();
    

    然后运行一个for循环直到数字即

    for(int i=0;i<numberOfSheep;i++)
    {
    double x-Cordinate="";//store your values here
    double y-Cordinate="";//store your values here
    String co-ordinates= x-Cordinate +","+y-Cordinate;
    map.put(i,co-ordinates);
    }
    

    现在您将拥有一张带有坐标和绵羊编号的地图。您可以从中获取键和值。例如,如果你想从 5 号羊坐标 地图然后你可以使用。 map.get(sheepNumber) 。如果您想将值与坐标分开,请使用 split(",") 希望我已经回答了您要查找的内容。

    【讨论】:

      【解决方案2】:

      在最后一行使用这个

      totalSheep[i]=i;
      

      【讨论】:

        【解决方案3】:

        所以,如果我正确理解你想要做的基本上是向用户询问一些羊,然后为每只羊询问(这只羊的 x 和 y 坐标?)。

        所以你要做的第一件事就是询问羊的数量并将其存储到numSheep,这看起来不错。

        然后你创建一个数组。这里你真正需要的可能是一个二维数组,比如

        int[][] coordinates = new int[sheepNum][2];
        

        所以它将是一个包含 5 个数组的数组,每个数组的长度为 2。这些将是 (x,y) 坐标,与用户输入的一样多。如果用户输入 5,则该数组将保存 5 组 (x,y) 坐标。

        然后你从 0 开始循环到这个数组的长度,这样也可以。

        for (int i = 1; i < coordinates.length; i++) { ... }
        

        注意coordinates.length 只是sheepNum,因为数组包含sheepNum 元素(x-y 对)。

        在这个循环中,你有变量i,它从0sheepNum,它是当前羊的数量。

        所以在这个循环中你需要做的就是填充数组。

        所以再读两个整数(羊号ixy

        并将这些值存储到coordinate[i][0]coordinate[i][1]

        完成:)

        【讨论】:

        • 那么从循环中的信息来看,这会是怎样的呢?所以基本上,唯一的区别只是一个二维数组而不是一维数组。在那之后我会在循环中做什么? 'totalSheep[i]=Integer.parseInt()' 不起作用。
        • 坐标[i][0] =sheepScanner.nextInt();和坐标[i][1] =sheepScanner.nextInt();所以用户输入这只羊的x和y。仅此而已。
        • 你只是将坐标初始化为一个整数吗?
        猜你喜欢
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-16
        • 1970-01-01
        相关资源
        最近更新 更多