可能的选择数量有限?

时间:2019-09-21 14:20:57

标签: java

Java新手在这里。

有这段代码(来自教程),我想知道,应该使用哪种循环或其他方法将最大猜测选择限制为3个? 我的意思是,用户只能猜测有限的次数,并且在该程序停止运行之后。

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int secretNum;
        int guess;
        boolean correct = false;

        Scanner keybord = new Scanner(System.in);
        System.out.print("GIVE ME SECRET NUMBER");
        secretNum = keybord.nextInt();

        while (!correct){
            System.out.println("GUESS: ");
            guess = keybord.nextInt();

            if (guess == secretNum){
                correct = true;
                System.out.println("YOU ARE RIGHT");
            }
            else if (guess < secretNum){
                System.out.println("HIGHER");
            }
            else if (guess > secretNum) System.out.println("LOWER");
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以使用以下计数器来跟踪尝试次数:

public static void main(String[] args) {
    int attempts = 0;
    Scanner keybord = new Scanner(System.in);
    System.out.print("GIVE ME SECRET NUMBER");
    int secretNum = keybord.nextInt();

    while (true){
        System.out.println("GUESS: ");
        int guess = keybord.nextInt();
        attempts++;

        if (guess == secretNum){
            System.out.println("YOU ARE RIGHT");
            break;
        }
        if (attempts == 3) {
            System.out.println("Max attempts!");
            break;
        }
        else if (guess < secretNum){
            System.out.println("HIGHER");
        }
        else if (guess > secretNum) System.out.println("LOWER");
    }
}

答案 1 :(得分:1)

使用干净的代码结构非常容易。在循环外声明一个变量,该变量将存储尝试次数。然后在循环条件中检查尝试次数,并在主体中递增此变量。

app.get('/test', (req, res) => {
  let APIKey = 'Udt4dOLtw4TI7mEhfSZHJ5TbgGC9q7kB';
  let SecretKey = 'HV7bzQrDmUJpVz1UyjWpy2sle9Ly/WYj';
  hitbtc.auth(APIKey, SecretKey);
  let buy = [];
  let sell = [];
  hitbtc.symbols().then(symbols => {
    symbols.forEach((symbol) => {
      let open = [];
      let timeStamp = [];
      let i = 0;
      console.log(symbol.id);
      hitbtc.candles(symbol.id, {limit: 15, period: "H1"}).then(result => {
        result.forEach(element => {
          open.push(element.open);
          timeStamp.push(element.timestamp);
        });
        tulind.indicators.rsi.indicator([open], [14], function (err, results) {
          if (results[0] > 80) {
            console.log("sell : ", symbol.id, " RSI value : ", results[0]);
            sell.push(symbol.id);
          } else if (results[0] < 20) {
            console.log("buy : ", symbol.id, " RSI value : ", results[0]);
            buy.push(symbol.id);
          }
        });
      })
        .catch(e => {
          //console.log(e);
        });
    });
    res.status(200).json({
      success: true,
      buy: buy,
      sell: sell
    })
  });
});

答案 2 :(得分:1)

do-while循环最适合于此。 保证至少执行一次,在循环的末尾而不是在开始时验证循环条件,当您遇到这样的中断条件时,很容易退出任何循环。

int guesses = 0;
final maxGuesses = 3;
final secretNum = ...

do {
    System.out.println("GUESS: ");
        guess = keybord.nextInt();

        if (guess == secretNum){
            System.out.println("YOU ARE RIGHT");
            break; // no need for 'correct' value, just break out of the loop
        }
        else if (guess < secretNum){
            System.out.println("HIGHER");
        }
        else if (guess > secretNum) System.out.println("LOWER");
}while (guesses++ < maxGuesses)

for循环也将起作用。这里,在循环开始之前检查猜测,并在循环结束时进行递增。

for(int guesses = 0; guesses < maxGuesses; guesses++){
    System.out.println("GUESS: ");
     guess = keybord.nextInt();

     if (guess == secretNum){
         System.out.println("YOU ARE RIGHT");
         break;// no need for 'correct' value, just break out of the loop
     }
     else if (guess < secretNum){
         System.out.println("HIGHER");
     }
     else if (guess > secretNum) System.out.println("LOWER");
}