How to generate only positive numbers (see what I mean below) - java

So I wrote this very simple program that asks the user to keep guessing numbers until they guess the correct number, and it will tell them if the number they picked is too low or high. The problem i'm having is the numbers were only supposed to be randomly generated 1 through 100 but java took that as -100 through 100. Anyway I was wondering how to only get it to return positive numbers.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GameMain {
public static void main(String[] args) {
int guess = 101;
Random r = new Random();
int answer = r.nextInt()%101;
System.out.println("Whats the number?");
Scanner input = new Scanner(System.in);
while (guess!=answer) {
guess = input.nextInt();
if (guess > answer) {
System.out.println("Too high!");
}
else if (guess < answer){
System.out.println("Too low!");
}
else if (guess == answer){
System.out.println("Correct you win!");
}
}
}
}

The Random class has another nextInt(...) method, one that takes a parameter and that returns a random number between 0 and 1 minus the number passed in. So if you pass in 100, you'll get a pseudo random number between 0 and 99. So just call r.nextInt(100) + 1 on your Random object, r, to get a number between 1 and 100.
In general, if you want a random number between a and b, you would use
r.nextInt(b - a + 1) + a

int answer = Math.abs(r.nextInt());
Not best solution, but another possible alternative...when in doubt with negatives...Math.abs() always works :D

Use
int answer = r.nextInt(100)
instead of
int answer = r.nextInt()%101

Refer this link
http://www.javapractices.com/topic/TopicAction.do?Id=62
you can refer this program and make use i suppose, give 1 as START and 100 as END, generate and then proceed...
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}

Related

Converting a string of ten digits to integer or generating a 10 digit long random integer to create an account number in Java

I would like to generate a ten digit account number greater than 1,000,000,000 and less than 9,999,999,999. I have 3 separate attempts that all are almost operational, but after 9 digits I either receive an error or a number that is generated is not an expected outcome.
for(int i = 0; i < 10; i++) {
int r = rand.nextInt(10);
int l = (int)Math.pow(10,i);
int currentRand = r * l;
System.out.println("i: "+ i+ ", random int: "+ r+", ten to the pow i: "+ l+ ", currentRand: "+ currentRand);
}
int n = rand.nextInt(89999) + 10000;
int n1 = rand.nextInt(89999) + 10000;
int n2 = Math.multiplyExact(n*100000);
System.out.println(n);
System.out.println(n1);
System.out.println(n2);
int accountNum;
String ofNumber = "";
for(int i = 0; i < 10;i++) {
ofNumber += String.valueOf(rand.nextInt(10));
System.out.println(ofNumber);
}
accountNum = Integer.parseInt(ofNumber);
The largest value representable as an int is 2147483647, so about 78% of the 10-digit number range is larger than what can be stored in an int. Use either long or BigInteger.
As Jim Garrison says, your account numbers won't fit into an int but they will fit into a long.
The Random class allows you to generate a stream of random long numbers between a minimum (inclusive) and a maximum (exclusive). Here is an example of this that prints out 10 account numbers:
I have assumed that the smallest account number you want is 1000000000 and the largest 9999999999
import java.util.Random;
public class AccountNumberDemo {
public static void main(String[] args) {
Random rand = new Random();
rand.longs(10, 1_000_000_001L, 10_000_000_000L)
.forEach(System.out::println);
}
}
If you just want one account number in a variable, then this shows how to do it:
import java.util.Random;
public class AccountNumberDemo {
public static void main(String[] args) {
Random rand = new Random();
long accountNumber = rand
.longs(1, 1_000_000_001L, 10_000_000_000L)
.findFirst()
.getAsLong();
System.out.println(accountNumber);
}
}

My code runs, but the if statements are not printing their contents when I compare contents of two arrays

I am trying to write a simple mastermind game where a 4 digit number will be randomly selected by the computer and the user inputs a number over and over again until the correct number is found. I am trying to do this by passing the guessed number and the random number to their own separate arrays and then comparing them, position by position to see if they are similar. If two numbers are in the exact same spot
Example:
if guessArray[0] == numsArray[0] then the computer will print a *.
If two numbers are present but not in the exact same spot (eg. you made a guess of 2056 but the actual number is 1203) then one + should be printed. This cycle repeats until the number is guessed.
I've already asked a friend in person what the problem was and he couldn't figure it out. He knows the most code out of my friends so this was my next place to go.
Here is the full project. I did not write the ConvertInt2Array method. I found it on the internet.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Mastermind {
public static Random numGen = new Random();
public static void main(String [] args) {
Scanner Input = new Scanner (System.in);
int x = 0;
int number = 0;
int random = 0;
int guess = 0;
int y = 0;
int numArray[] = new int[4];
int guessArray[] = new int[4];
boolean isGuessed = false;
//Generate Random Number
for(x=0; x<=3; x++) {
int rand = Math.abs(numGen.nextInt());//Get the absolute value
random = (rand % 999 + 1);
numArray[x] = random;
number+=random;
}
while(isGuessed == false){
System.out.println("Guess a four digit random number");
guess = Input.nextInt();
guessArray = convertInt2Array(guess);
for(y=0; y<=3; y++) {
if(numArray[y] == guessArray[y]) {
System.out.print("*");
}
else if(Arrays.equals(numArray, y, y, guessArray, 0, guessArray.length) == true) {
System.out.print("+");
}
else {
}
if(guess==number) {
isGuessed = true;
}
}
}
System.out.println("You guessed it correctly!");
}
public static int[] convertInt2Array(int guess) {
String temp = Integer.toString(guess);
String temp2;
int temp3;
int [] gArray = new int[temp.length()];
for(int i=0;i<temp.length();i++) {
if (i!=temp.length()) {
temp2 = temp.substring(i, i+1);
} else {
temp2 = temp.substring(i);
}
temp3 = Integer.parseInt(temp2);
gArray[i] = temp3;
}
return gArray;
}
}
There may be more than one issue here, but here's a potential problem:
int rand = Math.abs(numGen.nextInt()); // Get the absolute value
random = (rand % 999 + 1);
This will usually result in random being a three-digit number. You mentioned you want this to be a four-digit number. Random.nextInt() can return any of the possible 232 integer numbers (from -2147483648 to 2147483647). To fix this, use a different Random.nextInt and specify your bounds:
int lowerBound = 1000;
int upperBound = 10000;
random = numGen.nextInt(upperBound - lowerBound) + lowerBound;
Let's break this down: numGen.nextInt(upperBound - lowerBound) evaluates to numGen.nextInt(9000), which will return a number between 0 (inclusive) and 9000 (exclusive), i.e. anything in the range 0-8999. You then add the lower bound of 1000 to ensure that random will be at least 1000 and up to 9999.
See the documentation for Random.nextInt(int bound).
Hopefully this gets you pointed in the right track.

What's wrong with the code? No matter the user input, team 1 will win the game [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Java random always returns the same number when I set the seed?
(7 answers)
Closed 5 years ago.
import java.util.*;
import java.util.Random;
public class Playoffs
{
public static Scanner scan = new Scanner(System.in);
public static void main(String [] args)
{
boolean validNumber;
int game1;
System.out.print("What is the % chance that team 1 will win the game?");
do{
game1 = scan.nextInt();
validNumber = game1 >= 0 && game1 <=100;
if(!validNumber){
System.out.println("INVALID NUMBER ENTERED: NOT BETWEEN 0 AND 100");
System.out.print("Enter a valid number between 0 and 100: ");
}
}while(!validNumber);
System.out.println("Team 1 has a " + game1 + "% chance of winning.");
The code below should generate a random number between 0 (inclusive) and 100 (exclusive), stating that if the random number is less than the percentage the user input, team 1 will win, and team 2 should win if the random number is greater than the percentage entered, but it always comes out that team 1 wins
Random rand = new Random(100);
int randomNumber = rand.nextInt();
int oneGame = simulateOneGame(game1, randomNumber);
if(oneGame == 1){
System.out.println("\nTeam 1 has won the game");
}else if(oneGame == 0){
System.out.println("\nTeam 2 has won the game");
}
}
public static int simulateOneGame(int game1, int randomNumber)
{
int result=0;
if (randomNumber < game1) {
result += 1;
} else if(randomNumber > game1){
result += 0;
}
return result;
}
}
This code doesn't generate a number between 0 and 100:
Random rand = new Random(100);
int randomNumber = rand.nextInt();
rand.nextInt() can return any number between Integer.MIN_VALUE and Integer.MAX_VALUE, but since you are using a constant seed (100), you get the same "random" number every time - -1193959466 in your case.
This code does what you want:
Random rand = new Random();
int randomNumber = rand.nextInt(100);
Also note that you don't have to create a new Random instance in each iteration. It's enough to create one instance.

Count odd digits of a number with recursive method

I tried to write a simple java program which counts how many odd digits there are inside a number (for example, for input "123" the program should return 2). The program instead returns all the digits of the given number. Any idea?
import java.util.*;
//Counts the number of odd digits in an int using recursion
public class OddCount{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
System.out.println("The number of odd digits is " + oddDigitCounter(n));
}
public static int oddDigitCounter(int number) {
int result = 0;
if(number<=10){
if(number%2==0)
result = 0;
else
result++;
}
else{
if(number%10!=0){
if((number%10)/2!=0)
result = 1 + oddDigitCounter(number/10);
else
result = 0 + oddDigitCounter(number/10);
}
else{
result = 0 + oddDigitCounter(number/10);
}
}
return result;
}
}
Here is a way to write your recursive method without all the unnecessary conditions.
public static int oddDigitCounter(int number) {
if (number==0) {
return 0;
}
return (number&1) + oddDigitCounter(number/10);
}
Using &1 instead of %2 allows it to work for negative numbers as well as positive ones.1
1 (number&1) is zero for an even number, and one for an odd number, and works regardless of whether the number is positive or negative. For instance, if number==-3 then (number%2)==-1, but (number&1)==1, which is what we want in this case.
Check your code, you are using / instead of % in this if condition:
if((number%10)/2!=0)
It should be:
if((number%10)%2!=0)
In oddDigitCounter() why don't you simply check digit by digit if it's an even or odd one and echo (store) the result?
Recursive approach: at first call you may pass to the function the entire number and then if the number is 1 digit long let the function do the check and return, otherwhise do the check against the 1st digit and pass the others again to the function itself.
Procedural approach: do a simple loop through the digits and do the checks.
You can use following sample:
import java.util.Scanner;
public class NumberOfOddDigist {
private static int count = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Digit a positive int number: ");
int n = in.nextInt();
countOdd(n);
System.out.println("The number of odd digits is " + count);
in.close();
}
public static void countOdd(int number) {
int remainder = number % 10;
int quotient = (number - remainder) / 10;
if (!(remainder % 2 == 0)) {
count++;
}
number = quotient;
if (number < 10) {
if (!(number % 2 == 0)) {
count++;
}
} else {
countOdd(number);
}
}
}

Increaing Randomly Generated Numbers

I want to generate random integers such that the next generated number is always greater than the previous one.
Assume I start with 3, I want the next to be always greater than 3. And say I generated 5, I want the next to be greater than 5 and so on..
This should get you a number that is consistently larger than the previous value. The range is the maximum distance from the previous value that you want the number to be.
public getLargerRandom(int previousValue){
int range = 100; //set to whatever range you want numbers to have
return random.nextInt(range) + previousValue;
}
int rnd = 0;
while (true) {
rnd = ThreadLocalRandom.current().nextInt(rnd +1, Integer.MAX_INT);
System.out.println("Next random: "+rnd);
}
You would store the randomly generated number as a variable, then use that as a minimum value for the next generation of numbers.
int x = 0;
x = new Random.nextInt(aNumber) + x;
The following example generates a set of random numbers between a start value and a max value without going over the desired maximum number.
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
GetIncreasingInts(20, 3, 101);
}
public static void GetIncreasingInts(int numIntsToGet, int start, int max) {
if (numIntsToGet > 0 && start >= 0 && max > 0) {
Random random = new Random();
int nextStart = start;
int num = -1;
for (int index = 0; index < numIntsToGet; index++) {
if ((max - 1) <= nextStart)
break;
else {
num = nextStart + random.nextInt(max - nextStart);
nextStart = num;
System.out.println("Number: " + num);
}
}
}
}
}

Categories