繁体   English   中英

在扫描仪收到输入之前,如何停止下一个println的显示?

[英]How do I stop the next println from appearing before my scanner has received input?

我正在构建一个程序,向用户询问有关房屋(号码,街道等)的一些问题,稍后我将这些输入分配给字符串和整数。 现在我的问题是我想问7/8个问题,但是我希望下一个问题仅在用户为上一个问题提供输入后才出现。 以下是部分代码:

        int choice = sc.nextInt();
        sc.useDelimiter("\\n");

        switch(choice){

        case 1:
            System.out.println("Geef antwoord op onderstaande vragen  en druk op ENTER na elk antwoord: ");
            System.out.println();
            System.out.println("Is de koopwoning TE KOOP of VERKOCHT? Voer een van die twee opties in: ");
            System.out.println("Voer de straatnaam van de woning in: ");
            System.out.println("Voer het huisnummer in: ");
            System.out.println("Voer de postcode in: ");
            System.out.println("Voer de plaats in: ");
            System.out.println("Voer het aantal kamers in: ");
            System.out.println("Voer de vraagprijs/koopprijs in: ");
            System.out.println("Voer het energiepeil in: ");

            String kwstate = sc.next();
            String kwstr = sc.next();
            String kwnr = sc.next(); Integer.parseInt(kwnr);
            String kwpc = sc.next();
            String kwpl = sc.next();
            int kwkamers = sc.nextInt();
            int kwprijs = sc.nextInt();
            String energie = sc.next();

如何使用此代码执行此操作? 当我运行它时,它显然会显示所有查询,最重要的是,当我键入内容时,输入不会出现在问题旁边,而是出现在所有问题下方。 println对此负责,但是仅使用print可以将所有问题在命令窗口中的一行上紧挨着。 希望我有道理。 有任何想法吗?

将每个“ scan”语句直接放在您要回答的问题之后,如下所示:

System.out.println("Is de koopwoning TE KOOP of VERKOCHT? Voer een van die twee opties in: ");
String kwstate = sc.next();
System.out.println("Voer de straatnaam van de woning in: ");
String kwstr = sc.next();
System.out.println("Voer het huisnummer in: ");
String kwnr = sc.next(); 
//...

附带说明,您没有保存Integer.parseInt(kwnr);的结果Integer.parseInt(kwnr); 如果不将结果保存为int值,例如int kwnrInt = Integer.parseInt(kwnr); 结果将丢失。

只需将sc.next放在println语句之后。

System.out.println("Question");
String answer = sc.nextLine();
System.out.println("Second Question");

像那样。

然后以Q&A形式进行。

下面的代码只是为了展示基本逻辑:

System.out.print("Provide an integer here: ");
if sc.hasNextInt() {sc.nextInt()}
else {System.out.println("Didn't I tell you to enter integer???");}

如果您使用的是Windows,则无法使用:

sc.useDelimiter("\\n");

Windows在每行之间使用两个字符"\\\\r\\\\n" ,从我的测试看来, Scanner会看到"\\\\r"并将其混淆。 这样效果更好:

sc.useDelimiter("\\r?\\n");

它将"\\\\n""\\\\r\\\\n"视为定界符。 如果仍然遇到InputMismatchException ,这可能会解决该问题。 (表达系统相关的换行符可能是更好的方法。最好不要使用换行符作为分隔符,而应使用sc.nextLine()处理下一行以及当前行中所有未使用的字符。 ,或使用其他某种机制。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM