如何在输入后让程序提问? [英] How do I get the program to ask questions after input?

查看:89
本文介绍了如何在输入后让程序提问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过,主要是为了制作一个简单的计算器类型程序的问题。当它运行时,最后3个句子将打印出来而不让用户输入任何内容。如何使程序在输入后只询问问题?

感谢您提前提供任何帮助。



我尝试过的事情:



I've tried, mainly for the purpose of this question of making a simple "calculator" type program. When it runs the last 3 sentences will print out without letting the user enter anything. How do I make the program only ask a question after input?
Thanks for any help in advance.

What I have tried:

import java.util.Scanner;
public class hello1{
public static void main(String[]args)
{

 Scanner scan = new Scanner(System.in);
 String s1 ="";
 int num1=0;
 int square=0;

    do
    {
    	System.out.println("Please enter a number between 1 and 20");
    	num1 = scan.nextInt();
    	System.out.println("Do you want to square this number?");
    	String s2 = scan.nextLine();
    	if(s2.equalsIgnoreCase("Yes"))
    	{
    		square = num1*num1;
    		System.out.println("The square is " + square);
    	}
    	else
    	{
    		System.out.println("No square");
    	}

        System.out.println("Do you want to continue? Y/N");//Print
        s1 =scan.nextLine();//Read

    }

    while(s1.equalsIgnoreCase("Y"));
}
}

推荐答案

只需在代码中添加额外的行,如下所示:

Just add the extra line in your code as shown:
System.out.println("Please enter a number between 1 and 20");
num1 = scan.nextInt();
scan.nextLine(); // add this line to consume the newline character
System.out.println("Do you want to square this number?");


使用调试器,您将看到 num1 s2 s1 在运行时包含。



你应该学习使用调试器尽快。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。

调试器 - 维基百科,免费的百科全书 [ ^ ]

http://docs.oracle.com/ javase / 7 / docs / technotes / tools / windows / jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。

如果代码没有达到预期的效果,那么您就接近了一个bug。
With the debugger, you will see exactly what num1, s2 and s1 contain at runtime.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.


这篇关于如何在输入后让程序提问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆