繁体   English   中英

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

[英]Inserting values into two array using scanner class in java

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 : ##############

您应该将内部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()扫描器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM