使用Java中的扫描程序类将值插入两个数组

时间:2018-08-21 19:18:32

标签: java arrays

import java.util.Scanner;
public class Demo3 
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter how many friends: ");
        int numOfFriends = Integer.parseInt(scan.nextLine());
        String arrayOfNames[] = new String[numOfFriends];
        long income[] = new long[numOfFriends];
        for (int i = 0; i < arrayOfNames.length; i++) 
        {
            System.out.print("\nEnter the name of friend " + (i+1) + " : ");
            arrayOfNames[i] = scan.nextLine();
            for(int j = 0; j<arrayOfNames.length;j++)
            {
                System.out.print("\nEnter the income of friend " + (j+1) + " : ");
                income[j] = scan.nextLong();
            }
        }
    }
}

这是我的代码,我想从用户那里获取输入名称,然后从该人的收入中提取,然后再从另一个人的名字中获取 上面的代码排列不正确,我认为for循环中的问题示例输出应该像这样:

Enter how many friends: 2
Enter name of friend 1 : #############
Enter income of friend 1 : ############## 
Enter name of friend 2 : #############
Enter income of friend 2 : ##############

1 个答案:

答案 0 :(得分:1)

您应该使用for循环的内部。

import java.util.Scanner;
public class Demo3
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter how many friends: ");
        int numOfFriends = Integer.parseInt(scan.nextLine());
        String arrayOfNames[] = new String[numOfFriends];
        long income[] = new long[numOfFriends];
        for (int i = 0; i < arrayOfNames.length; i++)
        {
            System.out.print("\nEnter the name of friend " + (i+1) + " : ");
            arrayOfNames[i] = scan.nextLine();
        }
        for(int j = 0; j<arrayOfNames.length;j++)
        {
            System.out.print("\nEnter the income of friend " + (j+1) + " : ");
            income[j] = scan.nextLong();
        }
        scan.close();
    }
}

此外,如果要按顺序输入它们,则只应使用一个for循环

import java.util.Scanner;
public class Demo3
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter how many friends: ");
        int numOfFriends = Integer.parseInt(scan.nextLine());
        String arrayOfNames[] = new String[numOfFriends];
        long income[] = new long[numOfFriends];
        for (int i = 0; i < arrayOfNames.length; i++)
        {
            System.out.print("\nEnter the name of friend " + (i+1) + " : ");
            arrayOfNames[i] = scan.nextLine();
            System.out.print("\nEnter the income of friend " + (i+1) + " : ");
            income[i] = scan.nextLong();
            scan.nextLine();
        }
        scan.close();
    }
}

请注意,完成任务后,请不要忘记close()扫描仪。