I'm self learning Java for a few weeks and started testing my (basic) knowledge. I was trying to create something like some formula calculator, with an index selector. I want to know if it's possible to, after using a formula, go back to the first question. I tried to use a while loop, but I couldn't figure it out.
public class formulas {
public static void main(String[] args) {
// TODO Auto-generated method stub
// first question
// constant values definition
final double PI = 3.141592653589793238;
//index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("2. Triangle Area");
System.out.println("Formulas Index:");
System.out.println("");
for(int i=0; i<index.size(); i++) {
System.out.println(index.get(i));
}
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
Scanner scanner = new Scanner(System.in);
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a,b);
System.out.println("Hypotenuse c: "+ c);
}
else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA,arestaB);
System.out.println("The square area is: "+ squareArea);
}
else System.out.println("Please insert a valid formula number.");
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a*a)+(b*b));
return c;
}
static double squarearea(double a, double b) {
double area = a*b;
return area;
}
}
I'm always surprised that people don't make more use of do-while loops, it's a severely underrated construct.
Think about it, you MUST do at least one iteration of the loop before you know if you want to continue or exit the loop. You also want to re-print the menu on each iteration, so it's easier to just put it in a do-while (IMHO)
You can take a look at Control Flow Statements and The while and do-while Statements for more details
import java.util.ArrayList;
import java.util.Scanner;
public final class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// first question
// constant values definition
final double PI = 3.141592653589793238;
//index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("3. Triangle Area");
index.add("4. Quit");
Scanner scanner = new Scanner(System.in);
boolean printMenu = true;
boolean exit = false;
do {
if (printMenu) {
System.out.println("");
System.out.println("Formulas Index:");
System.out.println("");
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i));
}
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
}
printMenu = true;
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a, b);
System.out.println("Hypotenuse c: " + c);
} else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA, arestaB);
System.out.println("The square area is: " + squareArea);
} else if (firstQuestion.equals("3")) {
// Triangle area
} else if (firstQuestion.equals("4")) {
exit = true;
} else {
printMenu = false;
System.out.println("Please insert a valid formula number.");
}
} while (!exit);
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a * a) + (b * b));
return c;
}
static double squarearea(double a, double b) {
double area = a * b;
return area;
}
}
You can simply wrap your code starting from firstQuestion variable declaration till the end of the if condition in a while loop which is always set to true.
public class Formulas {
public static void main(String[] args) {
// first question
// constant values definition
final double PI = 3.141592653589793238;
// index
ArrayList<String> index = new ArrayList<>();
index.add("1. Pythagorean Theorem");
index.add("2. Square Area");
index.add("2. Triangle Area");
System.out.println("Formulas Index:");
System.out.println("");
for (int i = 0; i < index.size(); i++) {
System.out.println(index.get(i));
}
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("");
System.out.print("Write the formulas number you want to use: ");
String firstQuestion = scanner.nextLine();
System.out.println();
// methods selection
if (firstQuestion.equals("1")) {
System.out.println("Pythagoras Theorem");
System.out.print("Insert side a: ");
double a = scanner.nextDouble();
System.out.print("Insert side b: ");
double b = scanner.nextDouble();
double c = pitagoras(a, b);
System.out.println("Hypotenuse c: " + c);
} else if (firstQuestion.equals("2")) {
System.out.println("Square area");
System.out.print("Insert side a: ");
double arestaA = scanner.nextDouble();
System.out.print("Insert side b: ");
double arestaB = scanner.nextDouble();
double squareArea = squarearea(arestaA, arestaB);
System.out.println("The square area is: " + squareArea);
} else
System.out.println("Please insert a valid formula number.");
}
}
// methods parameters
static double pitagoras(double a, double b) {
double c = Math.sqrt((a * a) + (b * b));
return c;
}
static double squarearea(double a, double b) {
double area = a * b;
return area;
}
}
Related
I'm new to Java. I am tasked with creating a menu program, one option is to generate a username in the form of first initial and surname.
The method is stringOperation(String f, String s)
Variables are fName and sName.
Here is the code. I have highlighted the areas I need help with. The rest of the code is OK, I think. This is a section of the pseudocode that explains what is required:
stringOperation(String f, String s)
3.1.1 Assign first character of first initial to variable using f.substring(start position, length of string).
3.1.2 Concatenate first initial with users surname.
3.1.3 print username to console.
import java.util.Scanner; // imports scanner class
public class Assessment {
public static void main(String[] args) { //main method
menu(); //call menu method
}
public static void menu() { //method to display menu options
int choice;
String fName;
String sName;
Scanner sc = new Scanner(System.in);
//displays menu options
System.out.println("Welcome");
System.out.println("1. Username");
System.out.println("2. Factorial");
System.out.println("3. Area of triangle");
System.out.println("4. Circumference of circle");
System.out.println("5. Exit");
//asks for user input
do {
System.out.println("Enter your first name");
fName = sc.next();
System.out.println("Enter your surname");
sName = sc.next();
System.out.println("Thank you. Now enter a selection (1-5):");
choice = sc.nextInt();
//menu loop
switch (choice) {
case 1:
**stringOperation(String fName, String sName);**
break;
case 2:
numberFactorial();
break;
case 3:
areaTriangle();
break;
case 4:
circumferenceCircle();
break;
}
}while (choice!=5);
}
**//stringOperation method
private static void stringOperation(String f, String s) {
String initial = f.substring(0,1);
String username = initial + s;
System.out.println("Your username is " + initial + s);
}**
public static void numberFactorial() { //method to calculate factorial of a number
//variables
int number;
int factorial = 1;
int i;
//input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = sc.nextInt();
//for loop
for (i = 1; i <= number; i++) {
factorial = factorial * i;
}
System.out.println("Factorial of " + number + " is " + factorial);
}
public static void areaTriangle ()//method to calculate area of a triangle
{ //input
Scanner sc = new Scanner(System.in);
//variables
double width;
double height;
double area;
//input
System.out.println("Enter the width: ");
width = sc.nextInt();
System.out.println("Enter height: ");
height = sc.nextInt();
area = (height * width) / 2;
System.out.println("The area is :" + area);
}
public static void circumferenceCircle ()//method to calculate circumference of a circle
{ //variables
double radius;
double circumference;
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius: ");
radius = sc.nextDouble();
circumference = Math.PI * 2 * radius;
System.out.println("The circumference is : " + circumference);
}
}
If you want to make the method cleaner you could do something like this
private static void stringOperation(String f, String s) {
System.out.println("Your username is " + f.substring(0,1) + s)
}
If you need to refer back to the new username then have a global variable that your method can set to refer to later like this.
private static void stringOperation(String f, String s) {
Assessment.username = f.substring(0,1) + s;
System.out.println("Your username is " + Assessment.username);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter circle area");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
double circleArea = RadiusSquared * Math.PI;
return circleArea;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length");
length = scanner.nextDouble();
System.out.print("Enter rectangle width");
width = scanner.nextDouble();
double rectangleArea = length * width;
return rectangleArea;
}
public double getTriangleArea( double base, double height ) {
System.out.println("enter triangle base");
base = scanner.nextDouble();
System.out.println("enter triangle height");
height = scanner.nextDouble();
double triangleArea = (base* height)/2;
return triangleArea;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n" + "9. Exit");
userNum = scanner.nextInt();
if (userNum == 1){
System.out.println(getCircleArea(userNum));
}
else if (userNum == 2){
System.out.println(getRectangleArea(userNum,secNum));
}
else if (userNum == 3){
System.out.println(getTriangleArea(userNum,secNum));
}
else if (userNum == 9){
}
}
}
}
So I wanted it to only be able to put these 4 numbers but I am not sure if this is better than just a while loop, which I think I know how to do. Also what do you think about the actual geometry?
You can try the below code and figure out what's problematic in your code.
import java.util.Scanner;
public class Geometry {
private Scanner scanner;
public double getCircleArea( double radius ) {
System.out.print("Enter radius of circle to find area: ");
radius = scanner.nextDouble();
double RadiusSquared = Math.pow(radius, 2);
return RadiusSquared * Math.PI;
}
public double getRectangleArea( double length, double width ) {
System.out.print("Enter rectangle Length: ");
length = scanner.nextDouble();
System.out.print("Enter rectangle width: ");
width = scanner.nextDouble();
return length * width;
}
public double getTriangleArea( double base, double height ) {
System.out.print("enter triangle base: ");
base = scanner.nextDouble();
System.out.print("enter triangle height: ");
height = scanner.nextDouble();
return (base*height)/2;
}
public static void main( String[] args ) {
new Geometry().go();
}
private void go() {
scanner = new Scanner(System.in);
// main processing logic including input and output goes here.
int userNum = 0;
int secNum = 0;
while (userNum <= 0) {
System.out.println("1. Area of circle\n" + "2. Area of rectangle\n" + "3. Area of triangle\n");
System.out.print("choose a number: ");
userNum = scanner.nextInt();
if (userNum == 1) { System.out.println("Area of circle is " + getCircleArea(userNum)); }
else if (userNum == 2){ System.out.println("Area of rectangle is " + getRectangleArea(userNum,secNum)); }
else if (userNum == 3){ System.out.println("Area of triangle is " + getTriangleArea(userNum,secNum)); }
else System.exit(0);
}
}
}
It's depending on what your needs.
If you want to always display the menu selection bar once after user got the area, while is a must.
If not, just use Map to map each user's selection as to avoid bunches of if else block
//THIS IS FOR OPTION2
//no need the parameter, radius is depending input in the method scope
public double getCircleArea() {//...}
//...
public static void main( String[] args ) {
Map<Integer, Func> map = new HashMap();
map.put(num1, () -> getCircleArea());
//map.put(num2, xxx()) etc
new Geometry().go();
}
private void go() {
//...
map.get(userNum)
}
interface Func{
void execute();
}
(ps, from the code, seen scanner.nextDouble(), scanner.nextInt() to get from input of scanner. I think it is an alert when using different API to maintain the same functionality.
Because it violates encapsulation principle. java.util.Scanner already has the javadoc to interpret these, thus you should check from your side.
)
I was wondering if someone could tell me
1. why, when i input weightNumber with a decimal place, weightConverted doesn't convert it to the whole number, even though I create variable for it?
2. how could i improve this "program" in any way, THANK YOU !!
here is the problem:
code:
import java.util.Scanner;
public class cofee {
public static void main (String []args){
double weightNumber = 0;
String packageType = "";
String serviceType ="";
double totalFee = 0;
double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else?
final double LETTERCOSTP = 12.00;
final double LETTERCOSTS = 10.50;
final double BOXCOSTP = 15.75;
final double BOXCOSTS = 13.75;
final double BOXWEIGHTP = 1.25;
final double BOXWEIGHTS = 1.00;
// input
Scanner input = new Scanner(System.in);
System.out.print("Enter package type (letter/box): ");
packageType = input.nextLine().toLowerCase();
System.out.print("Enter type of service (standard/priority): ");
serviceType = input.nextLine().toLowerCase();
switch(packageType)
{
case "letter":
System.out.print("Enter the weight in ounces: ");
weightNumber = input.nextDouble();
break;
case "box":
System.out.print("Enter the weight in pounds: ");
weightNumber = input.nextDouble();
break;
default:
System.out.print("WRONG PACKAGE TYPE !!!");
}
// letter
if (packageType.equals("letter") && serviceType.equals("priority"))
{
totalFee = LETTERCOSTP;
}
if (packageType.equals("letter") && serviceType.equals("standard"))
{
totalFee = LETTERCOSTS;
}
// box
if (packageType.equals("box") && serviceType.equals("priority"))
{
totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP);
}
if (packageType.equals("box") && serviceType.equals("standard"))
{
totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS);
}
// display
System.out.println("The fee is € "+ totalFee + " for a package with");
System.out.println("\tType: "+packageType);
System.out.println("\tService: "+serviceType);
System.out.println("\tOunces: "+weightConverted);
}
}
The line double weightConverted = Math.round(weightNumber); will call round() with the value of weightNumber, which is 0, so it rounds 0 to... well... 0, and assigns it to weightConverted.
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pi = 3.142;
double T, v, a, x, r;
System.out.println("3.Centrifuge. The rotor of an ultracentrifuge rotates at x rev/s.");
System.out.println("A particle at the top of the test tube is r meter from the rotation axis.");
System.out.println("Calculate it’s centripetal acceleration.");
System.out.printf("Enter the number of rotation in rev/s : ");
x = input.nextInt();
System.out.printf("Enter the distance in meter : ");
r = input.nextInt();
T = 1/x;
v = (2*pi*r)/T;
a = (v*v)/r;
System.out.println("\n\nAnswer");
System.out.printf("The centripetal acceleration is : %.2f m/s^2\n", a);
}
}
Hi all. This is my coding and it cannot run when I put decimal point. how to fix it?
Replace input.nextInt(); with input.nextDouble();
x = input.nextInt(); // It will simply ignore decimal values
Hence you need to use nextDouble()
x = input.nextDouble(); // This will read the entire decimal value
You read a int with
input.nextInt();
Try
input.nextDouble();
Try it.
import java.util.Scanner;
public class JavaScannerDouble {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String data = input.next();
double decimalValue = Double.parseDouble(data);
System.out.println("Decimal value : " + decimalValue);
// test of decimal value
double response = decimalValue / 0.1;
System.out.println("response : " + response);
}
}
I'm trying to build an app which computes the area of a triangle, as per my homework assignment. Not quite sure where I'm going wrong, but I input the lengths of the triangle and would like the proper area displayed according to Heron's formula: sqrt (s(s-a) (s-b) (s-c)). All I'm getting for output is -0.0. Here is the code:
import java.lang.Math;
public class Formula
{
double area; double s;
public double findArea(double sideA, double sideB, double sideC)
{
s = 1/2 * (sideA + sideB + sideC);
area = Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC));
System.out.println("The area of the triangle is " + area);
return area;
}
}
And then I have another file for the main args
import java.util.Scanner;
public class findTriangleArea {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Formula triangle = new Formula();
double a,b,c;
// input triangle lengths a, b, c
Scanner inputTriangle = new Scanner(System.in);
System.out.println("Please enter triangle side a");
a = inputTriangle.nextDouble();
System.out.println("Please enter triangle side b");
b = inputTriangle.nextDouble();
System.out.println("Please enter triangle side c");
c = inputTriangle.nextDouble();
triangle.findArea(a, b, c);
}
}
1/2 is being computed in integer arithmetic, so like with all integer division, it's truncated -- in this case, to 0. Just write 0.5 and you'll be fine.
public class AreaOfTriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the height: ");
double height=scanner.nextDouble();
System.out.print("Enter the base: ");
double base=scanner.nextDouble();
scanner.close();
double area=(base*height)/2;
System.out.println("---------------------------");
System.out.println("Area of Triangle is: "+area);
}
}
Heron's Formula:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a, b, c;
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
double p = (a + b + c) / 2;
System.out.println(Math.sqrt(p * (p - a) * (p - b) * (p - c)));
}