如果问题的答案是错误的,如何停止程序



我收到一个提示,要用java编写一个程序,询问用户三角形的底和高。然后程序应该找到该区域。我启动程序询问用户是否愿意帮助我;是";则程序继续。如果他们说的不是";是";我希望程序停止。我不知道如何让它回复用户,然后停止运行。我的代码在下面。如果你有时间复习全部内容,那就太棒了!我是个新手。

public static void main(String[] args) {
System.out.println("Hey can you help me practice finding the area of a triangle?");
String answerFirstQuestion = "Yes";
//if (answerFirstQuestion = Yes){
//}else{
// System.exit(0);
//}
//^^This part isn't apart of the prompt. I wanted to ask the user a question, then have them answer "Yes". If they entered anything other than that, I wanted the program to print "Oh ok, that's fine. Thanks anyways." then stop. Could I get some feedback on how to accomplish this.
switch (answerFirstQuestion) {
case "Yes":
System.out.println("Thanks kid!nJust give me a random base and height for our imaginary triangle.nI'll then use the equation b*h/2 to see if my program can find the area.");
break;
default: 
System.out.println("Oh ok, that's fine.nThanks anyways.");
}
int base;
base = 6;
int height;
height = 12;
int area = base*height/2;
area = base*height/2;    
System.out.println("The base of the triangle is? " + base);
System.out.println("The height of the triangle is? " + height);
System.out.println("Area of Triangle is: " + area);
System.out.println("Cool I guess it works, thanks again!");
}
}

java.lang.System.exit((方法通过终止运行java虚拟机来退出当前程序
以下示例显示了java.lang.System.exit((方法的用法。

// A Java program to demonstrate working of exit()
import java.util.*;
import java.lang.*;

class GfG
{
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

for (int i = 0; i < arr.length; i++)
{
if (arr[i] >= 5)
{
System.out.println("exit...");

// Terminate JVM
System.exit(0);
}
else
System.out.println("arr["+i+"] = " +
arr[i]);
}
System.out.println("End of Program");
}
}

我希望这对你有所帮助:(。

返回即可。

System.out.println("Hey can you help me practice finding the area of a triangle?");
String answerFirstQuestion = "Yes";
switch (answerFirstQuestion) {
case "Yes":
System.out.println("Thanks kid!nJust give me a random base and height for our imaginary triangle.nI'll then use the equation b*h/2 to see if my program can find the area.");
break;
default: 
System.out.println("Oh ok, that's fine.nThanks anyways.");
return;   
// Return from the main function. The code below this will NOT be executed
}

最新更新