check unrepeated random number - java

I have a method that return a number:
public String getNum()
{
Random random = new Random();
return random.nextInt(1000) + "";
}
And I have this method that stores an object
public void store(User user)
{
String str = getNum();
user.setIdCode(str);
for (User users: userList)
{
if(users.getId() == user.getId())
{
user.setIdCode(getNum);
}
}
}
if Id is excited than re-set the id. This is for sure checks if the id exists the first time but how about the second time that id is set. there would be a possibility of repeating the same number. At the same time we cant go in infinite loop.

What you can try is add a few random numbers in a Set and then use them separately whenever you want.
What I mean by it is that if you're trying to get a random number every time, you can just store some random numbers at once and then retrieve them one by one when you need them.
In code, put this in some method called storeRandomNumbers() and call it in the beginning of your program. Also, declare the Set as a global variable.
You can also make a separate variable to keep track of how many random numbers have been used up and use it to retrieve the next random number from the Set.
The code would look something like this (makes changes according to your needs):
Random rand = new Random();
Set<Integer> uniqueRandoms = new HashSet<>();
while (uniqueRandoms.size()<10){
uniqueRandoms.add(rand.nextInt(11));
}
for (Integer i : uniqueRandoms){
// System.out.print(i+" ");
// retrieve them from here and use them whenever you want
}
Edit:
Yes as #Andreas gave the link to suggest, you don't compare Strings with ==, rather you use the equals() method.

Related

How to return an integer from a variable in Java?

I've never written a single line of Java in my life and I'm trying to help my son return a random number between 0-100. I figured out how to write it to the console but not how to return the actual value out of his method so he can use it. I think it has something to do with the crazy void, static, or ways ya'll write your functions. That's all Greek to me (er, java to me). Coming from Javascript I fixed that up for him in 10 secs but this has now really stumped me since I know nothing about Java.
The code is below and I want to give him some kind of return so he can use the number in the program he's writing.
import java.util.Random;
public class generateRandom{
public static void main(String args[]){
// create instance of Random class
Random rand = new Random();
// Generate random integer in range 0 to 100
int rand_int1 = rand.nextInt(101);
// Print random integers
System.out.println("Random Integer: "+rand_int1);
}
}
You can start by adding a static method like:
public static int computeRandom() {
Random rand = new Random();
return rand.nextInt(101);
}
and then invoke that method from your main().
But thing is: there are no detours in life. The real answer is: even if you just want "some small thing", you will have to invest the time and energy to learn enough to make that happen.
You need to create a separate method here return the random value and pass it around or you can just pass the rand_int variable as a argument to the function you want to use.

Random Number Occurrence Check

I have an array of Strings and when the user taps the button inside my app I generate a random number and use it to select a random String from my facts[] array. However, I tried improving my code so that the same random number would "never" occur(leading to the same String been shown to the user). Despite my efforts, my "Check" blocks doesn't seem to work since it generates a random fact when I click the button for the first time and then it does nothing. Please help me figure out the correct logic behind this and maybe write a more efficient code-block.
My current logic: check if the random number that has been generated already exists in my int[] factsCheck array and if it does create another one.If it doesn't add it to the array so that the program knows it has already been created once.
int[] factsCheck = new int[facts.length];
boolean isNotNewRandomNumber = true;
int count = 0;
int randomNumberToReturn;
private void initFactsCheck() {
for(int i=0; i<=factsCheck.length;i++) {
factsCheck[i] = -1;
}
}
String getFact() {
// Randomly select a fact
Random randomGenerator = new Random();
while(isNotNewRandomNumber) {
randomNumberToReturn = randomGenerator.nextInt(facts.length);
for(int i = 0; i<factsCheck.length; i++) {
if(factsCheck[i] == randomNumberToReturn) {
break;
} else {
count++;
}
}
if (count == factsCheck.length) {
// Doesn't exist
isNotNewRandomNumber = false;
}
count = 0;
}
return facts[randomNumberToReturn];
}
In the beginning of getFacts(), add this:
isNotNewRandomNumber = true;
The problem is that you isNotNewRandomNumber to false the first time you call getFacts(), then you never set it to true again, so you will never go into the while loop again.
I'm not sure that's all you need to do. There might be other errors too. It seems unnecessary to have a for loop inside the while loop. There must be a better way. And you probably want to set factsCheck[x] to some appropriate value just before the return statement.

Why is there no output from the While loop in my code, despite everything else working?

I made this program in java, on the BlueJ IDE. It is meant to take a number in the decimal base and convert it into a base of the users choice, up till base 9. It does this by taking the modulus between two numbers and inserting it into a string. The code works till the input stage, after which there is no output. I am sure my maths is right, but the syntax may have a problem.
My code is as follows:
import java.util.*;
public class Octal
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int danum = 0;
int base = 0;
System.out.println("Please enter the base you want the number in (till decimal). Enter as a whole number");
base=in.nextInt(); //This is the base the user wants the number converted in//
System.out.println("Enter the number you want converted (enter in decimal)");
danum=in.nextInt(); //This is the number the user wants converted//
while ( danum/base >= base-1 && base < danum) {
int rem = danum/base; //The number by the base//
int modu = danum % base;//the modulus//
String summat = Integer.toString(modu);//this is to convert the integer to the string//
String strConverted = new String();//Making a new string??//
StringBuffer buff = new StringBuffer(strConverted);//StringBuffer command//
buff.insert(0, summat); //inserting the modulus into the first position (0 index)//
danum = rem;
if ( rem <= base-1 || base>danum) {//does the || work guys?//
System.out.println(rem + strConverted);
}
else {
System.out.println(strConverted);
}
}
}
}
I am very new to Java, so I am not fully aware of the syntax. I have done my best to research so that I don't waste your time. Please give me suggestions on how to improve my code and my skill as a programmer. Thanks.
Edit (previous answer what obviously a too quick response...)
String summat = Integer.toString(modu);
String strConverted = new String();
StringBuffer buff = new StringBuffer(strConverted);
buff.insert(0, summat);
...
System.out.println(strConverted);
Actually, strConverted is still an empty string, maybe you would rather than display buff.toString()
But I don't really understand why making all of this to just display the value of modu. You could just right System.out.println(modu).
I assume that you want to "save" your value and display your whole number in one time and not each digit a time by line.
So you need to store your number outside of while loop else your string would be init at each call of the loop. (and print outside)
So, init your StringBuffer outside of the loop. you don't need to convert your int to String since StringBuffer accept int
http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#insert-int-int-
(You could even use StringBuilder instead of StringBuffer. It work the same except StringBuffer work synchronized
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)
Your if inside the loop is a specific case (number lower than base) is prevent before the loop since it's the opposite condition of your loop. (BTW : rem <= base-1 and base>danum are actually only one test since rem == danum at this place)
so :
StringBuffer buff = new StringBuffer();
if(base > danum) {
buff.append(danum);
} else {
while (danum / base >= base - 1 && base < danum) {
int rem = danum / base;
int modu = danum % base;
buff.insert(0, modu);
danum = rem;
}
if(danum > 0) {
buff.insert(0, danum);
}
}
System.out.println(buff.toString());
I would also strongly recommand to test your input before running your code. (No Zero for base, no letters etc...)
2 Things
do a lot more error checking after getting user input. It avoids weird 'errors' down the path
Your conversion from int to String inside the loop is wrong. Whats the whole deal summat and buff.... :: modifying the buffer doesnt affect the strConverted (so thats always empty which is what you see)
try to get rid of this. :)
error is logic related
error is java related
Your code has the following problems:
Firstly, you have declared and initialized your strConverted variable (in which you store your result) inside your while loop. Hence whenever the loop repeats, it creates a new string strConverted with a value "". Hence your answer will never be correct.
Secondly, the StringBuffer buff never changes the string strConverted. You have to change your string by actually calling it.
You print your result inside your while loop which prints your step-by-step result after every repetition. You must change the value of strConverted within the loop, nut the end result has to be printed outside it.

program on arraylist java

System.out.println("Enter the appointment ID to see the full details :");
int y=in.nextInt();
int r;
for(r=0;r<count;r++)
{
if(all.get(r).getID()==y)
{
all.get(r).display();
}
}
I am using this code to retrieve the full details that have been entered using the get statement and display function. This is a small part of my program. I was wondering is there any other way to do it
A better way would be to use a HashMap<Integer,DetailsClass> instead of an ArrayList.
Then, instead of a loop, you'll just write :
HashMap<Integer,DetailsClass> map = new HashMap<>();
...
if (map.containsKey(y)) {
DetailsClass details = map.get(y);
details.display();
}
This makes the code simpler and more efficient, since searching for a key in a HashMap takes expected constant time, while searching the List takes linear time.
If you must use an ArrayList, at least leave the loop once you find the object you were looking for :
int y=in.nextInt();
for(int r=0;r<count;r++)
{
if(all.get(r).getID()==y)
{
all.get(r).display();
return; // or break; depending on where this for loop is located
}
}
Never loop over a List by index. You don't know what the internal implementation of the List is and looping might result on O(n^2) complexity.
I would suggest the following:
System.out.println("Enter the appointment ID to see the full details :");
final int y = in.nextInt();
for(final Thing thing : all) {
if(thing.getID() == y) {
thing.display();
}
}
Or, if you can use Java 8, then:
all.stream()
.filter(t -> t.getID() == y)
.findFirst()
.ifPresent(Thing::display);

Java: How do I simulate probability?

I have a set of over 100 different probabilities ranging from 0.007379 all the way to 0.913855 (These probabilities were collected from an actuary table http://www.ssa.gov/oact/STATS/table4c6.html). In Java, how can I use these probabilities to determine whether something will happen or not? Something along these lines...
public boolean prob(double probability){
if (you get lucky)
return true;
return false;
}
The Random class allows you to create a consistent set of random numbers so that every time you run the program, the same sequence of values is generated. You can also generate normally distributed random values with the Random class. I doubt you need any of that.
For what you describe, I would just use Math.random. So, given the age of a man we could write something like:
double prob = manDeathTable[age];
if( Math.random() < prob )
virtualManDiesThisYear();
First you need to create an instance of Random somewhere sensible in your program - for example when your program starts.
Random random = new Random();
Use this code to see whether an event happens:
boolean happens = random.NextDouble() < prob;
I'm not sure where that range came from. If you have a distribution in mind, I'd recommend using a Random to generate a value and get on with it.
public ProbabilityGenerator {
private double [] yourValuesHere = { 0.007379, 0.5, 0.913855 };
private Random random = new Random(System.currentTimeMillis());
public synchronized double getProbability() {
return this.yourValuesHere[this.random.nextInt(yourValuesHere.length));
}
}

Categories

Resources