【问题标题】:Print number from a line从一行打印数字
【发布时间】:2018-01-20 19:02:04
【问题描述】:

我是编程新手,似乎无法解决这个问题。任何帮助表示赞赏,我目前显示了我的代码。非常感谢您。

输入的第一行包含要跟随的行数

  • 每行的第一个数字 n >= 2 包含该行后面的整数个数
  • 这 n 个整数(每个整数 >= 0; <= 1000)一直到行尾,并且应该使用索引号 1...n - 1 存储在数组中(最后一个除外)
  • 行中的最后一个整数 p (p >= 1 & p <= n - 1) 是要从行中选择并打印的整数的索引(从 1 开始)

到目前为止的代码:

public static void main(String[] args) {
    // Scanner to take the inputs
    Scanner input = new Scanner(System.in);

    // Variables
    int numOfLines;
    int di = 0;
    int n;

    // The arrays to store the results
    int[] data = new int[100];
    int[] result = new int[100];

    System.out.println("**Input**");
    // Read number of lines to follow
    numOfLines = input.nextInt();
    while (di < numOfLines) {
        // Read first integer of each line
        n = input.nextInt();
        // Store n-1 integers to array
        for (int dj = 1; dj <= n - 1; dj++) {
            data[dj] = input.nextInt();
        }
        // Multiply selected numbers and store to array
        result[di] = data[dj];
        di++;
    }
}

【问题讨论】:

标签: java arrays algorithm


【解决方案1】:

你说你无法解决这个问题。首先要做的是在编码之前清楚地理解问题。为了更清楚,在每一行,用户将输入如下内容:

<b><i>4</i></b> 500 600 700 <b><i>1</i></b>
  • 第一个数字表示后面有多少个数字。您在此处看到有四个紧随其后。
  • 最后一个数字表示要打印哪个索引。您会看到需要第一个数字。
  • 中间的数字是可以选择的数字。

所以,输出应该是中间的第一个数字,即500,所以输出应该是这样的:

The number is: 500

根据您的规范,您的代码中存在一些问题:

  1. data 数组在您的源代码中不能有固定大小(例如 100),因为如果您为其选择固定大小,用户总是可以选择其中包含比 @ 更多的数字的行987654324@数组可以容纳。您应该在每行输入的开头将 data 替换为一个大小合适的新数组。
  2. 不需要result 数组,因为您只需立即打印出所需的数字,而无需存储以供以后使用。
  3. // Multiply selected numbers and store to array 是不正确的评论,应该删除。
  4. 您需要添加一行代码来输入该行最后输入的数字作为所需的索引。
  5. 您需要在data 中打印出所需索引处的数字。

为了学习,我建议:

  1. 花时间了解问题
  2. 清楚地了解为什么需要进行这些更改
  3. 进行更改
  4. 检查一切是否正常
  5. 从头开始练习(在新的源代码文件中,这样您就不会删除您的工作版本),以更好地理解并看看您是否可以在没有帮助的情况下使其工作

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 2016-10-16
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多