【问题标题】:how to print Scanner element using parallel arrays in java?java - 如何在java中使用并行数组打印扫描仪元素?
【发布时间】:2020-09-30 14:05:58
【问题描述】:

我是学习并行数组的新手,想知道如何仅使用并行数组有效地打印内容/元素,我尝试过但无法让它按我想要的方式工作和运行。

任务是:程序从用户那里输入一个整数,表示将输入多少人的信息。然后,程序一次输入一个人的信息(首先是姓名,然后是年龄),并将这些信息存储在两个相关的数组中。

接下来,程序输入一个整数,表示列表中应显示其信息的人(要获取第一个人的信息,用户将输入“1”)。该程序会声明此人的姓名和年龄。

虽然在用户输入整数之前我得到了工作的姓名和年龄,但之后我不知道该怎么做

示例输入:

4
Vince
5
Alexina
8
Ahmed
4
Jorge
2
2 // I am confused about this part, how would I make it so that it prints the desired name,
     //for example with this input, it should print:

样本输出:

Alexina is 8 years old

我的代码:

import java.util.Scanner;

class Example {
  public static void main (String[] args) {

    Scanner keyboard = new Scanner(System.in);

    int[] numbers = new int[keyboard.nextInt()];
    for (int x = 0; x < num.length; x++){
    String[] name = {keyboard.next()};
    int[] age = {keyboard.nextInt()}; 
    }
    int num2 = keyboard.nextInt();
        System.out.println(); // what would I say here?
  }
}

【问题讨论】:

  • 由于您的数组是在for 循环中定义的,因此它们仅在此循环中可见。尝试在循环之前定义。

标签: java arrays parallel-arrays


【解决方案1】:

我认为你必须考虑 java 中局部和全局变量的使用。简而言之, 局部变量只能在方法或块中使用,局部变量只对声明它的方法或块可用。 例如:

{ 
  int y[]=new Int[4];
}

这个 y 数组只能在块内访问。 全局变量必须在类主体的任何地方声明,但不能在任何方法或块内声明。如果一个变量被声明为全局变量,它可以在类中的任何地方使用。 在您的代码中,您尝试创建数组并在 For 循环之外使用它们。但是您的数组仅在 For 循环内有效。每次循环运行后,所有信息都会丢失。For 循环的每次迭代都会创建新的数组。

因此,为了访问和保存信息,您必须在 For 循环之前声明数组,并使用迭代次数作为索引来访问和存储数据。最后,要打印您收集的数据,您必须将新输入扫描为整数变量。然后您可以根据需要访问您的数组。


    //For example 
    int [] age=new int[4]; //global -Can access inside or outside the For loop
    int[] numbers = new int[keyboard.nextInt()];
    for (int x = 0; x < 4; x++){

       age[x] = keyboard.nextInt(); //Local 
    }
    int num2 = keyboard.nextInt();
    System.out.println(age[num2]); // Here you have to access global arrays using num2 num2
  }
}

【讨论】:

    【解决方案2】:

    您需要重写您的代码,这样您的数组就不会在循环中被分配。您希望向数组添加值,而不是每次都重置它们,并且您希望之后能够访问它们。以下是您的代码的修改版本:

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
    
        int num = keyboard.nextInt();
        keyboard.nextLine(); //you also need to consume the newline character(s)
        String[] name = new String[num]; //declare the arrays outside the loop
        int[] age = new int[num]; 
        for (int x = 0; x < num; x++){
            name[x] = keyboard.nextLine(); //add a value instead of resetting the array
            age[x] = keyboard.nextInt();
            keyboard.nextLine(); //again, consume the newline character(s) every time you call nextInt()
        }
        int num2 = keyboard.nextInt() - 1; //subtract one (array indices start at 0)
        System.out.println(name[num2] + " is " + age[num2] + " years old"); //construct your string with your now-visible arrays
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      相关资源
      最近更新 更多