Java: Generating "00" as a possible Math.random output - java

I'm creating a "roulette wheel" for a programming class assignment. This wheel generates random numbers from 0 to 36 using Math.random. One part of the assignment is to add "double zero" (00) as a possible output. Is it possible to do so through this equation?
spin = (int) (Math.random()*(37 - 0)) + 0;

Assuming you want 00 and 0 to be a separate output, you will need to get a String instead, as integers treat the two as the same value. An option I thought of is to use a 39th possible output. You could add this in your code below:
String getSpin() {
int spin = (int)(Math.random() * 38);
if (spin == 38) return "00";
else return Integer.toString(spin);
}

When you want to print 00 you should take 0 convert it to string and add "0" to it and print it as 00 and in the application logic use only one 0 and make the app give it double change of hitting it

"00" can be NOT integer in Java so we can use String type for "00".
I thought we can prepare String array contains numbers as string from 00 to 36, then generate random number from 0 to 37 because length of string array is 38.
And then get a value from array at position for the random number.
I coded and put it in this answer, hope it can help you.
Cheers your assignment.
public static void main(String[] args) {
// Generate numbers as String from 00 to 36
String numbers[] = new String[38];
numbers[0] = "00";
for(int i=1; i<numbers.length; i++) {
numbers[i] = Integer.toString(i-1);
}
// Generate random number
int min = 0;
int max = numbers.length - 1;
int randomNum = min + (int)(Math.random() * ((max - min) + 1));
// Return number at a position of randomNum
System.out.println("Output: " + numbers[randomNum]);
}

Related

Printing out 3 of numbers in java

The output value is 100000 to 10 random natural numbers
What should I do to print out only from the right end to the third?
And if you print it out with multiple of ten, an error appears
so, if we get a multiple of 10, i want to put out 010 something
for example, input -> 6545 output -> 545,
input -> 27 output -> 027
and i'm using java.
pls help me
Assuming your inputs are actually ints:
System.out.printf("%03d",inputvalue%1000);
should give the result you want:
"%03d" forces output with zero padding
inputvalue%1000 calculates the remainder of division by 1000 (modulo), which will chop off all digits to the left of the three last
You can transform an Int to a String with String.valueOf(i). Then, you only have to take the 3 last characters of the string and adding 0. Because your "027" is a String, it isn't an Int
public static void main(String... args) {
Random rand = new Random();
int upperbound = 100000;
int lowerbound = 10;
int random_integer = rand.nextInt(upperbound - lowerbound) + lowerbound;
String output = String.valueOf(random_integer);
String finaloutput = output;
if (output.length() <= 3) {
for (int i = 0; i < 3 - output.length(); i++) {
finaloutput = "0" + finaloutput;
}
} else {
finaloutput = output.substring(0, 3);
}
System.out.println(random_integer + "->" + finaloutput);
}

I can generate random numbers, but not identify min and max correctly in my set of numbers

So below is a script that will generate a list of n amount of random numbers between 1-100. I need to get it to where I can also identify the max and min of the random numbers generated in the command prompt after it runs the script. I keep running into the problem where it will just duplicate the number 2 additional times. Example when n= 2: 12 12 12 43 43 43 22 22 22
I think my problem is that when I use int min = Math.min(b,b); the for loop wants to repeat that part too. But if I put it outside of the script then I no longer have the variable b to use.
int n = Integer.parseInt(args[0]);
for(int i = 0; i < n; i++)
{
int b = (int)(Math.random() * (100 - 1)) + 1;
System.out.println(b);
}
if you insist on using Math library, you should consider the first number as min and max.
int n = Integer.parseInt(args[0]);
int max = 0;
int min = 0;
for(int i = 0; i < n; i++){
int b = (int)(Math.random() * (100 - 1)) + 1;
if(i == 0){
min = b;
max = b;
}else{
min = Math.min(min,b);
max = Math.max(max,b);
}
System.out.println(b);
}
System.out.println(String.format("Min:%d , Max:%d",min,max));
The Random class can generate streams of random numbers (with
lower/upper bound).
IntSteam can be collected into IntSummaryStatistics, which provide min/max/avg/sum/count information on the streamed data.
When streaming, you can output (or process) the items over an identity function.
Combining all these results in a simple and elegant solution:
int n=Integer.parseInt(args[0]);
IntSummaryStatistics statistics = new Random()
.ints(1, 100)
.limit(n)
.map(i -> {
System.out.println(i);
return i;
}).summaryStatistics();
System.out.println("min: " + statistics.getMin());
System.out.println("max: " + statistics.getMax());
first the word script in your question means the programming language ( javascript) ?
or you mean the word script ( probably in java we call it a class or program not a script the word script is mainly used in python )
look easy fast way is to push the elements generated into an array and sort it
Vector x=new Vector();
for(int i=0;i<10;i++)
{
x.add(i,(Math.random() * (100 - 1)) + 1);
//System.out.println(x.elementAt(i));
}
Collections.sort(x);
System.out.println(x.elementAt(0));
System.out.println(x.elementAt(x.size()-1));

Java - Cant get it to work

I have been trying to finish this for a couple of hours now. My program is supposed to generate random numbers due to the users input. Then the program divide the numbers in two new even and odd arrays. I have solved the "generated random numbers" part but now i need too transfer the even and odd numbers into two new arrays.
This is what the output should look like:
How many random numbers between 0 - 999 do you want? **12**
Here are the random numbers:
145 538 56 241 954 194 681 42 876 323 2 87
These 7 numbers are even:
538 56 954 194 42 876 2
These 5 numbers are odd:
145 241 681 323 87
This is my code at the moment:
import java.util.Scanner;
public class SlumpadeTal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
}
}
}
}
NOTE that i can't use any class for this. such as Arraylist, Vector or others!
A simple solution would be to count to number of even numbers and odd numbers,
create arrays of those sizes, and once again iterate over your original array to put each number in it's place.
edit: something like this:
int evenCounter = 0;
int oddCounter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
evenCounter++;
}
else
oddCounter++;
}
}
int[] evenArray = new int[evenCounter];
int[] oddArray = new int[oddCounter];
evenCounter = 0;
oddCounter = 0;
for (int i =0; i < arrayen.length; i++){
if ((arrayen[i] % 2) == 0) {
evenArray[evenCounter] = arrayen[i];
evenCounter++;
}
else{
oddArray[oddCounter] = arrayen[i];
oddCounter++;
}
}
My solution will be divide the number into odd or even number after a number is generated. Using arraylist will be better than array because its capacity will be grow automatically and it is suitable for your case because you dont know how many even number or odd number will be generate for each time.
The if-statement you have in your code (if ((arrayen[i] % 2) == 0)) is correct.
What I suggest doing is instead of creating new arrays, create a collection type that has a dynamic length, such as an ArrayList. That way you don't have to worry about figuring out the size first, and thus don't have to iterate twice.
If you really need an array for whatever reason, you can always convert the ArrayList to an array with ArrayList#toArray(T[])

Equal Spacing In print statements

So I was just about finished with a small little program and when I ran it everything worked fine. I did have 1 small technical issue that I didnt like and it was an unevenly spaced "table" if you would. In a nutshell I want it so my outputs are aligned on both sides.
Original output:
How many numbers should be generated?
10
What is the number of values of each random draw?
1000
- 1 108
- 2 90
- 3 101
- 4 98
- 5 117
- 6 97
- 7 89
- 8 111
- 9 93
- 10 96
Code:
import java.util.Random;
import java.util.Scanner;
public class tester
{
public static void main(String[] args)
{
Random rnum = new Random();
Scanner in = new Scanner(System.in);
int x = 0;
int y = 0;
int num = 0;
int length = 0;
System.out.println("How many numbers should be generated?");
x = in.nextInt();
System.out.println("What is the number of values of each random draw?");
y = in.nextInt();
int[] roll = new int[x];
for(int i = 1; i<=y; i++){
num = rnum.nextInt(x);
roll[num] = roll[num] + 1;
}
length = (int) Math.log10(x) + 1;
for(int i = 0; i < x; i++){
System.out.println(i+1 + " " + roll[i]); //This is the code that prints the original output
/*
* This is the code I attempted that did not give the desired result
* a = i;
System.out.println(i+1);
while(Math.log10(i) < length){
System.out.print(" ");
length--;
}
System.out.print(roll[i]);*/
}
}
}
Take a look at the System.out.format (https://docs.oracle.com/javase/tutorial/essential/io/formatting.html) and in perticular the width option. This is probably what you are wanting.
Two ways to go about this:
1) As stated already, look at the System.out.format directory. It has a wide availability of methods to format your output
2) Change the spacing in a manual way, where the spacing depends on the amount of characters in the number to the left.

Integer to two digits hex in Java

I need to change a integer value into 2-digit hex value in Java.Is there any way for this.
Thanks
My biggest number will be 63 and smallest will be 0.
I want a leading zero for small values.
String.format("%02X", value);
If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().
Integer.toHexString(42);
Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)
Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)
Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):
Integer.toHexString(0x100 | 42).substring(1)
Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.
String.format("%02X", (0xFF & value));
Use Integer.toHexString(). Dont forget to pad with a leading zero if you only end up with one digit. If your integer is greater than 255 you'll get more than 2 digits.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
If you just need to print them try this:
for(int a = 0; a < 255; a++){
if( a % 16 == 0){
System.out.println();
}
System.out.printf("%02x ", a);
}
i use this to get a string representing the equivalent hex value of an integer separated by space for every byte
EX : hex val of 260 in 4 bytes = 00 00 01 04
public static String getHexValString(Integer val, int bytePercision){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
while(sb.length() < bytePercision*2){
sb.insert(0,'0');// pad with leading zero
}
int l = sb.length(); // total string length before spaces
int r = l/2; //num of rquired iterations
for (int i=1; i < r; i++){
int x = l-(2*i); //space postion
sb.insert(x, ' ');
}
return sb.toString().toUpperCase();
}
public static void main(String []args){
System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}
According to GabrielOshiro, If you want format integer to length 8, try this
String.format("0x%08X", 20) //print 0x00000014

Categories