Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am a beginner. Why isEmpty() is defined an error in my question.
I trim and split a string array:
String[] items = s.trim().split("[ !,?.\\_'#]+");
I want to print
int i = (items.isEmpty()) ? 0 : items.length;
but isEmpty shows an error.
Arrays don't have isEmpty method. You need to check it yourself with items.length == 0.
Also, be aware that items is never empty:
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
String[] items is known as an array and is one of the most simple data structures in Java. There are more complicated and handy data structures like ArrayList, HashMap, etc.
The isEmpty() is a method which has been declared in the List Interface, so all the Java classes that implemented this interface have their implementation of isEmpty method. (String[] is not an implementation of List)
Note: split method always returns a non-empty array, so it is useless to to have a method like isEmpty. You can just check the length of returned value, items.length == 0
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I wonder how to get the number of items in a ShortBuffer.
I want the number of items that are really in the buffer, not the maximum capacity.
Thanks.
Buffer is not a Collection, but a (comparatively thin) wrapper around a primitive array that provides some useful methods for operating on groups of primitive values. Like a primitive array, it always contains values for each valid index.
Therefore the number of items is always equal to its capacity.
It does not keep track of which indices have already been written to since its creation. And as one major use case is to wrap an existing array while still reflecting all changes to the wrapped array, that would not even be possible to implement.
ShortBuffer holds a position that keeps track on where to put elements. You can use it to know how many elements you put in. The number of elements always equals its capacity as others mentioned.
#Test
fun testShortBuffer() {
val shortBuffer = ShortBuffer.allocate(1024)
println(shortBuffer.position()) // position 0
shortBuffer.put(1)
println(shortBuffer.position()) // position 1
shortBuffer.put(shortArrayOf(2, 3, 4))
println(shortBuffer.position()) // position 4
shortBuffer.clear()
println(shortBuffer.position()) // position 0
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
public int pray(int secondsPrayed){
int randomRecoveryValue = secondsPrayed + new Random().nextInt(3);
int actuallyRecoveredValue = Math.min(this.MAX_MP -this.mp,randomRecoveryValue);
this.mp += actuallyRecoveredValue;
return actuallyRecoveredValue;
}
This is from a book I'm currently using to learn. The objective is to create a pray method for a Priest object that restores its MP by the amount of seconds prayed plus 0 to 2 at random. I don't quite understand two things:
3 after nextInt rather than 2 (the book's answer) - why is this when we're trying to get 0 to 2 at random?
actuallyRecoveredValue returns its value to secondsPrayed; however, to me it looks like that to get actuallyRecoveredValue in the first place we need RandomRecoveryValue, which in turn needs secondsPrayed, which at that point doesn't seem to exist? I'm new to Java so I don't have much experience with returning values and such.
nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive), drawn from this
random number generator's sequence.
You pass secondsPrayed as variable into the method, so it does exist inside the method (scope). From the code you posted, we can't tell if actuallyRecoveredValue returns its value to secondsPrayed is true.
to me it looks like that to get actuallyRecoveredValue in the first
place we need RandomRecoveryValue, which in turn needs secondsPrayed
it's true, but as stated above, secondsPrayed does exist
1) The nextInt() method returns an integer value between zero and the parameter you used (3 in your case). While zero is included in the range, the last element of the range is not.
You can think that nextInt(n) returns n possible values, meaning the range between "0" and "n-1"
nextInt(5) // can return 0,1,2,3,4
2) The code is a little bit messy, I'll give you that, and as you said to get you have to determine the value of "randomRecoveryValue" in order to determine actuallyRecoveredValue. The method pray() does three things:
Calculates the recovered value, based on the input param and some randomness
Adjusts this value, so that the priest cannot heal over its full health. That happens at the third line, basically the priest heals for a number of points equal to "randomRecoveryValue" only if its current MP is not too high, otherwise he heals for the value that will get him to full health.
Update the value of his MP
Returns how much the he actually healed, not necessary, but may be useful to the caller of this method
Cheers
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need to count the frequency of an element in arrays.
I used the method
Collections.frequency(Arrays.asList(arr),element);
but I get zero all the times
any ideas ?!
If you are ArrayList consists of elements of custom type
example person bean, or employee object.
Make sure you have overridden equals() method and hash() methods
if you have not overridden these methods that Collection method wont work.
You need to give details about "arr" & element. However, I did came across this some time back when I tried to use an array of primitives such as int[], converting them to a List using Arrays.asList()
There is nothing like List of "int". An Integer would work however, Integer arr[] = {1,1,1,1,3,3,4,5,5,5,6};
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was hoping someone could help. Well I know how to use linear search to find a numerical value inside of an array. But now I want to learn how to search a string array for a string.
For example if I have a string array of students names how could I search the array to find a specific name inside that array?
If someone could write me a simple example since I'm new to Java still. Thank you, also is there a better way to search these kinds of things or linear search fine? :)
Use Arrays.asList() to wrap the array in a List. Then search in the List using contains() method:
String[] a= {"is", "are", "then"};
Arrays.asList(a).contains("are");
You can do using arrays also, but have to write some more lines of code. contains() method also does the linear search only.
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
The code for Strings can be the same as for numerical values, except you should use the String class's equals(...) method instead of ==.
You should use equals(...) because it's possible for two different String objects to have the same characters. But == would be incorrect because they are different objects.
Examples comparison expressions:
myArray[i].equals(myString)
or
myString.equals(myArray[i])
Note: Be sure the part on the left side isn't null. Otherwise you will get a NullPointerException.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I could use some help comparing two arrays, previously created in another method. They are called enterNumbers, user input array and drawNumbers, a randomly generated array.
My method header should look like this:
public static boolean containSameElements(int[] enterNumbers, int[] drawNumbers)
{
}
The method should compare the two arrays and return true if the numbers are the same, regardless of the order.
Not looking for the answer, just maybe a place to start.
Just sort them before
Arrays.sort(enterNumbers);
Arrays.sort(drawNumbers);
if(Arrays.equals(enterNumbers, drawNumbers)){
System.out.println("both are same");
}
Well, you can either
Create two histograms (using a hash based map/set) to count elements
in each array, and then compare the sets/maps. This solution is O(n)
space and O(n) time on average. Have a look at Map or Set for this. (Either you want Map or Set depends if existence of duplicates is important or not)
Another solution is sort and iterate. This is O(nlogn) time worst
case. Have a look on Arrays.sort() for this solution.
if (drawNumbers.length != enterNumbers.length)
return false;
List<Integer> base = new ArrayList<Integer>();
for (Integer i : drawNumbers)
base.add(i);
for (Integer i : enterNumbers)
base.remove(i);
return base.isEmpty();
This is a very common "problem" which can be solved using different methods. If I understand you correctly, all of the numbers have be inside the both arrays, but they don't have to be at the same indexes?
Then you can just make a while/for loop with (with two counters; one for each array) and check if the number on index 0 in the first array equals any of the numbers in the second array. If it doesn't the while/for-loop is done and the test failed. If it does go on to the next index in the first array. Continue until everything is tested(all numbers in first array versus the second array) or until a number doesn't exist in both arrays. Good luck