write a java program on a scientific calculator
- User
write a java program on a scientific calculator
- Assistant
- User
what is wrong with this code package calculator;
import java.util.Scanner;
public class ScientificOperations {
/** * * @param args */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the base: "); double base = scanner.nextInt(); System.out.print("Enter the power: "); double power= scanner.nextInt(); System.out.print("Enter a number: "); double number = scanner.nextInt(); if (number >= 0) { double squareRoot = Math.sqrt(number); System.out.println("Result: " + squareRoot); } else { System.out.println("Invalid"); } }}
- Assistant
The code you provided has a couple of issues:
-
Package Declaration: The package declaration
package calculator;should be the first line in the code before the class declaration. -
Incorrect Data Types: You are using
scanner.nextInt()to read the input values, which assumes the input will be integers. However, in themainmethod, you are attempting to read and store decimal numbers (double). To resolve this issue, you should usescanner.nextDouble().
Here's the corrected code:
package calculator; import java.util.Scanner; public class ScientificOperations { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the base: "); double base = scanner.nextDouble(); System.out.print("Enter the power: "); double power = scanner.nextDouble(); System.out.print("Enter a number: "); double number = scanner.nextDouble(); if (number >= 0) { double squareRoot = Math.sqrt(number); System.out.println("Square Root: " + squareRoot); } else { System.out.println("Invalid input. Square root of a negative number is not possible."); } scanner.close(); } } -