Make a string variable from a random array - java

import java.util.Random;
public class DotComTestDrive {
public static void main(String [] args) {
String stringOfWords[] = {"Do", "You", "Like", "Me"};
boolean correctOrder = true;
int numberOfResets = 0;
String correctString;
String realString[];
while (correctOrder == true) {
System.out.println();
for (int x = 0 ; x < 4 ; x++) {
int rand = (int) (Math.random() * 4);
System.out.print(stringOfWords[rand]);
System.out.print(" ");
numberOfResets++;
}
// Place If statement here to change correctOrder to false when the new string is "Do You Like Me "
}
System.out.println(numberOfResets);
}
}
My main goal for this is to try and get the new random four words that
it prints out into an String[] so I can then use an If statement to
see if the string matches the original. Then I will make the boolean
"correctOrder" be false, ending the loop.
I know it is simple and sorry if its not a great or clear question.
Just trying to learn the basics and anything helps, thanks!

What I would suggest is to use a list and shuffle it every time you loop.
Map<K,V> map = xxxx;
List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(map.entrySet());
// each time you want a different order.
Collections.shuffle(list);
for(Map.Entry<K, V> entry: list) { /* ... */ }

Assuming that you want to put these Strings in realString, you should do as follows/
initialise this Array
assign one of its elements in your for loop.
For example:
String realString[] = new String[4];
while(correctOrder == true){
for(int x = 0; x < 4; x++){
int rand = (int) (Math.random()*4);
System.out.print(stringOfWords[rand]);
System.out.print(" ");
realString[x] = stringOfWords[rand];
}
}
Also, since I'm at it, I'd suggest you to change a few things in your code:
no need to specify == true: a boolean variable can be tested by itself.
the use of the Random class (instead of Math one) is often preferred. You could have a final Random r = new Random() and get a random int in the range [0, 4[ by simply using r.nextInt(4)

Related

Random number and array search

I am attempting to generate an ADDITIONAL single random number and create another method that will have three parameters = the integer array, the size of the array, and the value it will be searching for in the array. It will search through the array and count how many times the value was found.It will then either print out how many times the value was found or that the value was not found. I am a bit lost and this is what I have so far which generates the random array and prints it/ asking the user if they want to restart. Thanks in advance
My code:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public void createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] number = new int[20];
createNum(number);
printNum(number);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
I should not be telling you the whole code, since this looks like a homework question.
So here are the hints:
Creating an additional random number - Not so difficult, as you have RND_GEN
int rn = RND_GEN.nextInt(10)+1; //exactly as you have been doing it.
Creating a method that takes three parameters.... Here is the method header:
void search(int[] array, int size, int val)
Body of the method? You have various search algorithms out there. Some of the most popular ones are:
linear search
binary search
So just go on, research, learn and do it yourself.

Random Data Analyzer

I'm creating a program that will generate 100 random numbers between 1 and 1000, add them to a list, and then sum up those numbers. Here's my code:
public class Iteration {
public static void main (String [] args){
private int RandomDataAnalyzer(int Rando) {
Random rand = new Random();
List<Integer> NumList = new ArrayList<Integer>();
for (int i=0;i<=100;i++){
Rando = rand.nextInt(1001);
NumList.add(Rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
Rando = rand.nextInt(100);
sum = sum + Rando;
}
return sum;
}
}
}
And here's my errors:
H:\Java\Iteration.java:12: error: illegal start of expression
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
^
H:\Java\Iteration.java:12: error: ';' expected
private int RandomDataAnalyzer(int Rando) {
Any help, please?
You can't define a method inside another method. Close your main method first, then start RandomDataAnalyzer:
public static void main(String[] args) {
// Contents of main.
}
public int RandomDataAnalyzer(int Rando) {
// Contents of RandomDataAnalyzer.
}
I'm going to assume that this isn't a homework problem and that you're learning Java on your own. If I'm wrong, shame on me for giving a working version. But my impression is that you'll learn from this:
public class gpaCalc
{
static Random rand;
static int rando;
public static void main(String[] args)
{
ArrayList<Integer> NumList = new ArrayList<>(); // use ArrayList
for (int i=0;i<=100;i++)
{
rand = new Random();
rando = rand.nextInt(1001);
NumList.add(rando);
}
int sum = 0;
for (int i=0; i<100; i++)
{
rando = NumList.get(i); // get is "opposite" of put--get the value put into the list earlier
sum = sum + rando;
}
System.out.println(sum);
}
}
There doesn't seem to be a need for a separate method called randomDataAnalyzer.
Welcome to StackOverflow.
Let's begin with the first issue: randomDataAnalyzer is being defined inside main method. Which is wrong, you should be actually defining it at the same level.
Taken into consideration, you should also add the static word before this function because this method is part of the class, and not of the elements. It's not necessary to create a new element of the class 'Iteration' for using a simple method.
Last, but not least, you are looping through the arraylist incorrectly. You are not even calling it. As you will see now:
import java.util.*;
public class Iteration
{
public static void main(String[] args)
{
ArrayList<int> numberList = new ArrayList<int>(); // we define the arraylist
for (int i = 0; i < 100; i++)
{
numberList.add(new Random().nextInt(1001)); // we add a random number to the list
}
// finally, after the 100 values were added..
System.out.println(randomDataAnalyzer(numberList)); // we show the output
}
public static int randomDataAnalyzer(ArrayList<int> list) // we will send this function an arraylist which will get the Σ.
{
int sum = 0;
for (int value : list) // this is how we loop through foreach value in the list
{
sum += value; // which means sum = sum + value.
}
return sum; // after looping and summing up, here'll be the result
}
}
I hope this was what you were looking for.
Here's a working version. Note the changes to your original:
Don't define methods inside methods: it is illegal syntax.
Rando, NumList: the naming conventions are to start classes, interfaces, enums (i.e. types) with a capital letter, and methods, fields, and variables with a lowercase case letter;
Removed the int Rando parameter alltogether: it's value was never used (it was only assigned to)
Use the values from numList rather than generating new numbers.
Added a method illustrating that the use of such a list is not needed in this case; the 'list' of 1000 numbers is still present, but only conceptually.
import java.util.*;
public class Iteration {
public static void main (String [] args) {
int sum = new Iteration().randomDataAnalyzer();
System.out.println(sum);
}
private int randomDataAnalyzer() {
Random rand = new Random();
List<Integer> numList = new ArrayList<Integer>();
for ( int i=0; i<100; i++ )
{
numList.add( 1 + rand.nextInt(1000) );
}
int sum = 0;
for ( int i=0; i<numList.size(); i++ )
{
sum = sum + numList.get(i);
}
return sum;
}
// Note that the above method has the same effect as this one:
private int moreEfficient() {
Random rand = new Random();
int sum = 0;
for ( int i=0; i < 100; i++)
sum += 1 + rand.nextInt(1000);
return sum;
}
}

Counting the number of an element in an array?

So for an assignment in my class, we have a lab where we have to write code that will do three things:
generate an array of 50 random numbers from 0-9.
Return how many 8's appear in the array.
Return the number of runs in the array.
We were given a .java file to start out with that is this:
package ArrayOfInts;
public class ArrayOfInts {
private int [] intArray;
private int eights;
private int runs;
//Sets intArray to the parameter and initializes all other variables
public ArrayOfInts(int [] x){
}
//Returns how many 8's are in the array.
public int findTheEights(){
return eights;
}
//Returns the number of runs in the array.
public int countTheRuns(){
return runs;
}
}
The code I've written so far is this:
package ArrayOfInts;
public class ArrayOfIntsTester {
public static void main(String [] args){
int [] testArray = new int [50];
for(int i = 0; i < testArray.length; i++){
int x = (int)(Math.random()*9);
testArray[i]= x;
System.out.print(x + ", ");
}
System.out.println();
ArrayOfInts test = new ArrayOfInts(testArray);
System.out.println(test.findTheEights());
System.out.println(test.countTheRuns());
}
}
I honestly have no idea where to start with this. Help?? The code I've written generates the correct type of array, but I don't know how to count what I need to count for it.
For the eights: iterate over the array and do eights++ everytime you find an eight.
if (testArray[i] == 8){
eights++
}
Here is some pseudo code to help you count the eights:
numberOfEights = 0;
for each element in testArray{
if (element equals 8) {
numberOfEights = nnumberOfEight + 1
} else {
nothing to do
}
}
return numberOfEights
Try to turn this to java code.
For the other part, i don't understand what is your runs.
//To count number of eights, iterate through array with a counter and increment it when we see an 8
public ArrayOfInts(int [] x){
eights = 0; //reset our count
for (int currentInt : intArray)
{
if (currentInt == 8)
eights++;
}
//Process runs here
}
To count the number of eight just use another variable which is initialized to 0 , like this :-
int c=0;
for (i=0;i<testArray.length;i++)
{
if (testArray[i] == 8)
{
c++;
}
}
Now your c has the number of 8's present in your array you cant print its value.
--> If that's what you are trying to ask
first initialize the array in constructor
public ArrayOfInts(int [] x){
intArray=x;
}
initialize the eights to 0
private int eights=0;
then update your count method
public int findTheEights(){
for(int current:intArray)
{
if(current==8){ eights++;}
}
return eights;
}
In JavaScript you could do it like the following example.
Counting of eights can be done directly at the initializaion of the array.
And if I understand you right, you'd like to count the instances of the object with the countTheRuns(). That can be done with a class variable.
If you'd like to play with the code, you'll find it here at jsFiddle.
/*So for an assignment in my class, we have a lab where we have to write code that will do three things:
generate an array of 50 random numbers from 0-9.
Return how many 8's appear in the array.
Return the number of runs in the array.
*/
(function() {
var MAX_RANDOM = 50;
var NUM_RANGE = 9; // 0 to 9
function ArrayOfInts() {
this.eights = 0;
this.numbers = [];
this.init();
// class variabe run_counter
ArrayOfInts.run_counter = (ArrayOfInts.run_counter || 0) +1;
this.getNumbers = function() {
return this.numbers;
};
this.getEights = function() {
return this.eights;
};
}
ArrayOfInts.prototype.init = function() {
for (var i=0; i< MAX_RANDOM; i++) {
var randNum = Math.floor(Math.random()*(NUM_RANGE+1));
this.numbers.push(randNum);
if (randNum == 8) this.eights++;
}
};
// demo usage code ---------------------
var array = new ArrayOfInts();
var array2 = new ArrayOfInts();
document.getElementById('output').innerHTML = array.getNumbers();
console.log(array.getNumbers());
document.getElementById('output').innerHTML += '<br/>The array has the following no. of eights: ' + array.getEights();
document.getElementById('output').innerHTML += '<br/>The number generation ran ' + ArrayOfInts.run_counter + ' times.';
})();
<div id="output"></div>

Java - Printing Array List of String Arrays

I am pretty new to Java and had a question. This is homework, so I would not like any outright answers. Thanks!
I'm working on a genetic algorithm for playing poker. I wanted to create an arrayList of string arrays. The string arrays would hold moves for each possible hand during a round. What I want to do right now to make sure it is working is run my method and print out the results. Here are my practice classes (this is only a small part of the assignment):::
import java.util.ArrayList;
import java.util.Arrays;
public class Play
{
GeneticAlg start;
ArrayList<Object> pop;
public static void main(String[] args)
{
GeneticAlg start = new GeneticAlg();
ArrayList<String[]> pop = start.initializePopulation();
for(String[] arr: pop)
{
System.out.println(Arrays.toString(arr));
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class GeneticAlg
{
ArrayList<String[]> population;
int[] populationScores;
String[] chromosome;
int generation;
int index;
public GeneticAlg()
{
}
public ArrayList<String[]> initializePopulation()
{
ArrayList<String[]> population = new ArrayList<String[]>();
for (int i = 0; i < 20; i++)
{
Random generator = new Random();
String[] choices = {"bet","raise","call","check"};
chromosome = new String[33];
for (int j = 0; j < 33; j++)
{
if (j < 6) //first and second round possible hands)
{
index = generator.nextInt((choices.length)-1);
chromosome[j] += choices[index];
}
else //third, fourth, and fifth round possible hands)
{
index = generator.nextInt(choices.length);
chromosome[j] += choices[index];
}
}
population.add(chromosome);
}
return population;
}
}
Right now, it's printing out the array, but each entry looks like this:
[nullcall, nullraise, nullbet, nullraise, nullcall, nullraise,....
I want it to just return the move without null on the front. Any advice is appreciated. Thanks!
ETA: I fixed the two lines with the concatenation error, but it is still printing "null" in front of each command. Any advice?
Code after repairing the error:
import java.util.ArrayList;
import java.util.Arrays;
public class Play
{
GeneticAlg start;
ArrayList<Object> pop;
public static void main(String[] args)
{
GeneticAlg start = new GeneticAlg();
ArrayList<String[]> pop = start.initializePopulation();
for(String[] arr: pop)
{
System.out.println(Arrays.toString(arr));
}
}
}
import java.util.ArrayList;
import java.util.Random;
public class GeneticAlg
{
ArrayList<Object> population;
String[] choices;
int[] populationScores;
String[] chromosome;
int generation;
int index;
public GeneticAlg()
{
}
public ArrayList<Object> initializePopulation()
{
population = new ArrayList<Object>();
for (int i = 0; i < 20; i++)
{
Random generator = new Random();
for (int j = 0; j < 24; j++)
{
if (j < 6) //first and second round possible hands)
{
choices[0]= "bet";
choices[1]= "raise";
choices[3]= "call";
index = generator.nextInt(choices.length);
chromosome[j] = choices[index];
}
else //third, fourth, and fifth round possible hands)
{
choices[4] = "check";
index = generator.nextInt(choices.length);
chromosome[j] = choices[index];
}
}
population.add(chromosome);
}
return population;
}
}
Arrays of objects (like Stirngs) are filled at start with null values, so doing
chromosome[j] += choices[index];
is the same as
chromosome[j] = chromosome[j] + choices[index];
which is the same as
chromosome[j] = null + choices[index];
So you are concatenating null with choices[index]; which gives you nullbet for instance.
To solve it just use = instead of +=.
Since you don't want an outright answer, look at the code that populates your String[]'s. Your printing's doing the right thing, but the Strings in the array actually are "nullbet," "nullraise," etc.
The error comes from this line here:
chromosome[j] += choices[index];
The += operator, when used with a Strings, will concatenate the right-hand string to the end of the left-hand string. In this case, it tacks on choices[index] to the existing contents of chromosome[j], which will null by default if chromosome is declared as an array of Objects.
You probably meant
chromosome[j] = choices[index];
And accidentally inserted the + because you use population.add() with your list below.
Your "fixed" code looks like it doesn't compile - you're probably still running the previous version. You don't initialize choices ("choices = new String[4]") and you're confusing its indices (0, 1, 3 and 4). Also, if you're trying to add a fourth element to the array later, don't, you can't do that with arrays. And you're assigning an ArrayList to an ArrayList without a cast. You only needed to swap += with = in your original code, it seemed fine otherwise.

Java arraylist. I need to pass random numbers to an array list and pass them to another class to check those numbers against another set of numbers

I am confused with passing ARRAYLIST values from one class to another.
I used the ARRAY in these classes before. I am changed those with ARRAYLISTS.
I have 2 classes. this class has an ARRAYLIST called "locationcells". This programs get 3 random digits from another class and get uses inputs and check if their inputs match the 3 digits. it's more like a guessing game.
import java.util.ArrayList;
class SimpleDotCom {
private ArrayList<String> locationcells;
public void setLocationcells(ArrayList<String> Locs)
{
locationcells = Locs;
}
public String CheckYourself(String StringGuess)
{
String result = " Miss";
int index = locationcells.indexOf(StringGuess);
if (index >= 0)
{
locationcells.remove(index);
if (locationcells.isEmpty())
{
result = "Kill";
}
else
{
result = "Hit";
}
}
return result;
}
}
this looks right.
Now the class with the main method:
import java.util.ArrayList;
class SimpleDotComGame {
public static void main(String[] args)
{
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
/*
this is the part I don't understand. I used to have the int array and generated random numbers and it worked well.
int randomNum = (int) (Math.random() * 5);
ArrayList<String> locations = new ArrayList<String>();
*/
theDotCom.setLocationcells(locations);
boolean isAlive = true;
while (isAlive == true)
{
String guess = helper.getUserInput("Enter a number");
String result = theDotCom.CheckYourself(guess);
numOfGuesses++;
if (result.equals("Kill"))
{
isAlive = false;
System.out.println("You took " + numOfGuesses + "guesses");
}
}
}
}
If you see the comments section above. That's the part I am getting confused. I used to have an array there. INT array. So I was able to pass the INT random numbers to the "simpledotcom" class. Now it is an arraylist with string type, I am not sure how to move forward.
Thank you all in advance,
int numericGuess = Integer.parseInt(helper.getUserInput("Enter a number"));
Also you can use a list of Integers too:
ArrayList<Integer> locations = new ArrayList<Integer>();
while(//condition){
int randomNum = (int) (Math.random() * 5);
locations.add(randomNum)
}
this way you can perform
locations.indexOf(numericGuess) or locations.contains(numericGuess)
OR
Conversely you can do,
String guess = helper.getUserInput("Enter a number");
ArrayList<String> locations = new ArrayList<String>();
while(//condition){
int randomNum = (int) (Math.random() * 5);
locations.add(String.valueOf(randomNum))
}
and check by
locations.indexOf(guess) or locations.contains(guess)
You can always transform the random int to a string by using Integer.toString() before inserting into your array list.
You can convert the String back to int using Integer.parseInt()
E.g.
for (int i = 0 ; i < 3 ; i++)
{
locations.add(Integer.toString((int)(Math.random() * 5));
}
If I understand well: add 3 Strings to the ArrayList:
ArrayList<String> locations = new ArrayList<String>();
for (i=0; i<3; i++)
{ locations.add(String.valueOf((int) (Math.random() * 5))); }
Anyway, you might refactor a little as well, starting with the extracting the above lines from the main method.
Another way might be to store your integer in a list, and convert the guesses to integers. Looks more logic to me anyway. In that case, you'll have an ArrayList. To convert a string to an integer:
int guessNumber = Integer.parseInt(guess);
or
Integer guessNumber = Integer.valueOf(guess);
Both will throw a NumberFormatException if 'guess' does not contain a parseble integer (see javadoc )
Why are you not using arrays like (apparently) you did before, by the way?

Categories

Resources