我在java简介课程中,我知道这个问题对你来说可能很简单,但我确实需要帮助。 所以我试图从包含名称和收入的文件中读取,我想将它们读入不同的数组。
@{
Func<object, HelperResult> markup1 = @<text>hello world</text>;
new HtmlString(markup1.Invoke(null).ToString());
Func<object, HelperResult> markup2 = @<h1>hello world</h1>;
new HtmlString(markup2.Invoke(null).ToString());
}
答案 0 :(得分:1)
你快到了。我想这只是错误名称[ 12 ],fname [ 12 ],收入[ 12 ]在此期间:
while (infile.hasNextLine())
{
lname[12] = infile.next();
fname[12] = infile.next();
income[12] = infile.nextDouble();
} //而
假设您只需要文件中的前12行,它必须如下所示:
int lineIdx =0;
while (infile.hasNextLine() && lineIdx < 12)
{
lname[lineIdx] = infile.next();
fname[lineIdx] = infile.next();
income[lineIdx] = infile.nextDouble();
lineIdx++;
}//while
更新:工作逻辑(请阅读代码中的注释)...抱歉延迟。
// 1. Define two arrays
String[] families = null;
double[] taxes = null;
// 2. Read file:
while (infile.hasNextLine()) {
String personLastName = infile.next();
// skip first name
infile.next();
double personTax = infile.nextDouble();
// add person data
if (null == families) {
// create array for
families = new String[] { personLastName };
taxes = new double[] { personTax };
} else {
boolean familyExists = false;
// check existing families
for (int i = 0; i < families.length; i++) {
if (personLastName.equals(families[i])) {
// got it! add personTax to family owed taxes
taxes[i] += personTax;
familyExists = true;
break;
}
}
if (!familyExists) {
// Extend arrays to put new family
// create temp arrays with size+1
String[] tmpFamilies = new String[families.length + 1];
double[] tmpTaxes = new double[taxes.length + 1];
System.arraycopy(families, 0, tmpFamilies, 0, families.length);
System.arraycopy(taxes, 0, tmpTaxes, 0, taxes.length);
// set new last elements data
tmpFamilies[tmpFamilies.length - 1] = personLastName;
tmpTaxes[tmpTaxes.length - 1] = personTax;
// replace families and taxes with newly created tmp arrays
families = tmpFamilies;
taxes = tmpTaxes;
}
}
}// while
// Print results
System.out.println("Found " + families.length + " families and their taxes");
for (int i=0;i < families.length; i++)
{
System.out.println("family " + families[i] + " owes $" + taxes[i]);
}
答案 1 :(得分:0)
为什么要将它们读入不同的数组?这是你的任务所要求的吗?更好的解决方案是使用您的属性(如Employee)创建一个对象,然后将每个Employee添加到List<Employee>
如果您正在询问如何迭代地向数组中添加项,则需要一个从0开始并以array.length - 1结尾的索引。