开发者

c# Fill multiple arrays with input

I'm trying to fill 3 arra开发者_JS百科ys with user input, it should look like this:

Enter account number 1: 29384
Enter the account balance: 1111
Enter the account holder last name: lastname
Enter account number 2: 34938
Enter the account balance: 2222
Enter the account holder last name: lastname2
Enter account number 3: 46372
Enter the account balance: 3333
Enter the account holder last name: lastname3
and so on...

I have my program set up with for loops to fill a 5 line array but it asks for all five account numbers first then goes onto the balance and so on

using System;
public class Array1
{
    public static void Main()
    {
        int[] scores = new int[5];
        int x;
        string inputString;
        int[] balance = new int[5];
        int y;

        for(x=0; x < scores.Length; ++x)
        {
            Console.Write("Enter account number {0} ", x + 1);
            inputString = Console.ReadLine();
            scores[x] = Convert.ToInt32(inputString);
            }
        for(y=0; y < balance.Length; ++y)
        {
            Console.Write("Enter the account balance ");
            inputString = Console.ReadLine();

            }
    }
}

I'm sure there is a much better way to write this. Any help would be appreciated.


Yes.

Why not have a class with a structure

class DataHolder
{
  public String account_number;
  public int balance;
  public String lastname;
}

Then you're at least holding relevant data together

Your code then does as you've instructed, its asked to get all the accounts, then all the balances..

Where as 1 loop would have been sufficient

If you had an array of DataHolder class

DataHolder[] testData = new DataHolder[5];
For (int x=0; < x testData.length; x++)
{
 Console.Write("Account Number");
 testData[x].account_number= Console.ReadLine();
 Console.Write("Balance");
 testData[x].balance=Convert.ToInt32(Console.ReadLine());
 Console.Write("LastName");
 testData[x].lastname=Console.ReadLine();
}


I think you just want one for loop.

for(x=0; x < scores.Length; ++x)
{
        Console.Write("Enter account number {0} ", x + 1);
        inputString = Console.ReadLine();
        scores[x] = Convert.ToInt32(inputString);

        Console.Write("Enter the account balance ");
        inputString = Console.ReadLine();

   // and so on
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜