我一直在尝试这个问题但是我仍然无法找到解决方案。任何帮助表示赞赏!感谢
问题 - 声明并创建一个数组来存储四个玩家的名字。调用数组pNames。
要求用户输入四个播放器的名称并将其名称存储在pNames数组中。
private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable(inputTable.TableName);
outputTable.Columns.Add(inputTable.Columns[0].ColumnName);
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
newRow[0] = inputTable.Columns[rCount].ColumnName;
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
输出问候消息以迎接每个玩家。
Enter Name of Player 1 > Johnny
Enter Name of Player 2 > Jackie
Enter Name of Player 3 > Jessie
Enter Name of Player 4 > Jeremy
答案:
Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy
}
答案 0 :(得分:4)
数组基于0索引。
在循环中,您使用的是1索引库。
更改
for(int i = 1; i <= pNames.length; i++) {
System.out.print("Enter name of Player" + " " + i + " > ");
pNames[i] = sc.nextLine();
}
到
for(int i = 1; i <= pNames.length; i++) {
System.out.print("Enter name of Player" + " " + i + " > ");
// The index of pNames must start from 0!
pNames[i-1] = sc.nextLine();
}
更接近程序员推理模式的解决方案是使用从0开始的循环并更改System.out,如下所示:
// Loop start from 0 and goes to 4 excluded
for (int i = 0; i < pNames.length; i++) {
// To print Enter name of Player 1 change i to (i + 1)
System.out.print("Enter name of Player" + " " + (i + 1) + " > ");
pNames[i] = sc.nextLine();
}
答案 1 :(得分:2)
不是从1开始索引,而是需要将数组索引启动为0并在显示“输入播放器名称”时,只显示i的递增值1
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String [] pNames = new String[4];
for(int i = 0; i < pNames.length; i++) {
System.out.print("Enter name of Player" + " " + (i+1) + " > ");
pNames[i] = sc.nextLine();
}
System.out.println("Hello" + " " + pNames[0]);
System.out.println("Hello" + " " + pNames[1]);
System.out.println("Hello" + " " + pNames[2]);
System.out.println("Hello" + " " + pNames[3]);
}
答案 2 :(得分:0)
请改为尝试:
从0开始,使用sc.Next();
代替sc.nextLine();
:
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String [] pNames = new String[4];
for(int i = 0; i < pNames.length; i++) {
int a = i+1;
System.out.print("Enter name of Player" + " " + a + " > ");
pNames[i] = sc.next();
}
System.out.println("Hello" + " " + pNames[0]);
System.out.println("Hello" + " " + pNames[1]);
System.out.println("Hello" + " " + pNames[2]);
System.out.println("Hello" + " " + pNames[3]);
}
}
答案 3 :(得分:0)
只需更改此行:
pNames[i] = sc.nextLine();
到此:
pNames[i-1] = sc.nextLine();
由于您正在访问1到4,因此您的数组实际上在0-3范围内,因此您需要减去一个。