#java #for-loop #if-statement #while-loop #do-loops
#java #для цикла #if-оператор #цикл while #циклы выполнения
Вопрос:
Я только начал изучать Java-коды, поэтому у меня может возникнуть простой вопрос, который для меня не прост.
Я хотел бы указать необязательный «неправильный номер. Попробуйте еще раз «при вводе номера, отличного от secretNum. Ребята, можете ли вы помочь мне с этим кодом?
// Мне нужно узнать, как ставить «попробуйте еще раз», когда число равно!=, чем угадывать число.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if(sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " userName ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well donen");
System.out.println("Are you ready for the next step?n");
}
// I need learn how put "try again" when the number is != than guess number.
/* I have tried
* 1)Change the signal "==" or "!=".
* 2) do {
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
} while(secretNum != guess);{
System.out.println("Well done");
System.out.println();
System.out.println("Are you ready for the next step?");
System.out.println();
}
*/
System.out.println("Enter Yes or No");
while(!sc.next().equals("yes")amp;amp; !sc.next().equals("no"));{
System.out.print("Yes");
}
do {
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt ();
}
}while(secretNum2 != guess);{
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}
}
````````
Комментарии:
1. ПОДСКАЗКА:
if
оператор.
Ответ №1:
Вам не нужно do{} while()
для проверок, которые вы хотите выполнить здесь, достаточно просто while(){}
циклов.
Пожалуйста, попробуйте этот код вместо:
import java.util.Scanner;
public class GuessNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
if (sc.hasNextLine()) {
String userName = sc.nextLine();
System.out.println("Hello " userName ",");
System.out.println();
}
int secretNum = 5;
int secretNum2 = 15;
int guess = 0;
System.out.println("Guess what is the number 0 to 10: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum != guess) {
System.out.println("Please try againn");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Well donen");
System.out.println("Are you ready for the next step?n");
System.out.println("Enter Yes or No");
while (!sc.next().equals("yes") amp;amp; !sc.next().equals("no"))
{
System.out.print("Yes");
}
System.out.println("Guess what is the number 11 to 20: ");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
while (secretNum2 != guess) {
System.out.println("Please try againn");
if (sc.hasNextInt()) {
guess = sc.nextInt();
}
}
System.out.println("Congratulations");
System.out.println();
System.out.println("The End");
}
}
Комментарии:
1. Я думаю, что циклы do-while были лучшим выбором; они более краткие и существуют для такого типа ситуаций. Также все еще есть несколько проблем со строкой
while (!sc.next().equals("yes") amp;amp; !sc.next().equals("no"))
. Хотя это не тот раздел, о котором он спрашивал, я оставлю инструкцию для OP.2. Да, циклы do-while тоже будут работать, я просто сказал, что вам это не нужно в этой ситуации, что
while (!sc.next().equals("yes") amp;amp; !sc.next().equals("no"))
фрагмент кода не входит в сферу его вопроса, вот почему я его не рассматривал…3. @AdrianoMarra спасибо за ответ. Это сработало. Это мне очень помогло. Я пока мало что знаю о коде. Итак, у меня все еще есть основные вопросы.
4. @EdgarSousa добро пожаловать и продолжайте в том же духе, нет основных вопросов, которые все где-то начинали… Счастливый программист! 🙂