Как мне получить "Нажмите любую клавишу, чтобы продолжить", чтобы работать в моем Java-коде?
Я хочу, чтобы пользователь снова вводил информацию в первый цикл while после нажатия любой клавиши на клавиатуре. Как мне это достичь?
Я делаю что-то неправильно с циклами while. Должен ли я просто иметь один цикл?
import java.util.Scanner;
public class TestMagicSquare
{
public static void main(String[] args)
{
boolean run1 = true;
boolean run2 = true;
Square magic = new Square();
Scanner in = new Scanner(System.in);
while(run1 = true)
{
System.out.print("Enter an integer(x to exit): ");
if(!in.hasNextInt())
{
if(in.next().equals("x"))
{
break;
}
else
{
System.out.println("*** Invalid data entry ***");
}
}
else
{
magic.add(in.nextInt());
}
}
while(run2 = true)
{
System.out.println();
if(!magic.isSquare())
{
System.out.println("Step 1. Numbers do not make a square");
break;
}
else
{
System.out.println("Step 1. Numbers make a square");
}
System.out.println();
if(!magic.isUnique())
{
System.out.println("Step 2. Numbers are not unique");
break;
}
else
{
System.out.println("Step 2. Numbers are unique");
}
System.out.println();
magic.create2DArray();
if(!magic.isMagic())
{
System.out.println("Step 3. But it is NOT a magic square!");
break;
}
else
{
System.out.println("Step 3. Yes, it is a MAGIC SQUARE!");
}
System.out.println();
System.out.print("Press any key to continue...");// Here I want the simulation
in.next();
if(in.next().equals("x"))
{
break;
}
else
{
run1 = true;
}
}
}
}
Ответы
Ответ 1
Вы можете создать эту функцию (полезно только для ввода ключа) и использовать ее там, где вы хотите в своем коде:
private void pressAnyKeyToContinue()
{
System.out.println("Press Enter key to continue...");
try
{
System.in.read();
}
catch(Exception e)
{}
}
Ответ 2
1) См. while(run1 = true)
и while(run2 = true)
= - оператор присваивания в java. use == для сравнения примитивов
2) Вы можете сделать это следующим образом:
while(in.hasNext()){
}
Ответ 3
Прежде чем вдаваться в подробности реализации, я думаю, вам нужно немного отступить и пересмотреть свой алгоритм. Из того, что я собираю, вы хотите получить список целых чисел от пользователя и определить, образуют ли они магический квадрат. Вы можете сделать первый шаг в одном цикле while. Что-то вроде этого псевдокода:
while (true)
print "Enter an integer (x to stop): "
input = text from stdin
if input is 'x'
break
else if input is not an integer
print "non integer value entered, aborting..."
return
else
add input to magic object
После этого вы можете вывести информацию о номерах:
if magic is a magic square
print "this is a magic square"
else
print "this is not a magic square"
// etc, etc.....