在我的游戏中,当我收集木材时,我正试图增加木材的价值,但我无法弄清楚如何。这是我的代码:
package Main;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("In order to build your house, you need 25 wood"); //I haven't added building the house yet
System.out.println("To gather wood type 'gather wood'. (no caps)");
while (true) {
Scanner scan = new Scanner(System.in);
Random Random = new Random();
String getWood = "gather wood";
int randomNumber = Random.nextInt(11);
int wood = 0;
String s = scan.nextLine();
if (s.contains( getWood )) {
System.out.println("You have gathered " + randomNumber + " wood!");
} else {
}
}
}
}
当我输入“聚集木材”时,我希望它向int变量“wood”添加一个金额,最好是“System.out.println”中的相同随机数(“你已经聚集了”+ randomNumber +“wood!” );“
感谢任何帮助!
谢谢! :d
答案 0 :(得分:1)
您希望在while循环之外声明变量wood,否则它将始终重置为零。 然后你可以像这样添加随机数:
webmaster@localhost
这是简短形式:
wood += randomNumber;
答案 1 :(得分:0)
这应该做到
{ "COM1", "COM5", "COM5", "COM5", "COM5", "COM5", "COM5" }
答案 2 :(得分:0)
在if语句中它将是:
System.out.println("In order to build your house, you need 25 wood"); //I haven't added building the house yet
System.out.println("To gather wood type 'gather wood'. (no caps)");
int wood = 0;
while (true) {
Scanner scan = new Scanner(System.in);
Random Random = new Random();
String getWood = "gather wood";
int randomNumber = Random.nextInt(11);
String s = scan.nextLine();
if (s.contains( getWood )) {
System.out.println("You have gathered " + randomNumber + " wood!");
wood+=randomNumber ;
System.out.println("You now have " + wood + " wood!");
} else {
}
}
你可能想考虑创建一个类并访问“wood”变量吗?
答案 3 :(得分:0)
将int wood = 0;
放在循环之外。您可以在每个循环中创建一个值为0的新变量。
您还需要将wood += randomNumber;
放在if语句中。否则,木材的价值不会改变。
答案 4 :(得分:0)
如何将一个添加到int变量
int something = 1;
something++;
变量现在将为2。
如何添加金额:
int something = 1;
something += 5;
变量现在将为6。
如何添加超过1个金额:
int something = 1;
something = something+1+1+1;
现在变量将是4。
创建变量时如何向变量添加金额:
int something = 1+3;
变量现在将是4。 我认为这就是你在不评论你所做的意思时的意思,我会尽力帮助你!