How to get a String array to equal another String array - java

String[] mySecret;
String[] colours = {"R","Y","Bl","G","O","Pu","Pi","Br"};
public void getuserInput() {
numColours = min + (int)(Math.random() * ((max-min) +1));
numPegs = min + (int)(Math.random() * ((max-min) +1));
}
public void setSecret() {
for (i=0; i<numColours; i++) {
mySecret[i] = colours[new Random().nextInt(colours.length)];
}
}
This is a small part of my code. When I run this, I get a NullPointerException. Is there any other way to get mySecret which is meant to be a string array to contain a specified number of colours but chosen at random from the colours string array. Any help would be appreciated, thanks.

You shoud initialize your array mySecret like this:
String[] colours = {"R","Y","Bl","G","O","Pu","Pi","Br"};
String[] mySecret = new String[colours.length];

You need to read up on the Java language a bit more.
public void setSecret() {
mySecret = new String[numColours];
for ( int i=0; i<numColours; i++) {
mySecret[i] = colours[new Random().nextInt(colours.length)];
}
}

Related

Java - How can I print out a value as a word after BubbleSorting?

I used integer so that I can write out Numbers as an input, but now i would like the programm to output the number as Words again.
public class KartenSort {
private int zwei = 2;
private int drei = 3;
private int vier = 4;
private int fuenf = 5;
public int[] liste ={drei,zwei,fuenf,vier};
public int[] sortieren(){
int unsortiert;
for(int sortiert = 0; sortiert < liste.length -1; sortiert++){
if(liste[sortiert] < liste[sortiert+1]){
continue;
}
unsortiert = liste[sortiert];
liste[sortiert] = liste[sortiert+1];
liste[sortiert+1] = unsortiert;
sortieren();
}
return liste;
}
public static void main (String[] args){
KartenSort bs = new KartenSort();
int[] array = bs.sortieren();
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(sortiert + 1 +":" + array[sortiert]);
}
}
}
thank you in advance
In your case you could use Map
Map<Integer,String> numbers = new HashMap<>();
numbers.put(2, "zwei");
numbers.put(3, "drei");
numbers.put(4, "vier");
numbers.put(5, "funf");
for (int sortiert=0;sortiert < array.length; sortiert++){
System.out.println(numbers.get(array[sorted]));
}
The array liste does not contain Strings (what you probably mean by "words").
I think, you wanted to have something like
String[] liste = ...
Your version of liste is
int[] liste = ...
This means it contains integer numbers, not strings. Although you write
int[] liste = {drei,zwei, ...}
the content of the array are still integer numbers. drei is a variable and you will get the value of the variable into the list. The value of drei is the integer value 1.
When you have the value 1 there is no reference back to the name of the variable that had hold it some time ago.

How to convert ArrayList<String> to int[] in Java

I read Bert Bates and Katie Sierra's book Java and have a problem.
The Task: to make the game "Battleship" with 3 classes via using ArrayList.
Error: the method setLocationCells(ArrayList < String >) in the type
SimpleDotCom is not applicable for the arguments (int[])
I understand that ArrayList only will hold objects and never primatives. So handing over the list of locations (which are int's) to the ArrayList won't work because they are primatives. But how can I fix it?
Code:
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("Enter the number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("Kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class SimpleDotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
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;
}
}
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null;
} catch (IOException e) {
System.out.println("IOException:" + e);
}
return inputLine;
}
}
convert ArrayList to int[] in Java
Reason for Basic Solution
Here's a simple example of converting ArrayList<String> to int[] in Java. I think it's better to give you an example not specific to your question, so you can observe the concept and learn.
Step by Step
If we have an ArrayList<String> defined below
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
Then the easiest solution for a beginner would be to loop through each list item and add to a new array. This is because the elements of the list are type String, but you need type int.
We start by creating a new array of the same size as the List
int[] numbers = new int[numbersInAList.size()];
We then iterate through the list
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
Then inside the loop we start by casting the String to int
int num = Integer.parseInt(numbersInAList.get(ndx));
But there's a problem. We don't always know the String will contain a numeric value. Integer.parseInt throws an exception for this reason, so we need to handle this case. For our example we'll just print a message and skip the value.
try {
int num = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
We want this new num to be placed in an array, so we'll place it inside the array we defined
numbers[ndx] = num;
or combine the last two steps
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
Final Result
If we combine all of the code from "Step by Step", we get the following
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
int[] numbers = new int[numbersInAList.size()];
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
try {
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
}
Important Considerations
Note there are more elegant solutions, such as using Java 8 streams. Also, it's typically discouraged to store ints as Strings, but it can happen, such as reading input.
I can't see where you call setLocationCells(ArrayList<String>) in your code, but if the only problem is storing integers into an ArrayList there is a solution:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
It is true that you can't use primitive types as generics, but you can use the Java wrapper types (in this case, java.lang.Integer).

How to assign each column of an array to a specific variable?

Is this the right way of assigning each column in my data file to a particular variable?
public static void main(String[] args) {
//specifying the path to file
String datafile = " C:\\Users\\rez\\Desktop\\sol_2.mcmc";
//reading the file
double[][] mydata = FileReadingTools.getDoubleArray(datafile);
double P_0; //days
double M_0; // in days
double e_0;
double w_0 = Math.toRadians(0);
double[][] list = new double[3000][50];
for (int sol = 0; sol < 3000; sol++) {
list[sol][0] = P_0;
list[sol][2] = M_0;
list[sol][3] = e_0;
list[sol][4] = w_0;
System.out.println(P_0 + " " + M_0);
}
I believe you have swapped the left and right with your variable assignments. You want to assign the values from the array. Also, please use more descriptive variable names. I think you wanted something like,
for (int sol = 0; sol < mydata.length; sol++) {
P_0 = mydata[sol][0]; // mydata v-- as noted in the comments. ---v
M_0 = mydata[sol][2];
e_0 = mydata[sol][3];
w_0 = mydata[sol][4];
Alternatively, you could use printf and access the array directly with something like
System.out.printf("%.2f %.2f", mydata[sol][0], mydata[sol][2]);

Java ME String array without size

I have a simple question ?
String[] names = null ;
names[0] = "Hello"
I'm getting an error ..
How could I instantiate array as I don't know the the size limit... help me
Use ArrayList<String> when you don't know in advance the array size. What you are doing here is invalid (trying to access a null object).
Edit: as you can't use Vector and ArrayList, you'll have to roll you own implementation of dynamic array. You'll find one almost ready with some explanations on algolist.net. Simply replace the int storage by a String storage.
// Warning: not tested!
public class DynamicStringArray {
private String[] storage;
private int size;
public DynamicArray() {
storage = new String[10];
size = 0;
}
public DynamicArray(int capacity) {
storage = new String[capacity];
size = 0;
}
public void ensureCapacity(int minCapacity) {
int capacity = storage.length;
if (minCapacity > capacity) {
int newCapacity = (capacity * 3) / 2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
storage = Arrays.copyOf(storage, newCapacity);
}
}
private void pack() {
int capacity = storage.length;
if (size <= capacity / 2) {
int newCapacity = (size * 3) / 2 + 1;
storage = Arrays.copyOf(storage, newCapacity);
}
}
public void trim() {
int newCapacity = size;
storage = Arrays.copyOf(storage, newCapacity);
}
//...
}
How about this?
String[] names = new String[] { "Hello" };
Or you might also use ArrayList or StringCollection.
EDIT:
For J2ME: There was a trick posted here for dynamic array of Ints. I suppose it should possible to convert it for Strings. I have converted that example, however I didn't have J2ME emulator to test it:
public class DynamicStringArray {
private static final int CAPACITY_INCREMENT = 10;
private static final int INITIAL_CAPACITY = 10;
private final int capacityIncrement;
public int length = 0;
public String[] array;
public DynamicStringArray(int initialCapacity, int capacityIncrement) {
this.capacityIncrement = capacityIncrement;
this.array = new String[initialCapacity];
}
public DynamicStringArray() {
this(CAPACITY_INCREMENT, INITIAL_CAPACITY);
}
public int append(String str) {
final int offset = length;
if (offset == array.length) {
String[] old = array;
array = new String[offset + capacityIncrement];
System.arraycopy(old, 0, array, 0, offset);
}
array[length++] = str;
return offset;
}
public void removeElementAt(int offset) {
if (offset >= length) {
throw new ArrayIndexOutOfBoundsException("offset too big");
}
if (offset < length) {
System.arraycopy(array, offset + 1, array, offset, length - offset
- 1);
length--;
}
}
}
try
String[] names = new String[1];
names[0] = "Hello";
Use an ArrayList<String> if you don't know the size beforehand.
ArrayList<String> names = new ArrayList<String>();
names.add("hello");
names.add("another string");
...
looks like j2me has non-generic ArrayList that you could use like this.
ArrayList names = new ArrayList();
names.add("hello");
names.add("another string");
....
String name = (String) names.get(1);
How could i instantiate array as I dont know the the size limit
Sorry, that cannot be done. Arrays are of fixed size in Java, and you have to give the size when you create the array.
If you need a flexible buffer, consider using an ArrayList instead. That will grow as needed.
If you don't know the size limit (or more generally: almost always) you'll want to use a List instead of an array, because it's much more comfortable to handle.
List<String> names = new ArrayList<String>();
names.add("Hello");
The reason you're getting an exception (a NullPointerException) is that you only defined a variable to reference a String-array, but created no String array.
You'd have to initialize it like this:
String[] names = new String[10];
As you explained yo want to use it at J2ME there is no ArrayList provided for J2ME however there is an implementation here:
http://kickjava.com/src/j2me/util/ArrayList.java.htm
You can try it.
Also you should consider here too:
http://www1.j2mepolish.org/javadoc/j2me/de/enough/polish/util/ArrayList.html
As you are on J2ME and say you can't use arraylist I don't see you having any choice.
You need to choose a reasonable starting size for your array, watch the size, and if you need to add more objects than the size, copy it to a larger array.
With our constraints I cannot think of another way.
you can use with vector
Vector strings=new Vector();
strings.addElement("HELLO");
//then convert it to string array
String str[]=new String[strings.size()];
str[0]=(String)strings.get(0);
like this..
Hope this helpfull
String str[] = { "ABCde","xyZ","sdsdsdf"} ;
String str[][] = { {"ABC","abc"} ,
{"pqr","qwerTY"}
} ;

Java ArrayList<Double> as Parameter

I am currently working on a lab and would like to know how to handle the following problem which I have spent at least two hours on:
I am asked to create an ArrayList containing the values 1, 2, 3, 4 and 10. Whilst I usually never have any trouble creating an ArrayList with said values, I am having trouble this time. Should I create the ArrayList outside of the method or inside the method? Whichever way I have attempted it, I have been presented with numerous error messages. How do I add values to this ArrayList parameter? I have attempted to add values to it when calling it from the main method, but this still doesn't work. Here is the method in question.
public static double ScalesFitness(ArrayList<Double> weights){
//code emitted for illustration purposes
}
If anybody could help me it would be greatly appreciated. If any more code is required, then please let me know.
Thank you so much.
Mick.
EDIT: The code for the class in question is as follows:
import java.util.*;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
for(int i = 0; i > s.length(); i++){
CS2004.UI(0,1);
if(i == 0){
System.out.println(s + "0");
}
else if(i == 0){
System.out.println(s + "1");
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double scalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0;
double R = 0;
for(int i = 0; i < scasol.length(); i++){
if(lhs == 0){
L = L + i;
}
else{
R = R + i;
}
}
int n = scasol.length();
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
The other class file that I am using (Lab7) is:
import java.util.ArrayList;
public class Lab7 {
public static void main(String args[])
{
for(int i = 0 ; i < 10; ++i)
{
double x = CS2004.UI(-1, 1);
System.out.println(x);
}
System.out.println();
ScalesSolution s = new ScalesSolution("10101");
s.println();
}
}
you can these
1) use varargs instead of list
public static double scalesFitness(Double...weights)
so you can call this method with :
scalesFitness(1.0, 2.0, 3.0, 4.0, 10.0);
2) create the list outside your method
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
scalesFitness(weights);
Towards your initial posting, this would work:
scalesFitness (new ArrayList<Double> (Arrays.asList (new Double [] {1.0, 2.0, 4.0, 10.0})));
You may explicitly list the values in Array form, but
you have to use 1.0 instead of 1, to indicate doubles
you have to prefix it with new Double [] to make an Array, and an Array not just of doubles
Arrays.asList() creates a form of List, but not an ArrayList, but
fortunately, ArrayList accepts a Collection as initial parameter in its constructor.
So with nearly no boilerplate, you're done. :)
If you can rewrite scalesFitness that would be of course a bit more easy. List<Double> as parameter is already an improvement.
Should I create the ArrayList outside of the method or inside the method?
The ArrayList is a parameter for the method so it need to be created outside the method, before you invoke the method.
You need to import ArrayList in the file that includes your methods. This is probably solved but that's the issue I was encountering.

Categories