Hi i have my basic code done for Triangle area calculating with help of a guide. Then i added little code to make it more fun but i want it to reset after you get the outcome. I want the program to reset to "Enter the triangle's base: " after it has completed previous calculation with valid value. It would be good if it would reset after (x) amout of time.
Simply i want it to press C button in imaginary calculator after the task is done.
Code:
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
public class TriangleArea {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
//declare variables to hold the base and height
double base;
double height;
//Variables created. move on
System.out.print("Enter the triangle's base: ");
base = sc.nextDouble();
//Base has been declared and filled in
System.out.print("Enter the triangle's height: ");
height = sc.nextDouble();
//Both variables are filled in
double preArea = base * height;
//now we need to divide by 2
double Area = preArea / 2;
//There we go. All variables are done, area has been calculated.
System.out.println("The area of your triangle is: " + Area);
int Outcome;
if (Area <= 100) {
System.out.println("Triangle's area is small");
}
if (Area <= 300) {
System.out.println("Triangles size is medium");
}
if (Area >= 300) {
System.out.println("Triangle's area is big");
}
else {
}
}
}
You want to use a while loop that exits e.g., by having the user enter '0' as an exit code. You can use a boolean
that is initialized to true and gets set to false when the user enters the exit code.
import java.util.Scanner;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
boolean repeat = true;
while (repeat) {
// declare variables to hold the base and height
double base;
double height;
// Variables created. move on
System.out.print("Enter the triangle's base (enter 0 to exit): ");
base = sc.nextDouble();
if (base == 0) {
repeat = false;
break;
}
// Base has been declared and filled in
System.out.print("Enter the triangle's height (enter 0 to exit): ");
height = sc.nextDouble();
if (height == 0) {
repeat = false;
break;
}
// Both variables are filled in
double preArea = base * height;
// now we need to divide by 2
double Area = preArea / 2;
// There we go. All variables are done, area has been calculated.
System.out.println("The area of your triangle is: " + Area);
if (Area <= 100) {
System.out.println("Triangle's area is small");
}
if (Area <= 300) {
System.out.println("Triangles size is medium");
}
if (Area >= 300) {
System.out.println("Triangle's area is big");
}
else {
}
}
System.out.println("Bye bye");
}
}