This question already has answers here:
Java exponent error at 2^31 power [duplicate]
(2 answers)
Closed 8 years ago.
So, I have this code, which works fine for the first 4 numbers, but then it gives a wrong number, What's the problem? (I know I can also use Math.pow, but I wanted to try doing it myself first)
public static void main(String [] args){
int number = 98;
int result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
Console:
9604
92236816
449273376
Switch your int number to a long and you will get the right result.
public static void main(String [] args){
**long** number = 98;
**long** result = number;
int exponentt = 5;
int exponent = exponentt--;
System.out.println(Math.pow(number, exponent));
for (int i = 0; i < exponentt ;i++) {
result = result * number;
System.out.println(result );
}
}
It's going outside of the range for the int and giving you weird results. int can only store up to 2,147,483,647 -- 98^4 is well over that (9,039,207,968)
Related
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 5 years ago.
Improve this question
This program is supposed to go through the number of 2 to 50 people and get the probability out of 100,000 trials whether 2 people will have the same birthday or not.
import java.util.Random;
public class birthday {
public static void main(String[] args) {
int N = 2;
while (N != 51) {
double probability = one_probability(N);
System.out.println(N + " " + probability);
N++;
}
}
public static boolean one_group(int N) {
int A[] = new int[N];
Random random = new Random();
boolean have_match = false;
for (int i = 0; i < N; i++) { //assigns each person a birthday
int k = random.nextInt(365);
A[i] = k;
}
for (int i = 0; i < N; i++) { //testing to see if birthdays match up
for (int j = i+1; j < N; j++) {
if (A[i] == A[j]) { have_match = true; break; }
}
}
return have_match;
}
public static double one_probability(int N) {
int x = 0;
for (int i = 0; i < 100000; i++) { //repeating 100,000 times to get average probability
boolean have_match = one_group(N);
if (have_match == true) { x++; }
}
double probability = x / 100000; //getting the average probability
return probability;
}
}
Here's the result (it goes from 2-50), it keeps giving me zeros so I know something is wrong. Please help :)
Output
Try with
int probability = x / 1000; // 1/100 of the value to get an probability in percent (integer)
or
float probably = x / 100000F; //F for a `float`
double probability = x / 100000.0; //a decimal without a F is a `double`
Without that, this can't work :
float probably = x / 100000;
First, the division of two integer will be stored in memory like an integer then store in a float/double. That storage truncate the value. This is the operator logic to return the biggest type in an operation so :
int * int -> int
int * float -> float
int * double -> double
short * short -> int //that's a trick, int is the minimal value an operation can return
int probability=x/100000; always return 0.
convert it to double probability=x/100000.0; the value of probability will always less than or equal one. because x will never be greater than 100000. And also change the return type of one_probability method to double.
This question already has answers here:
Converting Decimal to Binary Java
(26 answers)
Closed 6 years ago.
How can we convert int number, a decimal, to Binary? I'm learning Java & have the code below. Any advice? Thanks!
public static int decimalToBinary(int number) {
int result = 0;
while(number > 0){
int mod = number % 2;
result = result * 1 + mod;
number /= 2;
}
return result;
}
You can use the Integer.toBinaryString() method as follows,
int n = 100;
System.out.println(Integer.toBinaryString(n));
The Integer.toBinaryString() takes an int as a parameter and returns a String, so you can also do the following:
int n=100;
String s = Integer.toBinaryString(n);
System.out.println(s);
This will print it out to the screen, but you can just as easily assign it to a variable.
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
My question is why isn't the code generating the amount of numbers that the users enters? Right now the code is only generating one number. Here is the original question given to me:
"In your main method, prompt the user for a number n. Write a method
called assessRandomness that generates a random number between 1 and
100 'n' times and return the percentage of times the number was less than
or equal to 50. Call your assessRandomness method from main and display
the result to the user from main. Do not interact with the user from
within the assessRandomness method."
output:
How many random numbers should I generate? 10
<assume the random numbers generated were 11 7 50 61 52 3 92 100 81 66>
40% of the numbers were 50 or less
my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("how many random numbers should I generate?: ");
int number = in.nextInt();
assessRandomness(number);
}
public static double assessRandomness(int n){
int random = (int)(Math.random()*100);
int randomNumbersLessthan50 = 0;
if (random <= 50)
{
double getPercentage = random/randomNumbersLessthan50;
}
else
{
System.out.println(random);
}
return random;
}
I don't see any kind of loop within assessRandomness.
Try
for(int x = 1; x <= n; x++){ ... }
as first line in assessRandomness, it should finally look like
public static double assessRandomness(int n){
int counterLessThan50 = 0;
for ( int x = 1; x <= n; x++)
if( (int)(Math.random()*100) <= 50 ) counterLessThan50++;
return (double) counterLessThan50 / n;
}
There's no repetition in your code to do something n times.
Here's one way to do it in one line using a stream:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).map(r -> r * 100 + 1).filter(r -> r <= 50).count() / (double)n;
}
Note that converting Math.random() to a number in the range 1-100 is pointless; this will give the same result:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).filter(n -> n < .5).count() / (double)n;
}
And is easier to read.
At the moment, your assessRandomness method never uses the variable n.
At first you should initialize a variable which counts the number of created randoms that are bigger than 50 (this will be your retutn value). You should then do a loop from 0 until n. For each loop run you should create a random value between 0 and 100. Then you should check wether the value is bigger than 50. If so, count up your previously created variable. When the loop has finished, return the count variable and print it in the main method.
This should help you understand better how to do something like this.
public static void main(String[] args) {
System.out.println("how many random numbers should I generate?: ");
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int[] arrayPlaceHolderInMainMethod = new int[number];
arrayPlaceHolderInMainMethod = generateRandomNumberArray(number);
assessRandomness(arrayPlaceHolderInMainMethod);
}
public static void assessRandomness(int[] inputArray) {
int randomNumbersLessthan50 = 0;
int randomNumbersGreaterthan50 = 0;
int random = 0;
for (int i = 0; i < inputArray.length; i++) {
random = inputArray[i];
}
if (random <= 50) {
randomNumbersLessthan50 += 1;
} else {
randomNumbersGreaterthan50 += 1;
}
System.out.println(">50: " + randomNumbersGreaterthan50 + " Less: " + randomNumbersLessthan50);
}
public static int[] generateRandomNumberArray(int numberPickedByUser) {
int[] arrayOfRandomNumbers = new int[numberPickedByUser];
for (int i = 0; i < numberPickedByUser; i++) {
arrayOfRandomNumbers[i] = (int) (Math.random() * 100 + 1);
}
return arrayOfRandomNumbers;
}
This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 7 years ago.
Below is a code that I have for flipping a given integer and displaying the flipped results. It runs but I have issues for when the number is smaller than two digits. It obviously cannot be flipped. I wanted to make the loop an if else stating "if number is two digits or more reverse." "Else state that the integer needs to be two or more digits." how could I go about this?
import java.util.Scanner;
public class ReverseInteger {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer that you would like to have reversed: ");
int number = input.nextInt();
reverse(number);
}
public static void reverse(int userInteger)
{
int tempDigit = 0;
while (userInteger > 0){
tempDigit = userInteger % 10;
System.out.print(tempDigit);
userInteger = userInteger / 10;
}
}
}
I am trying to get it to understand that 01 can be converted to 10. This would need to be done by the code understanding that the userInteger is more than one digit but I cant seem to figure out how to do that... Any ideas on how I can get this to check for two digits and execute the loop accordingly would be appreciated!
public static void reverse(int n)
{
int temp = 0;
int count = 0;
while(n != 0)
{
if(n%10 == 0)count++;
temp = temp*10 + n %10;
n /= 10;
}
for(int i = 0; i < count; i++)
{
System.out.print(0);
}
System.out.println(temp);
}
Convert the int to a String using Integer.toString method and save it to a string. Declare a String that will be later used as output. Start a for loop that goes through the number ( which was converted to a String) from its end to its beginning. It add each character from end to start to the output String. This results in the output String to be the reverse of the number String. Then just simply convert the output String using Integer.parseInt method and return the int value.
The code should look like:
public static int reverse(int n)
{
String number = Integer.toString(n);
String output;
for(int i = number.length()-1; i >= 0; i--)
output += number.charAt(i);
return Integer.parseInt(output);
}
I recommend using String.valueof(int).toCharArray(); and looping through in reverse to compose a new char[]. Then use Integer.parseInt(String);
This question already has answers here:
java.lang.ArrayIndexOutOfBoundsException: 0 - Array larger than Index?
(5 answers)
Closed 8 years ago.
When I try to comply I get this Error:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0"
I do not know hy
package Darts;
import java.util.Random;
import static java.lang.Integer.*;
/**
* Created by BryanSingh on 12/12/14.
* Dartsim.java
*
*/
public class DartSim
{
public static void main(String[] args)
{
//int trials = 0;
int trials = Integer.parseInt(args[0]);
DartSim myDart = new DartSim();
for (int i=1; i<=trials; i++)
{
myDart.toss();
System.out.println("pi = " + 4.0 * (double) myDart.getHits() / myDart.getThrows());
}
}
private int hits;
private int tries;
private Random gen;
public DartSim()
{
hits = 0;
tries = 0;
gen = new Random();
}
public void toss()
{
double x = 2 * gen.nextDouble() - 1;
double y = 2 * gen.nextDouble() - 1;
if(x*x+y*y<1)
{
hits = hits +1;
}
tries = tries +1;
}
public int getHits()
{
return hits;
}
public int getThrows()
{
return tries;
}
}
You aren't specifying any arguments when you run the program so args[0] isn't a valid index.
// to use 10 when there aren't args...
int trials = (args.length > 0) ? Integer.parseInt(args[0]) : 10;
Array Index Out Of Bounds Exception occurs in a for loop when it attempts to use the value of i in this case and the value of i is less than zero.
java.lang.ArrayIndexOutOfBoundsException: 0 is self explanatory args[0] position of array is not having value, that's why int trials = Integer.parseInt(args[0]); line throwing exception, you have to pass argument to your program.