2014-11-05 3 views
1

Я пробую свою руку на Java и официально не был обучен. Я где-то взял задание из курса и подумал, что просто попробую. Все идет хорошо до сих пор, за исключением того, что мне нужно, чтобы пользователь внес вклад, который является выбором из данного списка. У меня нет проблем со значениями String, но у них также есть возможность выбрать число из 0-39, которое я хотел бы сохранить как int.Пользовательский ввод из данного списка с сочетанием String и Int

Любая помощь будет оценена по достоинству.

import java.util.Scanner; 

public class RouletteGame { 

    static Player p1; 
    public static void main(String[] args){ 

     Scanner scan = new Scanner(System.in); 
     int num = (int)(Math.random()*37); 
     int winnings = 0; 
     int x = 0; 
     int counter = 1; 
     int p = 1; 
     String name; 
     String choice; 
     int iAmount = 100; 
     int betNum; 

     System.out.println("Welcome to Cache Creek style Rouylette..bet an amount and type"); 
     System.out.println(" if you select the correct colour, you win double your bet"); 
     System.out.println(" if you select the correct odd/even, you win double your bet"); 
     System.out.println(" if you select the correct number, you win 40 times your bet"); 
     System.out.println(" otherwise you lose your bet"); 
     System.out.println("If you lose all your money, the game is over"); 
     System.out.println(); 
     System.out.print("How much do you want to bet? $"); 
     int bet=scan.nextInt(); 

     while (x==0){ 
      Scanner scann = new Scanner(System.in); 
      System.out.println("What is your bet? (odd/even/red/black/exact number)"); 
      choice=scann.nextLine(); 
      } 

      if (choice.equals("odd")){ 
       System.out.println("You have selected odd."); 
       x=1; 
       } 
       else if (choice.equals("even")){ 
         System.out.println("You have selected even."); 
         x=1; 
       } 
       else if (choice.equals("red")){ 
         System.out.println("You have selected red."); 
         x=1; 
       } 
       else if (choice.equals("black")){ 
         System.out.println("You have selected black."); 
         x=1; 
       } 
       else if (choice.equals(int)){ 
        betNum = Integer.parseInt(choice); 
        System.out.println("You have selected " +betNum); 
        x=1; 
      } 
       else{ 
        System.out.println("Invalid value: Must be odd, even, red, black or a number between 0 and 39"); 
        x=0; 
      } 
     } 
    } 
} 
+0

возможный дубликат [Определить, является ли String целым в Java] (http://stackoverflow.com/questions/5439529/determine-if-a-string-is-an-integer-in-java) – vefthym

+0

use Integer.parseInt (String_input); для преобразования String в int –

+0

@KrsnaChaitanya он уже делает это. Проблема в строке 'else if (choice.equals (int)) {' – vefthym

ответ

0

Проблема в том, что вы не знаете, является ли данный ответ строкой или целым.

Эта линия не будет компилироваться:

else if (choice.equals(int)) {

Вместо этого создайте новый метод isInteger(String s), как this one и вызвать его на месте линии выше, как и что:

else if (isInteger(choice)) { 
    betNum = Integer.parseInt(choice); 
    if (betNum >= 0 && betNum <=39) { 
     System.out.println("You have selected " +betNum); 
     x = 1; //by the way, you can set x to be a boolean variable 
    } else { //betNum not a valid Roulete number 
     System.out.println("Invalid value: Must be odd, even, red, black or a number between 0 and 39"); 
     x=0; 
    } 
} 
+0

они x = 1 только для цикла ... кажется, он делает то, что я хочу, чтобы он делал. – Scholarmate

+0

ваш ответ имеет смысл, но когда я запускаю, он не возвращает значение betNum в println – Scholarmate

+0

, возможно, вы не видели мое обновление, и вы дали значение < 0 or > 39? Что он печатает? – vefthym

Смежные вопросы