Exception in thread “main” java.lang.ArithmeticException: / by zero [closed] - java

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 1 year ago.
Improve this question
My program is supposed to print all numbers from 1111-9999 where all numbers are evenly divisible by n. However, I am getting an exception stating that I'm dividing by zero. Why is this?
package NestedLoops;
import java.util.Scanner;
public class SpecialNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
for (int i = 1111; i < 9999; i++) {
int firstdigit = i % 10;
int seconddigit = (i / 10) % 10;
int thirddigit = (i / 100) % 10;
int fourtdigit = i / 1000;
if ((n % firstdigit == 0)&& (n % seconddigit == 0) && (n % thirddigit == 0) && (n %
fourtdigit == 0)) {
System.out.printf("%d ", i);
}
}
}
}
enter image description here

This is happens because the % operator are using dividing to calculate the result, so anyNumber % 0 will throw an java.lang.ArithmeticException: / by zero.
To prevent this, check if your digits are equal to 0 before the if statement.

Related

Why 1534236469 can't pass [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I think 1534236469 out of range! Leetcode: 7. Reverse Integer
I can't pass the test input 1534236469. why? the return range is[Integer.MAX_VALUE, Integer.MIN_VALUE],others should return zero
class Solution {
public int reverse(int x) {
if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
return 0;
int ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
return ans;
}
}
Thank for your help
The reverse of 1534236469 is 9646324351, which is larger than Integer.MAX_VALUE, so your code will result in numeric overflow and an incorrect result.
You can use long instead of int to fix the problem.
EDIT:
Your added if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) condition is pointless, since x is int, so it will never be outside the valid range of ints.
Even if x is within the valid range, the reverse of x may be outside the range. If you want to detect that the reversed x is too large and return 0, you should use long internally:
class Solution {
public int reverse(int x) {
long ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
if(ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) {
return 0;
} else {
return (int) ans;
}
}
}

Finding whether number 4 is prime or not? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Here is my program, inside for loop Math.sqrt(n) - I think here is error.
import java.util.Scanner;
public class PrimeNoCheck {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = s.nextInt();
if (isPrime(n)) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
the algorithm is:
To check if n is a prime number, you have to try to divide it by all the numbers, from 2 (1 is useless), to sqrt(n), included.
You don't have to check after sqrt(n), because, if n can be divided by X,
greater than sqrt(n), it also can be divided by Y (n/X), lesser than sqrt(n), or by Z, lesser than Y, if Y is not prime.
The error in you code is that you stop just before sqrt(n).
With your code 4, 9, 25, ... are seen as prime, and every prime ^2 also.
just Replace that: <= instead of <
for (int i = 2; i <= Math.sqrt(n); i++) {

How do you tie a String variable to a String variable? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hello so I am attempting to write a code that test the operators and need a little help declaring variables.
So in my code under my if statement I declare a certain answer to be true or false depending on what the entered number would be and I keep getting stuck on the "cannot find symbol" error. Here is my code
import java.util.Scanner;
public class TestOperators
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//prompt the user to enter an integer
System.out.print("Enter an integer: ");
int num = input.nextInt();
String t = new String("True");
String f = new String("False");
//calculate
if ((num % 5 == 0) && (num % 6 == 0))
answer = t;
else if ((num % 5 == 0) && (num % 6 != 0) || (num % 5 != 0) && (num % 6 == 0))
answer = t;
else if ((num % 5 == 0) || (num % 6 == 0))
answer = t;
else
answer = f;
//print results
System.out.println("Is " + num + " divisible by 5 and 6? " + answer);
System.out.println("Is " + num + " divisible by 5 or 6?" + answer);
System.out.print("Is " + num + " divisible by 5 or 6, but not both?" + answer);
}
}
The program tells me that I cannot declare the variable "answer" in that spot. I am trying to tie the string "f" and "t" variables to the answer variable and dont know how. Please help!
You're not declaring the variable at all. You're just trying to assign to it. You can just add
String answer;
to the code before you start trying to assign to it.
Additionally, you almost never want to call new String(String), and you can simplify your code significantly. You'd be better off determining the result (e.g. just with ||) and then converting the result into a string:
boolean result = ((num % 5 == 0) && (num % 6 == 0)) ||
((num % 5 == 0) && (num % 6 != 0) || (num % 5 != 0) && (num % 6 == 0)) ||
((num % 5 == 0) || (num % 6 == 0));
String answer = result ? "True" : "False";
Looking at that, the result you want actually seems to be as simple as:
String answer = (num % 5 == 0 || num % 6 == 0) ? "True" : "False";
The only way you can get "False" as an answer in both your original code and my final code is if the number isn't divisible by either 5 or 6.
Your code just expresses that in a really complicated way...
You never declared answer. Try adding this line at the beginning of the method:
String answer;

Adding two numbers of large length using strings [closed]

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 8 years ago.
Improve this question
I can't seem to figure out what wrong with this method used to add two strings. It has a buffer when stores each added digit and finally displays. However when two huge numbers (greater than 10 digits) are added it just truncates and doesn't store the remainder of the string.
public static void add(String a,String b){
StringBuilder buf = new StringBuilder();
if((a.length() - 1==0)&&(a.charAt(0)=='0')){
System.out.println(b);
return;
}
if((b.length() - 1==0)&&(b.charAt(0)=='0')){
System.out.println(a);
return;
}
else{
for ( int i1 = a.length() - 1, i2 = b.length() - 1, carry = 0;
(i1 >= 0 && i2 >= 0) || carry != 0;i1--, i2-- ) {
int digit1 = i1 < 0 ? 0 :
Integer.parseInt(Character.toString(a.charAt(i1)));
int digit2 = i2 < 0 ? 0 :
Integer.parseInt(Character.toString(b.charAt(i2)));
int digit = digit1 + digit2 + carry;
if (digit > 9) {
carry = 1;
digit -= 10;
} else {
carry = 0;
}
buf.append(digit);
}
}
System.out.println(buf.reverse().toString());
}
Since need to stop when both i1 and i2 reach a negative value, the condition should be
i1 >= 0 || i2 >= 0 || carry != 0
rather than
(i1 >= 0 && i2 >= 0) || carry != 0
Demo on ideone.
Just use BigInteger, and your whole method is then three lines long.

Java: How to test if individual characters are even or odd? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
In Java, how do I test if a character is an even or odd digit?
Here is what I have so far:
import java.util.Scanner;
public class OddOrEven{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int number, digit1, digit2, digit3;
System.out.print( "Enter three-digit number: " );// prompt
number = input.nextInt(); // read number
// determine the 3 digits
digit1 = number / 100;
digit2 = number % 100 / 10;
digit3 = number % 100 % 10;
if (digit1 % 2 == 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println( "This number contains all even digits.");
if (digit1 % 2 != 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains all odd digits.");
}
}
If the number you are working with is an int (or a similar primitive type like long) then you can do something like this
int num = // something
while (num != 0) {
int digit = num % 10;
System.out.println(digit + " is " + (digit % 2 == 0 ? "even" : "odd"));
num /= 10;
}
This will iterate over the digits from right to left.
public static void main(String[] args) throws Exception {
int num = 28172;
String temp = Integer.toString(num);
int[] numArray = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
numArray[i] = temp.charAt(i) - '0';
}
for (int i : numArray) {
System.out.println("Num " + i + " is " + ((i % 2 == 0) ? "even" : "odd"));
}
}
Gives me the output:
Num 2 is even
Num 8 is even
Num 1 is odd
Num 7 is odd
Num 2 is even
First, convert the int to a String. Then, since Strings are Character arrays, you can loop through each character in the array and turn it into an Integer by subtracting the ascii Character 0. Then, you can loop through each Integer in this array, and use the mod operator (%) which will give you the remainder of a division. num%2==0 will return true if the number is even, otherwise false.

Categories

Resources