2017-03-02 71 views
0

我想創建一個骰子程序,我需要的輸出是'一個','兩','三'等字符串。它當前正在打印輸出0,但這是因爲我的OutputDice方法是不正確的。當我拿出它時,它將整個參數作爲整數傳遞,但我需要它們作爲字符串。我怎麼做?如何將整數方法轉換爲Java中的字符串方法?

我的代碼如下:

import java.util.Random; 

public class Dice { 

    private int Value; 

    public void setValue(int diceValue) 
    { 
      Value = diceValue; 
    } 
    public int getValue() 
    { 
      return Value; 
    } 
    public void roll() 
    { 
     Random rand = new Random(); 
      Value = rand.nextInt(6) + 1; 
    } 
    public void OutputDice() 
    { 
     switch (Value) 
     { 
     case 1: 
      System.out.println("One"); 
     case 2: 
      System.out.println("Two"); 
     case 3: 
      System.out.println("Three"); 
     case 4: 
      System.out.println("Four"); 
     case 5: 
      System.out.println("Five"); 
     case 6: 
      System.out.println("Six"); 
     } 
    } 
} 

public class DiceRoll { 

    public static void main(String[]args) { 

     Dice firstDie = new Dice(); 
     Dice secondDie = new Dice(); 

     firstDie.OutputDice(); 
     secondDie.OutputDice(); 

     System.out.println("Dice 1: "+ firstDie.getValue()); 
     System.out.println("Dice 2: "+ secondDie.getValue()); 
    } 
} 
+1

你忘記打電話'roll' –

+0

如果你不滾你的骰子,我不認爲它會得到你的任何號碼。 :) – Blank

回答

3

還從未值分配給你的骰子。在顯示值之前,您需要調用roll()方法。此外,隨着開關case語句,你需要包括休息後,你的情況如此

public void OutputDice() 
{ 
    switch (Value) 
    { 
    case 1: 
     System.out.println("One"); 
     break; 
    case 2: 
     System.out.println("Two"); 
     break; 
    case 3: 
     System.out.println("Three"); 
     break; 
    case 4: 
     System.out.println("Four"); 
     break; 
    case 5: 
     System.out.println("Five"); 
     break; 
    case 6: 
     System.out.println("Six"); 
     break; 
    } 
} 
0

感謝您的幫助。這是一個簡單的疏忽。下面是我得到的答案:

import java.util.Random; 

    public class Dice { 

     private int Value; 

     public void setValue(int diceValue){ 
       Value = diceValue; 
     } 
     public int getValue(){ 
       return Value; 
     } 
     public void roll(){ 
      Random rand = new Random(); 
       Value = rand.nextInt(6) + 1; 
     } 
     public void OutputDice(){ 
      switch (Value) 
      { 
      case 1: 
       System.out.println("One"); 
       break; 
      case 2: 
       System.out.println("Two"); 
       break; 
      case 3: 
       System.out.println("Three"); 
       break; 
      case 4: 
       System.out.println("Four"); 
       break; 
      case 5: 
       System.out.println("Five"); 
       break; 
      case 6: 
       System.out.println("Six"); 
       break; 
      } 
     } 
    } 

public class BrandonAssignment4 { 

    public static void main(String[]args) { 

     Dice firstDie = new Dice(); 
     Dice secondDie = new Dice(); 

     firstDie.roll(); 
     secondDie.roll(); 

     firstDie.OutputDice(); 
     secondDie.OutputDice(); 
    } 
} 
相關問題