【发布时间】:2016-01-08 14:39:24
【问题描述】:
我正在创建一个程序,该程序涉及用户必须以某种格式输入有关游戏的数据,他们将输入几条信息,然后我必须向他们显示这些信息,包括他们玩的游戏的总分和总时间进入。我目前正在使用数组来存储信息,但我不知道如何将他们给我的所有数据相加。这是我目前所拥有的。
//setting up my array.
myArray = input.split(":");
score = Integer.parseInt(myArray[1]);
timePlayed = Integer.parseInt(myArray[2]);
这是我设置数组拆分器。
do {
numGames++;
System.out.println("Enter game information seperated with colons. Example - Game:Score:Mins");
input = scanner.nextLine();
这是我提示用户以我请求的格式输入数据的地方。这将重复,直到他们进入“退出”或达到游戏限制 20。
}while (!input.equalsIgnoreCase("quit") && numGames <20);
System.out.println("Player: " + player );
System.out.println("- - - - - - - - - - - - -");
System.out.println("Games played: " + numGames + ", " + "Score: " + score + ", " + "Time played: " + timePlayed);
然后我希望信息像这样显示,但是当我运行我的程序时,它不会将总游戏时间相加,游戏计数有效,但得分和游戏时间无效。
抱歉,如果这是我的第一篇文章,格式不正确!如果你们需要我的程序中的更多信息或代码来帮助我,请告诉我,我会尝试的!非常感谢! :)
请求的完整代码:
String input;
String player;
int score;
int timePlayed;
float scores;
float time;
Scanner scanner = new Scanner (System.in);
int numGames = 0;
System.out.print("Enter your name: ");
player = scanner.nextLine();
//If the player does not enter a name they are them prompted to do so again until they have.
while (player.isEmpty())
{
System.out.print("Enter your name: ");
player = scanner.nextLine();
}
String[] myArray = new String [2];
//This section is prompting the player to input game data in a format requested.
do {
numGames++;
System.out.println("Enter game information seperated with colons. Example - Game:Score:Mins");
input = scanner.nextLine();
//If the player does not enter any information then this piece of code will run and ask them to do so.
while (input.isEmpty())
{
System.out.println("Enter game information seperated with colons. Example - Game:Score:Mins");
input = scanner.nextLine();
}
//setting up my array.
myArray = input.split(":");
score = Integer.parseInt(myArray[1]);
timePlayed = Integer.parseInt(myArray[2]);
//This displays to the player what they have just entered.
System.out.println("Player: " + player );
System.out.println("- - - - - - - - - - - - -");
System.out.println("Games played: " + numGames + ", " + "Score: " + score + ", " + "Time played: " + timePlayed);
input = scanner.nextLine();
try{
scores = Float.parseFloat(myArray[1]);
time = Float.parseFloat(myArray[2]);
}
catch (NumberFormatException e) {
System.out.println("Error: invalid input, not a number" + e.getMessage());
}
input = scanner.nextLine();
score.add(myArray[0]);
}while (!input.equalsIgnoreCase("quit") && numGames <2);
System.out.println("Player: " + player );
System.out.println("- - - - - - - - - - - - -");
System.out.println("Games played: " + numGames + ", " + "Score: " + score + ", " + "Time played: " + myArray[2]);
System.out.println("Exit");
scanner.close();
【问题讨论】:
-
请显示您的完整代码
-
通过完整代码,我们的意思是here 中的解释。 IE。编译并展示您的问题的一段代码。例如,这应该清楚
input实际上是什么。 -
这不是完整的代码。
score是什么类型?我没有看到你在代码中的什么地方总结了播放时间? -
我还没总结出玩的时间,这是我不明白,不知道怎么做的部分。
标签: java arrays split java.util.scanner string-split