使用public void决定()?

时间:2013-01-24 15:52:40

标签: java

我制作了一个接受用户号码的程序。

我的程序示例:

   int strength, health, luck;

JOptionPane.showMessageDialog(null,"Welcome to Yertle's Quest");    

      String name = JOptionPane.showInputDialog("Enter the name of your character");

       Scanner in = new Scanner(System.in);
     System.out.println("Enter strength (1-10): ");
      strength = in.nextInt();

     System.out.println("Enter health (1-10): ");      
      health = in.nextInt();

     System.out.println("Enter luck (1-10): ");      
      luck = in.nextInt(); 

我的问题是: 用户只能得到15分。如果他为每个统计数据(力量,健康,运气)提供超过10分,则默认值将分配给每个统计数据 - 即5.如果每个统计数据(力量,健康,运气)的总分数超过15,默认值将分配给每个统计数据。

3 个答案:

答案 0 :(得分:0)

鉴于我正确理解了这个问题:

if ( luck + health + strength > 15) {
    luck = 5;
    health = 5;
    strength = 5;
}
if (luck > 10) { luck = 5; }
// same for the other attributes

答案 1 :(得分:0)

if(strength > 10)
{
 defaultToFive(strength);
}

if(health > 10)
{
 defaultToFive(health);
}

if(luck > 10)
{
 defaultToFive(luck);
}

if((strength + health + luck) > 15)
{
 defaultToFive(strength);
 defaultToFive(health);
 defaultToFive(luck);
}

private void defaultToFive(int stat)
{
 stat=5;
}

答案 2 :(得分:0)

使用简单的if语句:

 import java.util.Scanner;

 public class CheckLuck {

 public static void main(String[] args) {
 Scanner in = new Scanner(System.in);int strength,health,luck;
 System.out.println("Enter strength (1-10): ");
 strength = in.nextInt();

   if(strength>10)    /* chech for each value, should not be >10 */
   strength=5;

 System.out.println("Enter health (1-10): ");
 health = in.nextInt();
   if(health>10)
   health=5;

 System.out.println("Enter luck (1-10): ");
 luck = in.nextInt();

   if(luck>10)
      luck=5;


 if(strength+health+luck>15)   /* If sum  is >15 assign 5 to each value */
  strength=health=luck=5;

 }

}

更新:使用public void决定()

(对不起,如果这听起来很有趣)

 import java.util.Scanner;

 public class TestDecide {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);int strength,health,luck;
System.out.println("Enter strength (1-10): ");
strength = in.nextInt();

if(strength>10)
strength=5;

 System.out.println("Enter health (1-10): ");
 health = in.nextInt();

 if(health>10)
 health=5;

 System.out.println("Enter luck (1-10): ");
 luck = in.nextInt();
  if(luck>10)
      luck=5;

if(strength+health+luck>15)
{
strength=health=luck=5;
decide();
}
else
{
    System.out.println("Congrats!!!!!!!!!!!! for your scores");



}

}
public static void decide()
{
System.out.println("You have given your character too many points! Default values have been assigned: Character, strength: 5, health: 5, luck: 5");


}

}