I'm sure this is a small, stupid error that I just can't see.
I'm getting a compiling error in this code:
private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
in my length.
Compiling error is:
"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList "
How can I fix this? I do want to use Math.random();
Also not sure if this makes a difference, but this is is being done within a String method.
Thanks in advance!
if cities is of type ArrayList you have to use cities.size() instead of cities.length.
There are a couple of errors here.
First: If your method is not void is because you're gonna return something, in your method you should return a String.
Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double
Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.
So, the easier fix would be just changing the string and int for double and return it like this:
private static double setQuestions(){
double match = Math.floor(Math.random()*cities.length);
return match;
}
Remember if you want to use the double returned you should store it when you call it, like this:
double result = setQuestions();
Hope it helps!
The code has three problems:
First, the variable "cities" is an ArrayList, as the compiller error wrote. ArrayList is a Collection which implements the interface List. The size of any implementations of List is accessable by method size(). Than, you should change cities.length by cities.size() or you turn cities as array.
Second, you defined the variable "match" as an int value but method floor from Math return a double. If you really want "match" to be a int, than you can use the cast against the method floor, that is, you code become: int match = (int) Math.random()*cities.size();
Third, your method requires an String as return, than you should return the String object correctly.
Related
My question is rather simple but nonetheless I wasnt able to find an answer.
Id like to create a new Integer (or any other data type) every time a method is called like:
public void x(){
int i = 0;
int num;(plus value of i in its name eg: num1, num2, num3,...)
i++;
}
what you're thinking of is called varvars (variable variables) and Java does not support them (thank god - we have reflection)
PHP does though: http://php.net/manual/en/language.variables.variable.php
what you probably want is to put your Integers in a Collection: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
You should store your int num into the class instead of the method, this wise your variable has object escope and will have its reference anytime you call your method.
What does it mean when there are square brackets in front of double. For example double[]?
Is there any special way to use the return function when using them in a method.
For example:
public double[] MethodName(){
}
What is the type of the return value?
Square brackets [] would indicate an array. In your case of code:
public double[] MethodName(){
....
}
You have a public method MethodName which returns an array. Double indicates what type the array is, i.e. stores an array of objects of type double.
EDIT: Forgot about answering your return question. But for your line of code, MethodName would return an array of type double (which would depend on the implmentation inside the method body). Hope that helps (I'm new to Java too; climbing the SO rep ladder)
I have 3 ints named A, B, and C. These are to be multiplied with the number 52. I have a string that contains the name of which int I want to mulitply (in example below my string type == A;.
I want to know if there is anyway to make the name of the String change into the name of the object/int that I wish to use.
What I have right now:
public class MultiplySomeNumbers{
int A = 100;
int B = 200;
int C = 300;
String type = "A";
final int multiplied = 52;
public int multiply(String type){
return multiplied* ____ //What goes here?
}
}
I DON'T want to do anything like this:
public int multiply(String type){
if(type.equalsIgnoreCase("A"){
return multiplied*A;
}else if(type.equalsIgnoreCase("B"){
...
Any help would be greatly appreciated!
No, that is not possible (maybe with Reflection, but it's still a no-go). Every single situation where you think you might need this does not need it.
There are several issues, but here are a few:
No intellisense for those generated variables
Very unclear code
Ambiguous naming (what if you create a new variable that happens to have the same name as a generated one?)
etc etc etc
You will have to go with your second option.
We might be able to provide a different solution, but the question is rather unclear as it is right now. Perhaps you could expand a little so we can help you better.
Although there may be a way to do this with reflection, it's probably a really bad idea. If you really can't just pass in the value, but want to specify a limited set of constants by which you can multiply, I'd recommend creating an enumerated type.
Taking your same example, but using an enum instead of trying to look up constants by name, would look something like this:
public class MultiplySomeNumbers{
public enum Type {
A(100),
B(200),
C(300);
private final int value;
private Type(int value) {
this.value = value;
}
public final int getValue() {
return value;
}
}
Type type = Type.A;
final int multiplied = 52;
public int multiply(Type type){
return multiplied * type.getValue();
}
}
While there is nothing wrong with using an enum for this solution, it may not be the most flexible solution. Enums are, by design, effectively immutable ... they are intended to have the sense of constants. If you wish to change the value of a variable by multiplying its value by 52, then this is not possible with enums.
What I think you really should do is use a HashMap. A Map is a key / value pair.
The key is the "variable's name"; a String quantity
The value is the "variable's current value"; an Integer quantity (not int!)
Your Map can be declared like this:
Map<String, Integer> myVariables = new HashMap<String, Integer>();
then to load your variables into the map, you simply call the Map's put() method:
myVariables.put("A", Integer.valueOf(100));
myVariables.put("B", Integer.valueOf(200));
myVariables.put("C", Integer.valueOf(300));
Retrieving the value of a variable is as simple as using the get() method with your variable name as the key:
int val = myVariables.get("A").intValue();
Notice that I have chosen to box and unbox the primitive int values myself rather than rely on autoboxing. This is just a personal choice. It does trade off conciseness, but I'd rather see what's actually happening.
In my opinion, using reflection to determine a class field to access dynamically at run time is wholly unsatisfactory and should be avoided ... most especially since using the Java Collections API enables a statically typed, type safe solution that can be checked at compile time.
You can't check for a variable's name. For more information look here, there are some good answers:
Java Reflection: How to get the name of a variable?
But maybe a HashMap can help you, where you store "A", "B", "C" as keys and the respective numbers as value.
edit: Okay, maybe with something like this http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html it could be possible.
I want to parse some Strings (they include some numbers) with same format but different number kind and set these number to their related array. for example having this string: " "positions":[[35.23,436.34],[23.5, 7.1]] I want to put these number into a float array named "this"! and for this string" "indices":[[23,4],[2,1]]" I want to put them into an integer array named "that"!
To do so, I've wrote a generic function with this declaration:
private <E extends Number> voidfunc(ArrayList<E> array, String JSON){
.
.
array.add((E) NumberFormat.getInstance().parse(JSON.substring(...)));
.
.
}
this works well and put numbers into array correctly but later, in somewhere in my app I get a "class cast exception. Can not cast Double to Float" trying to do this:
floatArray[i] = temp.get(i);
temp have defined as a float arraylist and have filled with above function.
can anybody tell me why it is so, and how can I solve that? I really appreciate that.
In your example, E is type parameter of generic method. This type is not known at run time, so cast to this type done with (E) is fake and compiler most probably reported warning at this line. JVM does not check type compatibility during this cast, so it is possible that value of incompatible type will get into the list. For example, value of Double type may be stored in List<Float>. Later, when you try to extract value form the list and cast it to Float, ClassCastException will occur.
You probably need to change your code like this:
private void func (ArrayList <? super Double> array, String JSON)
{
...
array.add (NumberFormat.getInstance ().parse (JSON.substring (...)));
...
}
ArrayList <Number> temp = new ArrayList ();
func (temp, json);
floatArray [i] = temp.get (i).floatValue ();
Try with:
floatArray[i] = ((Double) temp.get(i)).floatValue();
I've got a problem.
I'm trying to compare a String and a int but can't seem to get working.
What am I doing wrong?
Getting this from Eclipse:
The type of the expression must be an array type but it resolved to List
int numberOfMoves;
List<String> highscoreLinkedList = new LinkedList<String>();
if (moves < Integer.parseInt(highscoreLinkedList[2])){
highscoreLinkedList[2] = Integer.toString(moves);
highscoreLinkedList[1] = name;
}
This is for a highscore textfile for a game I'm making. The String at index 2 is a number of moves and the int moves is also a number of moves.
You cannot access a list element using highscoreLinkedList[2] - that syntax is reserved for arrays. To access a list you have to use the get() method, i.e. highscoreLinkedList.get(2)
You are trying to treat list as an array, but the only way to access elements of the is through calling get() method. Your code does not compile.
Lists don't work the same way as arrays in Java. To access a certain element, you have to use the get() method, and to get the element, you need to use set(), like so:
// you have highscoreLinkedList[2], it should be:
highscoreLinkedList.get(2);
// you have highscoreLinkedList[2] = ..., it should be:
highscoreLinkedList.set(2, Integer.toString(moves));
You can see all of the methods for LinkedList here.