I have a lot of Strings, like l1 or l23.
Now I want to print out a random string, e.g. l3.
I have already written code for a random number:
int r = 1 + (int)(Math.random() * ((30 - 1) + 1));
So, now I want to print a string which's variable name is the letter l plus the random integer r.
Is this possible?
You can use an array
long[] l = new long[30];
int r = // 1 to 29;
System.out.println("l" + r + ": " + l[r]);
You can use array. Index can be choosen in random manner:
System.out.println(l[random.nextInt(30)]);
Related
I am writing a program where I have strings of 9 bits of "0" and "1" to convert to exponent (taking each index and doing 2 ^ n from right to left).
example: ["1","0","1"] = 2^2 + 0^1 + 2^0
I know this is wrong because of the errors I am getting but am confused what to do which will calculate it in an efficient manner.
expoBefore = (strNum.charAt(9)) * 1 + (strNum.charAt(8)) * 2 + (strNum.charAt(7)) * 4 + (strNum.charAt(6)) * 8 + (strNum.charAt(5)) * 16 + (strNum.charAt(4)) * 32 + (strNum.charAt(3)) * 64 + (strNum.charAt(8)) * 128;
for example for one of the strings I am passing through [11111111] I want it to add 1 * 2^0 + 1 * 2 ^1 + 1 * 2^2.....etc
Clarification edit:
What is a more efficient way of converting a string of 0's and 1's to an integer?
You're trying to multiply a character's ascii value with an integer.
You must take the integer value of this character and then multiply it with another integer. Hope this helps.
String str = "111";
int x = Character.getNumericValue(str.charAt(0));
int y = Character.getNumericValue(str.charAt(1));
int z = Character.getNumericValue(str.charAt(2));
System.out.println(x + y + z);
Output:
3
You need to use a loop.
Iterate over the binary string. For each character, add 2^x to an accumulator if the bit is set (where x is the position of the bit), otherwise, add 0.
String binary = "11111111";
int number = 0;
for(int i = binary.length() - 1; i >= 0; i--) {
char c = binary.charAt(i);
number += Integer.parseInt(c + "") * Math.pow(2, binary.length() - i - 1);
}
System.out.println(number); // prints 255
How to convert binary to decimal
Just use a for loop and increment down to miniplate each number
It is very inefficient to use Math.pow(2, i) in a loop.
Faster to keep the previous value and multiply by 2 each time through (code untested):
int ip = 1;
int sum = 0;
for ( int i = binary.length -1; i >= 0) {
if ( binary.charAt(i) == '1' ) {
sum += ip;
}
ip *= 2;
}
You may want to use long ints if the number gets large.
Also, be sure to check that binary contains only zeroes and ones.
I have a small problem when trying to generate a random string with random size (between 3 and 20). I have an array arr with all characters from a (lowercase) to Z (uppercase). I then generate a random length arrLength for a second array arr2, which will be containing some randomly selected chars.
My issue is that the letter 'a' (lowercase) never appears in my randomly generated strings. I think that the mistake might be inside the for loop, but I have failed to see it so far. Maybe it has something to do with (int) casting or Math.floor rounding?
char[] arr = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
int arrLength = (int) (Math.floor((Math.random() * ((17 - 3) + 1)) + 3));
char[] arr2 = new char[arrLength];
String str = "";
for(int i=0;i<arrLength;i++) {
char num = arr[(int) (Math.floor(Math.random() * (50) + 1))];
arr2[i] = num;
}
Instead of the magic constant 50 use arr.length (note there are more than 50 characters in the array) and leave out the +1 as it makes the lowest number you can get to 1 and array indices start at 0 in Java.
I have to make a Poker Dice game for class. I am able to successfully random five numbers 1 to 6 (to resemble rolling a die five times). However, I need to show "Nine" for 1, "Ten" for two, etc. I am using an array to hold the numbers. I can't seem to figure out how to assign a string output for each int.
public static void main(String[] args) {
int[] player = new int[5];
String[] cards = new String[] {"Nine", "Ten", "Jack", "Queen", "King", "Ace"};
System.out.println("User: " + playerHand(player, cards));
}
public static String playerHand(int[] player, String[] cards) {
String hand = "";
for (int i = 0; i < player.length; i++) {
player[i] = (int) (Math.random() * (6 - 1) + 1);
hand += player[i] + " ";
}
return hand;
}
You've put your strings in an array, so you just add an element from the array to your hand string:
hand += cards[player[i]] + " ";
There is, however, still a problem with your code. You obtain the random numbers as follows:
player[i] = (int) (Math.random() * (6 - 1) + 1);
You probably expect this to be a number from 1 to 6. However, Math.random() returns a double from 0 (inclusive) to 1 (exclusive). That means that player[i] will never be assigned 6. This error kind of solves another error: since Java arrays are zero-based, the element with index 6 does not exist. (Thus, if 6 would have been chosen, your program would have aborted with an error message.) But still, the number 0 and thus the word "Nine" will never appear in your solution. So you have to change the two lines to:
hand += cards[player[i] - 1] + " ";
and
player[i] = (int) (Math.random() * 6 + 1);
respectively.
Consider making the cards array a static class member; then you don't need to pass the array to the playerHand method as an argument.
You might use a switch block
switch(array[i]){
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
etc...
I'm new to programming in general so I'm trying to be as specific as possible in this question.
There's this book that I'm doing some exercises on. I managed to do more than half of what they say, but it's just one input that I have been struggling to find out.
I'll write the question and thereafter my code,
"Write an application that creates and prints a random phone number of the form XXX-XXX-XXXX. Include the dashes in the output. Do not let the first three digits contain an 8 or 9 (but don't be more restrictive than that), and make sure that the second set of three digits is not greater than 742. Hint: Think through the easiest way to construct the phone number. Each digit does not have to be determined separately."
OK, the highlighted sentence is what I'm looking at.
Here's my code:
import java.util.Random;
public class PP33 {
public static void main (String[] args) {
Random rand = new Random();
int num1, num2, num3;
num1 = rand.nextInt (900) + 100;
num2 = rand.nextInt (643) + 100;
num3 = rand.nextInt (9000) + 1000;
System.out.println(num1+"-"+num2+"-"+num3);
}
}
How am I suppose to do this? I'm on chapter 3 so we have not yet discussed if statements etcetera, but Aliases, String class, Packages, Import declaration, Random Class, Math Class, Formatting output (decimal- & numberFormat), Printf, Enumeration & Wrapper classes + autoboxing. So consider answer the question based only on these assumptions, please.
The code doesn't have any errors.
Thank you!
Seeing as this appears to be homework I feel like an explanation of what is happening should be given.
You have three sets of numbers you need to generate.
The first number has the most requirements. It has to be greater than 100 but not contain an 8 or 9.
You ensure it will always be greater than 100 by using:
(rand.nextInt(7)+1) * 100.
This says, generate a random number between 0 and 6. Add 1 to that number to ensure that it can never be 0. So if it picks 0, +1 is added making it 1. If it picks 6, +1 is added making it 7, etc. This satisfies rule #1 and rule #2.
You ensure the first number never has an 8 or 9.
(rand.nextInt(8) * 10) + rand.nextInt(8)
Genreate a random number from 0-7. The *10 makes sure it will be in the tenth position while the last one places the number in the last position.
Instead of trying to fix the other answer as it also uses DecimalFormat incorrectly.
package stackoverflow_4574713;
import java.text.DecimalFormat;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int num1 = (rand.nextInt(7) + 1) * 100 + (rand.nextInt(8) * 10) + rand.nextInt(8);
int num2 = rand.nextInt(743);
int num3 = rand.nextInt(10000);
DecimalFormat df3 = new DecimalFormat("000"); // 3 zeros
DecimalFormat df4 = new DecimalFormat("0000"); // 4 zeros
String phoneNumber = df3.format(num1) + "-" + df3.format(num2) + "-" + df4.format(num3);
System.out.println(phoneNumber);
}
}
Output:
662-492-1168
For the first three digits, you need to generate each digit separately. See variables i1, i2, and i3 below.
For the three digits, any number between 0 and 741 should work.
For the final set of four digits, any number between 0 and 9999 should work.
The trick here is how you format the output. You could do it with a NumberFormat object, but I chose to do it with the String.format() method. In it, you specify how you want each number to be formatted. So, I used the format string "%d%d%d-%03d-%04d". The %d inserts a base-10 formatted integer into the string. The %03d makes sure that it is three characters wide and that any additional space is left-padded with a 0. In other words, 4 is formatted as "004" and 27 is formatted as "027". The %04d works similarly, except it is four characters wide.
Here's how you put it all together.
Random r = new Random();
int i1 = r.nextInt(8); // returns random number between 0 and 7
int i2 = r.nextInt(8);
int i3 = r.nextInt(8);
int i4 = r.nextInt(742); // returns random number between 0 and 741
int i5 = r.nextInt(10000); // returns random number between 0 and 9999
String phoneNumber = String.format("%d%d%d-%03d-%04d", i1, i2, i3, i4, i5);
System.out.println(phoneNumber);`
Hmm, just a really simple idea to change this to
num1 = rand.nextInt(8)*100 + rand.nextInt(8)*10 + rand.nextInt(8);
num2 = rand.nextInt(743);
For easier output you may use DecimalFormat
DecimalFormat df3 = new DecimalFormat ( "000" ); // 3 zeros
DecimalFormat df4 = new DecimalFormat ( "0000" ); // 4 zeros
System.out.println(df3.format(num1)+"-"+df3.format(num2)+"-"+df4.format(num3));
I had this same question as the first assignment for my Java class, with the caveat that we could only use the methods that we have learned in class up to that point. Therefore, we could not use the .format method. Here is what I came up with:
import java.util.Random;
/**
*
* #author
*/
public class Randnum {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Random num = new Random();
int num0, num1, num2, num3, num4, num5, num6, num7;
num0 = num.nextInt(7) + 1;
num1 = num.nextInt(8);
num2 = num.nextInt(8);
num3 = num.nextInt(643) + 101;
num4 = num.nextInt(10);
num5 = num.nextInt(10);
num6 = num.nextInt(10);
num7 = num.nextInt(10);
String randnum= "A random phone number: ";
System.out.print (randnum);
System.out.print (num0);
System.out.print (num1);
System.out.print (num2);
System.out.print ("-" + num3 + "-");
System.out.print (num4);
System.out.print (num5);
System.out.print (num6);
System.out.println (num7);
}
}
You might also want to check that the prefix is not 555
var num1 = Math.floor(Math.random()*7) + 1;
var num2 = Math.floor(Math.random()*8);
var num3 = Math.floor(Math.random()*8);
var part2 = Math.floor(Math.random()*742);
if(part2 < 100){
part2 = "0" + part2;
}else if (part2 < 10) {
part2= "00" + part2;
}else{
part2 = part2;
}
var part3 = Math.floor(Math.random()*10000);
if(part3 < 1000){
part3 = "0" + part3;
}else if (part3 < 100) {
part3 = "00"+ part3;
}else if(part3 < 10){
part3 = "000" + part3;
}else{
part3 = part3;
}
document.getElementById("demo").innerHTML= " " + num1 + num2 + num3 + "-" + part2 + "-" + part3;
public String GetRandomPhone(){
return String.format("(%03d) %03d-%04d",
(int) Math.floor(999*Math.random()),
(int) Math.floor(999*Math.random()),
(int) Math.floor(9999*Math.random()));
}
I'm very new to java and am working on my first Android app. I am using the webview demo as a template. I am trying to generate a random integer between 1 and 12 and then call a certain javascript function based on the result. Here's what I have:
int number = 1 + (int)(Math.random() * ((12 - 1) + 1));
number = (int) Math.floor(number);
String nextQuote = "javascript:wave" + number + "()";
mWebView.loadUrl(nextQuote);
So mWebView.loadUrl(nextQuote) will be the same as something like mWebView.loadUrl("javascript:wave1()")
I just want to know if what I have here is correct and will work the way I think it will. The application isn't responding as expected and I suspect this bit of code is the culprit.
The key statement are as follows:
int number = 1 + (int)(Math.random() * ((12 - 1) + 1));
number = (int) Math.floor(number);
The first statement gives the answer you need, but in a rather cumbersome way. Lets step through what happens:
((12 - 1) + 1) is 12. (This is evaluated at compile time ... )
Math.random() gives a double in the range 0.0D <= rd < 1.0D.
Math.random() * 12 gives a double in the range 0.0D <= rd < 12.0D.
The (int) cast converts the double to an int by rounding towards zero. In other words (int)(Math.random() * 12) will be a integer in the range 0 <= ri <= 11.
Finally you add 1 giving an integer in the range 1 <= ri <= 12.
W**5 :-)
A simpler and clearer version would be:
private static Random rand = new Random();
...
int number = 1 + rand.nextInt(12);
The second statement is (as far as I can tell) a noop. It implicitly converts an int to a double, gets the double form of largest integer that is less or equal to that double, and converts that back to an int. The result will always be identical to the original int.
Documention of Java Random Class
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Random.html
A good way to do this.
Random rand = new Random(); // does not have to be static but can be.
int number = rand.nextInt(12) + 1; // 1 to 12 Must use 12
// Range is 0-11 add 1: 1-12
String nextQuote = "javascript:wave" + number + "()";
mWebView.loadUrl(nextQuote);
** from Java doc ** Method: public int nextInt(int n)
"Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)"