Math.Random Function in Java - java

I have used the below Java code to generate random numbers using math.random function
public class randomnumber {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num = generatenumber(35);
while(num>0 & num < 35) {
System.out.println(num);
break;
}
//System.out.println("greater");
}
public static int generatenumber(int n) {
double d= Math.random() * 100;
int x = (int)d;
//System.out.println(x);
return x;
}
}
However, the output is not being displayed when the number is greater than 35. I want the program to print until num is less than 35. What should I change so that it will do that?
Clarification:
Each time this Math.random() generates a random number. On the the first call, if the number generated is greater than 35 ,then I want this function "generate number " to be called again so that next time if the number is less than 35, that number is printed.

There are three mistakes:
You should use && instead of &. This two operators are quite different.
The line "int num=generatenumber(35);" should be inside the while too.
You need to remove the break statement.

You wrote:
int num=generatenumber(35);
while(num>0 & num < 35)
{
System.out.println(num);
break;
}
You mean to generate and test many times but in fact you're passing zero or one time in your loop depending on the value of num.
The correct code according to your "specs" is
int num;
while(true)
{
num = generatenumber(35);
System.out.println(num);
if (num>0 && num < 35) // note the double &&: logic and not arithmetic
{
break;
}
}
General note: while loops with conditions are most of the time more complicated than with a true. You have to think of an initialization AND a termination condition, which is sometimes the same. Too much copy/paste and errors...
shmosel suggestion is even better using do/while:
int num;
do
{
num = generatenumber(35);
System.out.println(num);
}
while (num>0 && num < 35); // note the double &&: logic and not arithmetic

You can use the following code.
public static void main(String[] args) {
int num = ThreadLocalRandom.current().nextInt(100);
for (; num > 35; num = ThreadLocalRandom.current().nextInt(100)) {
System.out.println(num + " is ignored");
}
System.out.println(num + " is ok");
}

Related

Explain if block nesting

This is regarding some homework and I tried to make a range which is 10 to 40.
The code would accept two inputs within the range. The method will then check if both numbers are within the range and then if they are it would give me the product of both numbers, if not it is suppose to show me a message.
I have been working on this for quite a long time and I cant get it to work I am a complete beginner.
public class testing
{
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
int total = first * second;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
total = first * second;
} else {
System.out.println("Number is not in range, please try again");
}
}
}
}
return total;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
System.out.print("Product of x and y = " + total);
}
}
Expected result is to show me if the numbers are not in range but it is not doing so currently.
It gives me the product of both numbers regardless whether it is in the range.
Here:
int total = first * second;
followed by an if, follewed by:
return total;
Meaning: every time when your if evaluates to false, your method simply returns the value that you assigned initially!
What you could do: have an else block that prints the error message. Or that throws an exception.
But ideally, you should separate concerns here. Meaning:
write a method like boolean inRange(int first, int second). That method returns true or false, depending on first / second matching your criteria
if that method returns true, call compute(), otherwise print your message
In other words: your compute() method maybe shouldn't have that if block at all. Let that method compute the result, and have another method tell you whether you want to invoke compute() or not.
A "ladder" built from ifs behaves as a logical and relation. The first if passes when a condition applies, then the second if passes when both the previous condition applies and its own condition, and so on.
However for checking if something is off, violating any (even a single one) of the rules is enough, that is a logical or relation.
While it is not the best coding style, you could mechanically rewrite that structure into this via flipping the comparisions and dismantling the ladder:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (first > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second < min) {
System.out.println("Number is not in range, please try again");
return 0;
}
if (second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
This method displays the message and returns with 0 if the input is not valid, and returns the product if everything is fine.
Then it could become an actual logical or, which is denoted as || in Java:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (first < min
|| first > max
|| second < min
|| second > max) {
System.out.println("Number is not in range, please try again");
return 0;
}
return first*second;
}
Now as I think of it, there is nothing wrong with your original condition either, just the result has to be flipped: when the code reaches the innermost block, everything is fine, so that is the place where you could return first*second;. And if any of the if fails, you need the message and return 0;:
public static int computeProduct(int first , int second)
{
int max = 40;
int min = 10;
if (min <= first) {
if (first <= max) {
if (min <= second) {
if (second <= max) {
return first*second;
}
}
}
}
System.out.println("Number is not in range, please try again");
return 0;
}
Now I am not so sure if this helps or not...
There you go :
public static int computeProduct(int first , int second)
{ int max = 40;
int min = 10;
if(first<=min || second<=min ||first>=max||second>=max)
{
System.out.println("Number is not in range, please try again");
return 0; //or return whatever you like
}
return first *second ;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number between 10 to 40:");
int x = scanner.nextInt();
System.out.println("Enter another number between 10 to 40:");
int y = scanner.nextInt();
int total = computeProduct(x, y);
if(total!=0){
System.out.print("Product of x and y = " + total);
}
else {
System.out.print("cannot compute as numbers are not in range");
}
}

java: how to calculate multiplication between all values in variable difference

I received that task:
"A small method, calculateProduct is to be written. It will ask the user to enter two int values, and then calculate and display the product of all the values between the two values entered. For example if the user enters the numbers 2 and 5 the program will display the result 120 (calculated as 2 * 3 * 4 * 5)"
I tried to build something like this:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
int b;
int big;
int small;
//ask to insert two variables
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
// compare two variables
// set the biggest variables to b, the smallest - to a
if (a >=b){
big=a;
small=b;
}
else {
big=b;
small=a;
}
// set the do while loop to complete the code. Run multiplying before counter won't fit to b variable
int result = small;
for (int i=small; i<=big;i++){
result*=i;
}
System.out.println("the multiplication progression between "+small+" and "+big+" equals to "+result);
}
}
However, when I insert 2 and 5 the result is 240. Does anybody know how to fix it? thanks!
Change loop to:
for (int i = small + 1; i <= big; i++)
{
result *= i;
}
you init result with small then multiply it by small again.
Fix: Start the for statement with small+1
...
int result = small;
for (int i=small+1; i<=big;i++){
result*=i;
}
....
The other obvious solution here is to change the init statement from
int result = small;
to
int result = 1;
In that case you don't have to touch your looping code.
And for the record: "small" is a rather bad name here, why not call it "smallerInput" or something like that.
Finally: you could avoid dealing with "small" - if a < b you can simply loop from a to b; and otherwise you could loop "backwards" from "b to a".
Just change your for loop as below mentioned will solve your problem.
The problem in your loop is :
In its first iteration it is multiple with itself rather than its
incremented value.
From:
for (int i=small; i<=big;i++)
To:
for (int i=small+1; i<=big;i++)
The task is to write a method called "calculateProduct". Above you are doing all your callculation in your main method. Try to separate that. Example :
import java.util.Scanner;
public class Exam {
public static void main (String[]args) {
Scanner in = new Scanner(System.in);
int a;
int b;
System.out.println("Insert variable a");
a = in.nextInt();
System.out.println ("Insert variable b");
b=in.nextInt();
if(a>=b){
calculateProduct(b,a);
}
else{
calculateProduct(a,b);
}
}
public static void calculateProduct (int m, int n) {
int result = 1;
for (int i = m; i <= n; i++) {
result *= i;
}
System.out.println("the multiplication progression between "+m+" and "+n+" equals to "+result);
}
}

ProjectEuler solution returns incorrect answer

The problem I'm trying to solve comes from ProjectEuler.
Some integers have following property:
n + reverse(n) = a number consisting entirely of odd digits.
For example:
14: 14 + 41 = 55
Numbers starting or ending with 0 aren't allowed.
How many of these "reversible" numbers are there below 10^9?
The problem also gives a hint:
there are 120 such numbers below 1000.
I'm quite new to Java, and I tried to solve this problem by writing a program that checks all the numbers up to a billion, which is not the best way, I know, but I'm ok with that.
The problem is that my program gives out a wrong amount of numbers and I couldn't figure out why! (The code will most likely contain some ugly things, feel free to improve it in any way)
int result = 0;
boolean isOdd = true;
boolean hasNo0 = true;
public int reverseNumber(int r) //this method should be working
{ //guess the main problem is in the second method
int n = 0;
String m = "";
if (r % 10 == 0) { hasNo0 = false; }
while (r > 0){
n = r % 10;
m = String.valueOf(m+n);
r /= 10;
}
result = Integer.parseInt(m);
return result;
}
public void isSumOdd(int max)
{
int number = 1;
int sum = 0;
Sums reverseIt = new Sums();
int amount = 0;
while (number <= max)
{
sum = reverseIt.reverseNumber(number) + number;
while (sum > 0)
{
int x = sum % 10;
if (x % 2 == 0) { isOdd = false; }
sum /= 10;
}
if (isOdd && hasNo0) { amount++; }
number++;
isOdd = true;
hasNo0 = true;
}
System.out.println(amount);
}
Called by
Sums first = new Sums();
first.reversibleNumbers(1000000000);
The most important problem in your code is the following line:
sum = reverseIt.reverseNumber(number) + number;
in isSumOdd(int max) function. Here the reverseIt object is a new instance of Sums class. Since you are using Sums member data (the boolean variables) to signal some conditions when you use the new instance the value of these member variables is not copied to the current caller object. You have to change the line to:
sum = this.reverseNumber(number) + number;
and remove the Sums reverseIt = new Sums(); declaration and initialization.
Edit: Attempt to explain why there is no need to instantiate new object instance to call a method - I've found the following answer which explains the difference between a function and a (object)method: https://stackoverflow.com/a/155655/25429. IMO the explanation should be enough (you don't need a new object because the member method already has access to the member data in the object).
You overwrite odd check for given digit when checking the next one with this code: isOdd = false;. So in the outcome you check only whether the first digit is odd.
You should replace this line with
idOdd = idOdd && (x % 2 == 0);
BTW. You should be able to track down an error like this easily with simple unit tests, the practice I would recommend.
One of the key problems here is that your reverseNumber method does two things: check if the number has a zero and reverses the number. I understand that you want to ignore the result (or really, you have no result) if the number is a multiple of 10. Therefore, you have two approaches:
Only send numbers into reverseNumber if they are not a multiple of 10. This is called a precondition of the method, and is probably the easiest solution.
Have a way for your method to give back no result. This is a popular technique in an area of programming called "Functional Programming", and is usually implemented with a tool called a Monad. In Java, these are implemented with the Optional<> class. These allow your method (which always has to return something) to return an object that means "nothing at all". These will allow you to know if your method was unable or unwilling to give you a result for some reason (in this case, the number had a zero in it).
I think that separating functionnalities will transform the problem to be easier. Here is a solution for your problem. Perhaps it isn't the best but that gives a good result:
public static void main(final String [] args) {
int counter = 0;
for (int i = 0; i < 20; i++) {
final int reversNumber = reverseNumber(i);
final int sum = i + reversNumber;
if (hasNoZeros(i) && isOdd(sum)) {
counter++;
System.out.println("i: " + i);
System.out.println("r: " + reversNumber);
System.out.println("s: " + sum);
}
}
System.out.println(counter);
}
public static boolean hasNoZeros(final int i){
final String s = String.valueOf(i);
if (s.startsWith("0") || s.endsWith("0")) {
return false;
}
return true;
}
public static int reverseNumber(final int i){
final StringBuilder sb = new StringBuilder(String.valueOf(i));
return Integer.parseInt(sb.reverse().toString());
}
public static boolean isOdd(final int i){
for (final char s : String.valueOf(i).toCharArray()) {
if (Integer.parseInt(String.valueOf(s))%2 == 0) {
return false;
}
}
return true;
}
the output is:
i: 12
r: 21
s: 33
i: 14
r: 41
s: 55
i: 16
r: 61
s: 77
i: 18
r: 81
s: 99
4
Here is a quick working snippet:
class Prgm
{
public static void main(String args[])
{
int max=(int)Math.pow(10, 3); //change it to (10, 9) for 10^9
for(int i=1;i<=max;i++)
{
if(i%10==0)
continue;
String num=Integer.toString(i);
String reverseNum=new StringBuffer(num).reverse().toString();
String sum=(new Long(i+Long.parseLong(reverseNum))).toString();
if(sum.matches("^[13579]+$"))
System.out.println(i);
}
}
}
It prints 1 number(satisfying the condition) per line, wc is word count linux program used here to count number of lines
$javac Prgm.java
$java Prgm
...//Prgm outputs numbers 1 per line
$java Prgm | wc --lines
120

Boolean in Java

Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}

Converting decimal to binary in Java

I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand.
What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages:
The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
Multiple markers at this line
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable Binary
Multiple markers at this line
Syntax error on token "mod", invalid AssignmentOperator
Syntax error on token "mod", invalid AssignmentOperator.
Integer.toBinaryString(int) should do the trick !
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.
Working code :
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.
There are a two main issues you need to address:
Don't declare a method inside another method.
Your loop will never end.
For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.
For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation:
int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.
For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.
mod is not a valid operator, the syntax you wanted was %
You can use System.out.print to print on the same line rather than println
Try these corrections and let me know how you get on:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
Here is a small bittesting code I made for Android.
int myres = bitTest(7, 128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards
Mikael Andersson
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}

Categories

Resources