Why do I get a DivideByZeroException in my Java code? - java

import java.io.IOException;
import java.util.*;
public class calling {
public static String s;
public static String t;
public static int y;
public static int x;
public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;
}
public static void calculation() {
Scanner input = new Scanner(System.in);
System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();
if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}
System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();
if (t.equals("y") || t.equals("Y") ) {
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (x/y));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}
else
if (t.equals("x") || t.equals("X")){
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}
public static void main (String [] args) throws IOException {
num1();
num2();
calculation();
}
}
i keep getting this error in what should be my final result which is simply the result of the calculations being performed
this is the error:" Exception in thread "main" java.lang.ArithmeticException: / by zero
at calling.calculation(calling.java:44)
at calling.main(calling.java:64)"

Since this is likely homework, I'll give you a hint to point you in the right direction.
When you run your program, you execute num1 and num2 to collect the values of x and y from the user. Within num2, y is declared as a local variable. What happens to that variable when num2 returns? And what does that imply for the class field (variable) y declared on line 7?
This is also a good time to learn how to use a debugger. Put a breakpoint on line 44, and see what the values of x and y are.

You need to make sure that the:
int x;
int y;
are the ones you want. Integer's default to zero when static.

Related

Java: Missing return statement for a math quiz?

New to Java. The task is to Create a MathQuiz application that asks the user whether they would like a simple or difficult math quiz and the number of questions they would like to answer. The application then displays the questions, one at a time,prompting the user for the answer and confirming whether or not the answer is correct. The MathQuiz application should include separate methods for the simple and difficult math quiz.The simple() method should display addition problems. The difficult() method should display multiplication problems. Random numbers should be generated for the quiz questions. This is what I have so far:
import java.util.Scanner;
public class MathQuiz {
public static double simple() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberAdd = randomNumber1 + randomNumber2;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " + " + randomNumber2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == randomNumber1 + randomNumber2) {
System.out.println("Correct!");
}else {
System.out.println("Wrong. The correct answer is " + randomNumberAdd);
}
}
public static double difficult() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberMul = randomNumber1 * randomNumber2;
int correct = 0;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " * " + randomNumber2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == randomNumber1 * randomNumber2) {
System.out.println("Correct!");
}else{
System.out.println("Wrong. The correct answer is " + randomNumberMul);
}
}
//user options
public static void main(String[] args) {
int choice;
Scanner input = new Scanner(System.in);
System.out.println("There are two levels available:");
System.out.println("1. Simple");
System.out.println("2. Difficult");
System.out.print("Enter your choice: ");
choice = input.nextInt();
if (choice == 1) {
simple();
} else if (choice == 2) {
difficult();
}
input.close();
}
}
public static double simple() {}
public -> It specifies the access level of this function.
static -> It means this function is a behavior of your class and not specific to any instance of this class.
double -> It's what your function returns, a double typed value here, as an output at end of execution.
simple()-> It's your function name
In both of your functions simple() and difficult() you are not returning any value as output. So you have to change it to void.
Change your method simple() and difficult() return type from double to void and the error should go away
Change the return type of simple() and double() method to void, i.e.
public static void simple() and
public static void difficult()
The return type of these methods is currently double, so it is expected to return a double value. If they don't return a double value, the compiler will give you an error. So, if you don't plan to return a value in your methods, change the return type to void.
Removing the return type of double from your method's signature and setting it to void, the error should go away.
public static void simple() {
// your code
}
public static void difficult() {
// your code
}

Type mismatch:could not convert from int to boolean

In the if statement, within the argument I get an error saying "type mismatch, could not convert from int to boolean". Please provide a solution.
public static void main(String[] args) {
Scanner sathya1 = new Scanner(System.in);
System.out.println("Enter the numbers");
int x = (sathya1.nextInt());
int y = (sathya1.nextInt());
int addition = x+y;
int subtraction = x-y;
int multiplication = x*y;
float division = x/y;
if(sathya1.nextInt(addition){
System.out.println("The number is " +addition);
elseif(sathya1.nextInt(subtraction)){
System.out.println("The number is " +subtraction);
elseif(sathya1.nextInt(multiplication)){
System.out.println("The number is " +multiplication);
elseif(sathya.1nextInt(division)){
System.out.println("The number is " +division);
}
}
}
}
}
}
The line
if(sathya1.nextInt(addition){
makes no sense. It's like saying "if 12". The same goes for the other lines. In addition, you're missing a closing ), among lots of other problems.
Maybe you mean:
import java.util.Scanner;
public class BasicArithmetic
{
public static void main(String[] args)
{
//create a scanner for keyboard input
Scanner sathya1 = new Scanner(System.in);
//ask user for the operation to be used
System.out.print("Please enter the corresponding number to be used \n(1)for Addition,(2)for Subtraction,(3)for Multiplication,(4)for Division:");
int enteredNumber = sathya1.nextInt();
//get the two numbers to be used
System.out.println("Enter the numbers");
float x = sathya1.nextFloat();
float y = sathya1.nextFloat();
//arithmetic operations of the two numbers
float addition = x+y;
float subtraction = x-y;
float multiplication =x*y;
float division = x/y;
//if..else statement
if(enteredNumber==1)
{
System.out.println("The sum of the two number is "+addition);
}
else if(enteredNumber==2)
{
System.out.println("The subtraction of the two number is "+subtraction);
}
else if(enteredNumber==3)
{
System.out.println("The product of the two number is "+multiplication);
}
else if(enteredNumber==4)
{
System.out.println("The quotient of the two number is "+division);
}
else
{
System.out.println("Please enter the correct corresponding number");
}
}
}

JAVA Greatest common divisor recursion

I can't get this to run.There is a tester program and a method below. it says error identifier expected.Thanks in advance
public class 121tester{
public static void main(String[]args){
Scanner input= new Scanner(System.in)
System.out.println("Enter first number");
int num1=input.nextInt();
System.out.println("Enter second number");
int num2=input.nextInt();
System.out.println("The Greatest common factor of "+num1+" "+num2+" is "+GCD(num1,num2));
}
}
private static int GCD(int num1, int num2){
if(num2==0){
return num1;
}
return(GCD(num2, num1%num2);
}
Class name can't start with number. Change from
class 121tester
to
class Tester121
Another thing your GCD method should declare into inside class. It is better to use some IDE at initial stage of programming to remove compiler error.
Try the following:
import java.util.Scanner;
public class GCDTester{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int num1 = input.nextInt();
System.out.println("Enter second number");
int num2 = input.nextInt();
System.out.println("The greatest common factor of " + num1 + " " + num2 + " is " + gcd(num1,num2));
}
private static int gcd(int num1, int num2){
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
}
But #Masud is correct, you should place the gcd method in a class of its own so that it can be used as an object in its own right.

BMI calculator errors

While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java

How can I return a statement in this program correctly?

I want my program to execute the first return statement if the conditions are true otherwise return it as normal.
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
return answer;
}
}
Well, in your code you don't need to return anything.
But, if you want to return something you are in the wrong method.
main is a "special" method, it cannot return anything (well, in other languages it might return an int which is the exit status, but ignore it here) and is where your code starts.
If you want to return something you should write a method.
A method is a block of code which is execute when you call it and can return value back to who called it. In this case your method will be static because you will call it from the main method which is static
public static int methodName()
{
int X, Y;
int answer;
if (x == y)
{
// Do something
return returnSomethingBackTomain;
}
else
{
return returnSomethingOfDifferentTomain;
}
}
Well.. it could be your method
public static int methodName()
{
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
}
else {
System.out.println("These two numbers are not the same, but they equal: " + answer);
}
return answer;
}
But please be more specific on what you want to do.
Because i dont see any reason to write a such method.
If your main function is void, you don't have to return anything, you can just use
return;
That gives:
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return;
}
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
But you can also do:
...
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
} else {
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
}
import java.util.Scanner;
public class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y)
System.out.println("These two numbers are the same and they equal: " + answer);
else
System.print.ln("These two numbers are not the same, but they equal: " + answer);
}
}
main has a void return type, so no need to return anything.
By the way, try to fit CQS principle.
Indeed, printing something is a side-effect operation, so no need to return anything but void.
You're making a few mistakes.
The main method should never be used to return a value.
The main method is the entry point to your program.
Here you declare methods to be run at the start of the program. In GUI-projects, this is used to load the inital GUI (Forms).
Also, a void method cannot return something.
When initalising a method, you have to declare what type the returned value will have.
Void means that there is no data returned.
You will have to write a method which you can call to receive your data.
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
int answer = x + y;
if (x == y) {
System.out.println("These two numbers are the same and they equal: " + answer);
return answer;
}
return answer;
}
Now you can initalize your class (e.g. Scanner) and call the method scanForEqualNumbers.
Scanner scanner = new Scanner();
int result = scanner.scanForEqualNumbers();
If you don't want to have to initialize a class to call the method, you can declare the scanForEqualNumbers as static.
public static int scanForEqualNumbers() { ...
Then you can call this method directly as this:
int result = Scanner.scanForEqualNumbers();
1 more note.
You don't need the return in the IF-statement.
As you return the answer anyway, you can keep the print the the IF-statement and use the return after it.
You could also return -1 as answer in an ELSE-statement so you can use this answer in further methods. This way you can check the result of the method without having to read the console output.
I even suggest to make a seperate class for this.
You'll need your Main-method to run your program. This'll also be the location of your method class.
public class MyApp {
public static void main(String[] args) {
MyScanner myScanner = new MyScanner();
int result = myScanner.scanForEqualNumbers();
System.out.format("The scanned numbers %s equal", result > 0 ? "ARE" : "are NOT");
}
}
public class MyScanner {
import java.util.Scanner;
public class Untitled {
public int scanForEqualNumbers() {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
/* This can be replaced, see below
int answer = x + y;
if (x != y) {
answer = -1;
}
return answer;
*/
// IF X equals Y ? return X + Y : ELSE return -1
return (x == y ? x + y : -1);
}
}

Categories

Resources