Java Math random() to print only one number [closed] - java

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 2 years ago.
Improve this question
How could i get this code to just give me ONE number between 0-9.
At the moment it prints 10 numbers between that 0-9 but i need it to just pick one number from 0-9
import java.lang.Math;
public class random {
public static void main(String args[]) {
int max = 9;
int min = 0;
int range = max - min + 1;
for (int i = 0; i < 9; i++) {
int rand = (int)(Math.random() * range) + min;
System.out.println(rand);
}
}
}

Your System.out.println(rand) is inside the for loop that repeats 9 times. If you want a single value to be displayed, just remove the loop. That should fix it. Like the following:
public class random {
public static void main(String args[]) {
int max = 9;
int min = 0;
int range = max - min + 1;
int rand = (int)(Math.random() * range) + min;
System.out.println(rand);
}
}

Related

How to link one with another parts [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 3 years ago.
Improve this question
I have this homework. I'm having a hard time linking the first part with the second. This is what I have. I know I'm missing something at some point to indicate that from the number input it should add the next 100 numbers.
package test;
import java.util.Scanner;
public class Ex216 {
public static void main(String[] args) {
// Write a program in Java that reads an integer from the keyboard and makes the sum of the next 100 numbers, showing the result on screen
Scanner myInput = new Scanner(System.in);
int =a
int sum;
System.out.print("Enter first integer: ");
a = myInput.nextInt();
for (int n = a; n <= 100; n++)
System.out.printf("Sum = %d\n", sum);
}
}
This is what is casing me the trouble.
first of all,int =a is not a valid expression. it should be int a; then as you want to add next 100 number from the given value, you need to add those values into sum, such as sum = sum+number.
Here is a code snippet:
Scanner myInput = new Scanner(System.in);
// correct declaration
int a;
// initialize sum with zero.
int sum=0;
System.out.print("Enter first integer: ");
a = myInput.nextInt();
//for simplicity,start value n from a and loop until n reaches a+100.
for (int n = a; n <= 100+a; n++) {
sum = sum + n;
}
System.out.println("Sum = "+ sum);

My Java code is not running [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 5 years ago.
Improve this question
If I am not mistaken, this bit of code should print out all even numbers smaller than or equal to 100. When I run this code, nothing happens. No error message or anything. I'm using Eclipse.
public class Even {
public static void main(String args[]) {
int number = 1;
int remainder = number % 2;
while(number <= 100) {
number++;
if(remainder == 0) {
System.out.println(number);
}
}
}
}
As others stated before, value of remainder is set only once. However, you check it a hundred times expecting it to tell you something else every time. I'd suggest putting it inside a loop, so you get a "fresh" value for every number.
public class Even {
public static void main(String args[]) {
int number = 1;
int remainder;
while(number <= 100) {
number++;
remainder = number % 2;
if(remainder == 0) {
System.out.println(number);
}
}
}
}
The reminder doesn't change as the assignment is prior to while loop. The statement int remainder = number % 2; has to be inside while loop to see the expected result.
for(int i = 0;i<=100; i= i+2)
System.out.println(i);
You do not need remainder :)

Java 8 Unreachable Code [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
I am fairly new to Java and I ran into this problem once or twice in one of my books. This is a super simple program and I just don't understand why it's not working. I know when you use return, anything after it in the method is meaningless. So does this mean after you perform an for statement or an if statement that is a return?
I am using Java 8 on Windows 8 in the latest version of Eclipse.
This is my simple program:
// Find the sum of 1 through 50 and the average.
class SumAndAverage
{
public static void main(String args[])
{
int sum = 0;
double average = 0;
for(int i = 1; 1 <= 50; i++)
{
sum += i;
}
// the following code is "unreachable"
average = sum / 100;
System.out.println("The sum is: " + sum);
System.out.println("The average is " + average);
}
}
1 is always less than or equal to 50, isn't it? You probably meant to compare i with 50:
for(int i = 1; i <= 50; i++)
{
sum += i;
}
for(int i = 1; 1 <= 50; i++)
1 is always less than or equal to 50.

Sum of factorials in Java [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 8 years ago.
Improve this question
I made a program to sum factorials in java like 4! + 3! + 2! + 1! = 33, but it doesn't work. Could anyone help explain why?
import javax.swing.JOptionPane;
public class fac {
public static void main(String[] args) {
int sum = 0, fact, i, j;
fact = Integer.parseInt(JOptionPane.showInputDialog("ENTER NO"));
for (i = fact; i > 1; i--) {
for (j = fact - 1; j > 0; j--)
fact = fact * j;
sum = sum + fact;
}
sum = sum + 1;
System.out.print("SUM OF FACTORIAL = "+sum);
}
}
You are repeatingly calculating factorial of fact in the outer loop. The start value of the inner loop is wrong.
But you should have found this error by yourself using a debugger.
This is where methods might come in handy. First an outer loop because you're counting down (from 4, in this example).
static final int NR = 4; //for example
static void main(String[] args) {
int total = 0;
for (int i = NR; i > 0; i--)
total += calculateFactorial(i); //i += j; is the same as i = i + j;
System.out.println("Answer: " + total);
}
Now it looks way easier, right? The code suddenly became readable. Now for calculateFactorial(int nr) all we have to do is calculate 4 * 3 * 2 * 1 (for the factorial of 4, that is):
public static int calculateFactorial(int nr) {
int factorialTotal = 1;
for (int i = nr; i > 0; i--)
factorialTotal *= i; //i *= j; is the same as i = i * j;
return factorialTotal;
}
Methods just made code easy to read and write. I'd suggest you read a book like Clean Code

Project Euler 12 - Optimization [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 9 years ago.
Improve this question
I am working on Project Euler Problem 12. Could anyone provide any tips on how to improve my code so it executes in my life time?
public class HighlyDivisibleTriangularNumber {
public static void main(String[] args) {
int divisors = 0;
int count = 1;
while(divisors <= 501) {
long triNum = triangularNumber(count);
divisors = getFactors(triNum);
System.out.println(triNum+"_"+divisors);
count++;
}
}
private static int getFactors(long triNum) {
int divisors = 0;
while(triNum > 1) {
triNum = triNum / 2;
divisors++;
}
return divisors;
}
private static long triangularNumber(int i) {
long total = 0;
for(int k = 1; k <= i; k++) {
total += k;
}
return total;
}
}
1) triangular numbers
The first (and probably most important) optimization you can do is in how you compute the triangular numbers.
You can observe that the nth triangular number (let's call it t(n) ) is equal to n + t(n-1).
So each time you compute a triangular number, you can just take the triangular number before it and add n. This would lead to the naive recursive function :
private static long triangularNumber(int i) {
if(i == 1) return 1;
else return i+triangularNumber(i-1);
}
But this won't improve the performance much... to resolve this, I suggest you do some research on memoization and adapt the function I gave you (I won't give you the answer, this is an excellent exercise)
Now, on a regular computer you should have the answer to the problem in a reasonable time. But it can be improved a little better
2) counting divisors
Your function for counting divisors is wrong. What you should do is try to divide your number by successive natural numbers and see if the result is an natural integer.
private static int getFactors(long triNum) {
int divisors = 0;
for(int i = 1; i <= triNum; ++i) {
if(triNum%i == 0) // triNum is a multiple of 1 <=> i is a divisor of triNum
divisors++;
}
return divisors;
}
You can even improve this by counting only to the square root of trinum and adding two divisors each time. But there's a trick if you do this, I'll let you figure it out if you decide to try this.
Why do do recompute the triNum each time? Just add the difference each time (basically your count).
public static void main(String[] args) {
int divisors = 0;
int count = 1;
long truNum = 0;
while(divisors <= 501) {
triNum += count;
divisors = getFactors(triNum);
System.out.println(triNum+"_"+divisors);
count++;
}
}
Furthermore, your approach to count the factors is completely off. You are just searching for the first power of two to be greater than the given number. Read up on (prime)-factorization. Note that you need to account for the combinations of (prime) factors, too.
Example: 12
12 = 2 * 2 * 3
But the divisors of 12 are
1, 2, 3, 4 (= 2*2), 6 (= 2*3), 12
So in total there are 6 divisors of 12 and not 3 as the mere prime factorization may lead you to believe.

Categories