如何在循环中验证正确范围内的值?

时间:2018-10-04 18:10:44

标签: java loops for-loop while-loop do-while

我有一个问题:如何验证输入的值是否在正确的范围内,并要求用户重新输入选择?我已经有下面列出的代码,但是它一直循环播放。例如,如果玩家1输入6,它应该说不正确,然后重新输入正确的数字,而当玩家1输入介于1和5之间的数字时,它继续进入玩家2并重复。我的问题是我使用的循环不允许我这样做,而是将我的打印语句循环了5次。

from functools import partial
from multiprocessing import Pool

def pool_map_fn(value=None, constante=None, i=None):
    s = {'val': value[i:i+constante]}
    window = pd.concat([s['val']['Date'],s['val']['Price']], axis=1)
    window['Price'] = pd.to_numeric(window['Price'], errors='coerce').fillna(0)
    calc = window['Price'].mean()                                        
    date_variable = window['Date'].iloc[-1]
    price_var = window['Price'].iloc[-1]
    if price_var < calc:
        print('Parameter',constante,'Lower than average',date_variable,price_var,calc)  
        portfolio = portfolio.append({'Parameter': constante,
                                      'Date': date_variable, 
                                      'Price': price_var,
                                      'Calculation': calc}, ignore_index=True)
    if price_var > calc:
        print('Parameter',constante,'Higher than average',date_variable,price_var,calc)

parameters = range(300,550,50)
portfolio = pd.DataFrame(columns=['Parameter','Date','Price','Calculation'])
for key, value in sorted(d.items()):
    for constante in parameters:
        with Pool() as pool:
            results = pool.map(partial(pool_map_fn, value=value, constante=constante),
                               range(len(value) - constante + 1))

enter image description here

enter image description here

我要感谢帮助我清理代码的人。我遇到一个问题,如果输入数字1,该代码将再次打印无效,然后尝试...好吧,您可以在下面的图片中看到。如果我输入1,则应继续要求玩家2输入数字。

    import java.util.Scanner;
    import java.util.Random;
    public class Moropinzee
    {
       public class void main(String[] args)
       {
       String personPlay;
       int computerInt;
       String response; 


        int Monkey = 1;
        int Robot = 2;
        int Pirate = 3;
        int Ninja = 4;
        int Zombie = 5;
        Scanner scan = new Scanner(System.in);
        Random generator = new Random(); 

        System.out.print("Hey, let's play Moropinzee!\n" + 
                       "Please enter a move.\n");

        System.out.println("Player 1: Enter a number 1-5 for Monkey, Robot, Pirate, Ninja, or Zombie:");
        String player1 = scan.next().toUpperCase();


        System.out.println("Player 2: Enter a number 1-5 for Monkey, Robot, Pirate, Ninja, or Zombie");
        String player2 = scan.next().toUpperCase();

        System.out.println();



      for(int number = 0; number < 5; number++)
      {
      System.out.println("Invaild choice, Player 1. Enter a number 1-5:");
      }
    }
  }

3 个答案:

答案 0 :(得分:0)

我觉得在这里使用while循环会更有益。另外,您在最后一个打印行中拼写了“无效”。尝试使用类似while的while循环:

// used to print invalid command if input other than those stated is 
    used.
while (!playerOne.equalsIgnoreCase("1") && 
    !playerOne.equalsIgnoreCase("2")) {
    System.out.println(invalidCommand);
    playerOne = scan.nextLine();
}

尝试对每个将被接受的输入使用此命令(我只做过1和2),并创建一个名为invalidCommand的变量,它将告诉用户尝试有效的输入!

答案 1 :(得分:0)

用以下代码替换您的代码:

import java.util.Scanner;
import java.util.Random;
class Moropinzee
{
   public static void main(String[] args)
   {
    String personPlay;
    int computerInt;
    String response; 


    int Monkey = 1;
    int Robot = 2;
    int Pirate = 3;
    int Ninja = 4;
    int Zombie = 5;
    int player1 = 0;
    int player2 = 0;
    Scanner scan = new Scanner(System.in);
    Random generator = new Random(); 

    System.out.print("Hey, let's play Moropinzee!\n" + "Please enter a move.\n");
    while(!(player1>0) || !(player1<6)) {
        System.out.println("Player 1: Enter a number 1-5 for Monkey, Robot, Pirate, Ninja, or Zombie:");
        player1 = scan.nextInt();
    }


    while(!(player2>0) || !(player2<6)){
        System.out.println("Player 2: Enter a number 1-5 for Monkey, Robot, Pirate, Ninja, or Zombie:");
        player2 = scan.nextInt();
    }

//...........true..............
    System.out.println();
   }
}

请注意,我已将变量player1player2更改为int。 因此,请相应地更改以获取更多代码。

答案 2 :(得分:0)

尝试一下...如果您不明白该问什么。

public static void main(String[] args) {
    int[] playerChoice = new int[5]; // 5 players
    try (Scanner scan = new Scanner(System.in)) {  //in try resource so it is closed when no longer needed.
        for (int i = 0; i < playerChoice.length; i++) { //loop over the players
            System.out.println("Player " + (i + 1));
            int intInput;
            try {
                intInput = scan.nextInt();//get the input in int
            } catch (InputMismatchException ime) { // input was not int
                intInput = 0;//assign bad number
            }
            if (intInput < 1 || intInput > 5) { //test
                System.out.println("Invalid input.");
                i--;//retry
            }
        }
    }
}