如何在Java代码中使用“按任意键继续”?

pgccezyw  于 2023-03-16  发布在  Java
关注(0)|答案(5)|浏览(411)

我想让用户在按下键盘上的任意键后,在第一个while循环中再次输入信息。我该如何实现呢?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;
        }
      }
    }

   }
vxbzzdmp

vxbzzdmp1#

你可以创建这个函数(只适用于回车键),并在代码中的任何地方使用它:

private void pressEnterToContinue()
 { 
        System.out.println("Press Enter key to continue...");
        try
        {
            System.in.read();
        }  
        catch(Exception e)
        {}  
 }

如果您使用扫描仪:

private void pressEnterToContinue()
 { 
        System.out.println("Press Enter key to continue...");
        try
        {
            System.in.read();
            scanner.nextLine();
        }  
        catch(Exception e)
        {}  
 }
33qvvth1

33qvvth12#

1)参见while(run1 = true)while(run2 = true)
=是java中的赋值运算符。使用==运算符来比较原语
2)你可以这样做

while(in.hasNext()){

}
bf1o4zei

bf1o4zei3#

我的答案仍然只适用于Enter键,但它不会在输入流上留下可能会妨碍以后的内容(System.in.read()可能会在流上留下下一次输入时读取的内容),所以我读了整行(这里我使用Scanner,但我想这实际上并不必要,你只需要一些东西来去除输入流中的整行):

public void pressEnterKeyToContinue()
{ 
        System.out.println("Press Enter key to continue...");
        Scanner s = new Scanner(System.in);
        s.nextLine();
}
lnvxswe2

lnvxswe24#

在进入实现细节之前,我认为您需要退一步重新检查一下您的算法。根据我收集的信息,您希望从用户那里获得一个整数列表,并确定它们是否构成幻方。您可以在单个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.....
dohp0rv5

dohp0rv55#

https://darkcoding.net/software/non-blocking-console-io-is-not-possible/
转到Linux上的Java非阻塞控制台输入一节。
对于您的代码,您可以将main()数字计算移到一个新函数magicSquare()中,并让它在以下情况下返回false
并修改如下链接的代码

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class test {
    private static String ttyConfig;

/*
returns true if properly exiting, return false if exiting before all numbers were received from input
 */
    public static boolean magicSquare() {

        int nums = 0;

        Square magic = new Square();

        Scanner in = new Scanner(System.in);

        while (nums<2) {
            System.out.print("Enter an integer(x to exit): ");
            if (!in.hasNextInt()) {
                if (in.next().equals("x")) {
                    return false;
                } else {
                    System.out.println("*** Invalid data entry ***");
                }
            } else {
                nums++;
                magic.add(in.nextInt());
            }
        }

        System.out.println();
        if (!magic.isSquare()) {
            System.out.println("Step 1. Numbers do not make a square");
            return true;
        } 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");
            return true;
        } 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!");
        } else {
            System.out.println("Step 3. Yes, it is a MAGIC SQUARE!");
        }
        return true;
    }

    public static void main(String[] args) {
        try {
            setTerminalToCBreak();
            boolean callMagicSquare = true;
            boolean run = true;
            while (run) {
                if (callMagicSquare) {
                    resetTerminal();  // sets console to get input only after enter is pressed
                    run = magicSquare();
                    System.out.println("Press any key except \'x\' to continue");
                    setTerminalToCBreak(); // sets console to read any key press prior
                    callMagicSquare = false;
                }
                
                if (System.in.available() != 0) {
                    int c = System.in.read();
                    if ((char) c == 'x') {
                        break;
                    } else {
                        callMagicSquare = true;
                        continue;
                    }
                }
            } // end while
        } catch (IOException e) {
            System.err.println("IOException");
        } catch (InterruptedException e) {
            System.err.println("InterruptedException");
        } finally {
            resetTerminal();
        }
    }

    private static void resetTerminal() {
        try {
            stty(ttyConfig.trim());
        } catch (Exception e) {
            System.err.println("Exception restoring tty config");
        }
    }

    private static void setTerminalToCBreak() throws IOException, InterruptedException {

        ttyConfig = stty("-g");

        // set the console to be character-buffered instead of line-buffered
        stty("-icanon min 1");

        // disable character echoing
        stty("-echo");
    }

    /**
     * Execute the stty command with the specified arguments
     * against the current active terminal.
     */
    private static String stty(final String args)
            throws IOException, InterruptedException {
        String cmd = "stty " + args + " < /dev/tty";

        return exec(new String[]{
                "sh",
                "-c",
                cmd
        });
    }

    /**
     * Execute the specified command and return the output
     * (both stdout and stderr).
     */
    private static String exec(final String[] cmd)
            throws IOException, InterruptedException {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        Process p = Runtime.getRuntime().exec(cmd);
        int c;
        InputStream in = p.getInputStream();

        while ((c = in.read()) != -1) {
            bout.write(c);
        }

        in = p.getErrorStream();

        while ((c = in.read()) != -1) {
            bout.write(c);
        }

        p.waitFor();

        String result = new String(bout.toByteArray());
        return result;
    }

}

相关问题