在學習基礎知識之後,我嘗試使用Java中的第一個項目,因此我很抱歉可能是一個完整的初學者問題。我一直在尋求整個下午的幫助,並且我的代碼開始顯得雜亂無章。檢查存儲在ArrayList中的值是否大於數字
我正在嘗試創建一個滾動d10s數的骰子滾輪,然後檢查有多少個是7或以上,並將它們計數/顯示爲成功。如果沒有一個成功,我希望它顯示「Botch」。
經過一番研究,我發現創建一個ArrayList,並從那裏(我認爲)是最好的選擇。但是我現在已經陷入了一段時間,出現了不同的錯誤和問題,每當我拿下一個,代碼變得更加混亂,我的目標似乎更遠。我的朋友說「歡迎編程」,並建議我問社區。
這裏是我的工作:
import java.util.Scanner;
import java.util.ArrayList;
public class RollDie {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String numberOfDice;
// User input for number of dice to roll
System.out.print("How many dice? ");
numberOfDice = userInput.next();
System.out.println("Rolling " + numberOfDice + " dice!");
userInput.close();
Integer roll = 0;
int dice = Integer.parseInt(numberOfDice);
int sides = 10; // # of die sides
ArrayList<Integer> sux = new ArrayList<Integer>(); // Store results of roll
// print result
for(int d=0; d < dice; d++) {
// roll should be 1 through sides
roll = (int) (Math.random() * sides) + 1;
sux.add(roll);
}
System.out.println(sux);
// Count successes and print or check for botch
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) {
s++;
System.out.println(s + " successes!");
} else {
System.out.println("BOTCH!");
break;
}
}
}
}
一切都將打印SUX的ArrayList後是一個爛攤子。我知道for循環是錯誤的,我只是不知道如何使它正確。變量s似乎不合適...任何幫助將不勝感激,並讓我知道這篇文章是否違反社區標準。謝謝!
編輯:爲了澄清我的ramblings,我的問題是:如何檢查滾動後添加到ArrayList的數字是否大於或等於7(或任何數字)?
_IF沒有一個是成功的,我希望它顯示「誤事」 _軋輥的,這違背了你的代碼,而你應該採取'的System.out.println(「誤事!」);'出來並使用標誌變量來幫助識別何時適合顯示它。在我看來,你問**多個**問題,請考慮編輯你的帖子,從而限制它只有**一個**具體問題。 –
謝謝你的迴應和幫助,我想我的帖子確實有點複雜和臃腫,直到出現多個問題。 – Zero