How to find an index of given String in array of strings? - java

Surely the solution to this is the following:
public long myFunc(String name) throws Exception {
for(int i=0;i<amount;i++){
if(this.otherString[i].equals(name))
return longArray[i];
}
throw new Exception("Not found");
}
However, this does not seem to be the case.

You can use Guava, then your code can looks like this
String[] stringArray = {"s1", "s2", "s3"};
int index = Iterators.indexOf(Iterators.forArray(stringArray), new Predicate<String>() {
#Override
public boolean apply(String input) {
return input.equals("s2");
}
});
or simpler
int index = Arrays.asList(stringArray).indexOf("s2");
Your code can also look like this
public class Finder {
private String[] stringArray = {"s1", "s2", "s3"};
public int findIndex(String name) {
for (int i = 0; i < stringArray.length; i++) {
if (stringArray[i].equals(name))
return i;
}
throw new RuntimeException("Not found");
}
public static void main(String... s) {
int index = new Finder().findIndex("s1");
System.out.println(index);
}
}

You can either run your code through a debugger and find out why it doesn't work, or add some println traces to your original code and you'll see what the problem is:
public long myFunc(String name) throws Exception {
System.out.println("Looking for: " + name);
for (int i = 0; i < amount; i++){
if(this.otherString[i].equals(name))
return longArray[i];
System.out.printf("%4d: \"%s\": No match.%n", i, this.otherString[i]);
}
for (int i = amount; i < this.otherString.length; i++)
System.out.printf("%4d: \"%s\": Not checked.%n", i, this.otherString[i]);
throw new Exception("Not found");
}
By the way, make sure you are correctly interpreting the method's behaviour. Could it be that it's finding it but throwing an ArrayIndexOutOfBoundsException because i is greater than longArray.length, and you misinterpret that as the exception you are explicitly throwing?

Turns out '\u0000' was at the end of the string that was meant to be equal. This does not show in printing. Next time I will be more ruthless in the inspection of the debugging. Thank you for all the suggestions though, and sorry for wasting your time.

This might be completely wrong, but isn't the problem just missing curly brackets in the if statement? I am new to the java language and the example is probably messy, but it uses the same structure from your question and works just fine:
public class random_class {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] a = new String[] {"hi!", "hello world!", "ho ho ho world!"};
int b = getHWIndex(a);
System.out.println(b);
}
public static int getHWIndex(String[] stringArray){
int i;
Boolean test = false;
for(i=0;i<stringArray.length;i++){
if(stringArray[i].equals("hello world!")){
test = true;
break;
}
}
if(test == true){
return i;}else{
return i = 0; // this is not a good answer...
//but as you return an int I could not think on a quick way to fix the return when there is no match.
}
}
}

Related

Why does these constructors have an error?

public class CharacterList {
private char [] charArray;
private int count;
public CharacterList(int arraySize){
charArray = new char[arraySize];
count = 0;
}
private int indexOf(char searchingChar) {
int a = 0;
for (int i = 0; i < charArray.length; i++) {
if(charArray[i] == searchingChar)
a = i;
else
a = -1;
}
return a;
}
public boolean addCharacter(char characterToAdd){
if(indexOf(characterToAdd) == -1){
doubleArrayCapacity();
count ++;
return true;
} else if(indexOf(characterToAdd) == 0){
charArray[0] = characterToAdd;
count++;
return true;
} else
return false;
}
}
I need to construct all the methods given in the attached list. I have done these many so far and the remaining are hard to get. Could someone:
1.) Check if the code I written till now is correct?
2.) Help me with the other constructors
Thank you in advance
Use an IDE, it will tell you that line 31 and 32 are the errors:
c cannot be resolved to a variable
Fix:
Rename c to characterToAdd
The method doubleArrayCapacity() is undefined for the type CharacterList
Fix:
Create method doubleArrayCapacity()
private void doubleArrayCapacity() {
// TODO Auto-generated method stub
}
And your code will compile (doesn't mean that it's working!).
Contructor is ok. Only one think I've found incorrect it your code is lack of method public void doubleArrayCapacity(). Probably you have forgoted implement or you avoid when copy source code here.
Another cause, where could be error is call of this contractor. How you call it? With argument or without? How that looks like?
public void doubleArrayCapacity() {
//create new array of char, which is double length
char [] newCharArray = new char[this.charArray.length*2];
//prescribe values from old array to new one
for(int i=0; i<this.charArray.length-1; i++) {
newCharArray[i] = this.charArray[i];
}
//set newCharArray set new value of your field charArray
this.charArray = newCharArray;
}

How to change the value of a String Array from a different class?

This may be a very simple question, but I can't seem to find a suitable answer on Google. I have a class called Player, which has a String array called playerInv with a size of 10.
In my Main Activity Class, I want to run a for loop to determine the first index in the array that is empty (""). I then want to populate that with a new string, and then terminate the loop. How do I do this?
Sorry for the nooby question. Like I said, I've tried Google to no avail!
For Loop:
String playerInvTemp[] = thePlayer.getPlayerInv; ERROR -- cannot resolve getPlayerInv
for (int i=0; i < playerInvTemp.length; i++)
{
if ((!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i); ERROR cannot resolve setPlayerInv
//invText.setText();
Blood = true;
break;
}
}
Player Class:
public class Player {
private int playerPos;
private int playerHP;
private String playerInv[];
Player(int startPos, int startHP, String[] newInventory)
{
playerPos = startPos;
playerHP = startHP;
playerInv = newInventory;
}
public int getPlayerPos() {
return playerPos;
}
public void setPlayerPos(int playerPos) {
this.playerPos = playerPos;
}
public int getPlayerHP(){
return playerHP;
}
public void setPlayerHP(int playerHP){
this.playerHP = playerHP;
}
public String getPlayerInv(int pos)
{
return playerInv[pos];
}
public void setPlayerInv(String playerInv[]) {
for (int i=0; i<10; i++)
{
this.playerInv[i] = playerInv[i];
}
}
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String getPlayerInv()
{
return this.playerInv; *//this gives error "Incompatible types. Required java.lang.string, found java.lang.string[]"*
}
}
Do this
Add these two method in Player class
public void setPlayerInv(String val, int index)
{
this.playerInv[index] = val;
}
public String[] getPlayerInv()
{
return this.playerInv;
}
then change your for loop like this
String playerInvTemp[] = thePlayer.getPlayerInv();
for (int i=0; i < playerInvTemp.length; i++)
{
if (!playerInvTemp[i].isEmpty()) || playerInvTemp[i] == null)
{
setPlayerInv("Blood Essence", i);
//invText.setText();
Blood = true;
break;
}
}
Bunch of problems here, .length() is not valid for an array, it should be .length.
`for (int i=0; i<thePlayer.getPlayerInv(i).length(); i++)`
You most likely mean null or at least need to check for it, here and you need [] not ():
if (thePlayer.getPlayerInv[i] == "" or theplayer.getPlayerInv[i] == null)
This is all wrong, and as a matter of fact you need to post your code and errors, you have many problems and should start with learning some basics about Java.
Try some beginners tutorials (https://www.google.com/search?q=java+tutorials&ie=utf-8&oe=utf-8). You have a lot of both syntax and logic errors.
Do you run an instance of constructor player()??
I did
Player a=new Player();
a.getPlayerInv(0)
and works fine.

No suitable method found? Please assist me in completing this?

I was wondering how can I use the remAll method on the very bottom of my code.
Whenever I try to use out.println(list.remAll());, it gives me an error saying
"No suitable method found for remAll"?
How can I fix this?
I have also tried using out.println(remAll(list));
I'm a beginner when it comes to Java and I am just learning, so pardon me if this is much simpler than it looks. P.S. Sorry if the format is wrong or something. It's my first post here.
import java.util.*;
import static java.lang.System.*;
public class StringArrayListLoader
{
public static void main(String args[])
{
Scanner kb = new Scanner(in);
out.print("Size of list? ");
int s = kb.nextInt();
ArrayList<String>list = new ArrayList<String>();
out.println("Enter the Strings: ");
for(int x = 0; x < s; x++)
{
out.print("String " + x + " :: ");
list.add( kb.next());
}
out.println("\nThe ArrayList you entered is ...");
out.println(list);
out.println(beginWithx(list) + " of the Strings begin with an \'x\'");
out.println(firstLast(list) + " of the Strings begin and end witletter.");
out.println("First String = Last String? " + firstLast2(list));
out.println(*******); // what am i supposed to put here?
}
public static int beginWithx(ArrayList<String>ar)
{
int count = 0;
for(int i = 0; i<ar.size(); i++)
if("x".equals(ar.get(i).substring(0,1)))
count++;
return count;
}
public static int firstLast(ArrayList<String>ar)
{
int counting = 0;
for(int i = 0; i<ar.size(); i++)
if(ar.get(i).substring(0,1).equals(ar.get(i).substring(ar.get(i).length()-2, ar.get(i).length()-1)))
counting++;
return counting;
}
public static boolean firstLast2(ArrayList<String>ar)
{
int counting = 0;
if(ar.get(0).equals(ar.get(ar.size()-1)))
return true;
return false;
}
public static void remAll(ArrayList<String>list, String s)
{
int i=0;
while(i<list.size())
{
if(list.get(i).equals(s))
{
list.remove(i);
}
else
{
i++;
}
}
out.println(list);
}
}
Your remAll method takes two parameters, an ArrayList<String> and a String. You must pass two parameters to call the method properly, such as
remAll(list, someOtherStringHere); // remAll has its own "out.println" calls
The method signature is
public static void remAll(ArrayList<String>list, String s)
So, you need to call it like:
remAll(list, "some string");
By inspection of the code, it will then remove all instances of "some string" from the list.

For if loop in Java with array

Why does this code give me an error? I'm tyring to return the index of the first string in strArr that matches string s.
private String strArr[];
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
}
You are not initialising the array (therefore will get a NullPointerException when you try and get it's length)
You are not returning from the method if the string is not found
public class StringArrayIndex {
private String strArr[] = new String[]{"bar","foo", "cas"};
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
return -1;
}
public static void main(String[] args){
System.out.println(new StringArrayIndex().indexOf("foo"));
}
}
When submitting to Stack Overflow you should try to give more information (full code samples, error messages etc) so people can help you more easily.
You need to also return some value e.g. -1 after your loop.
Your return is in an IF statement so the Java compiler is
not sure you will ever enter this IF. And if you don't, you might
never return a value from your method. Therefore the compile-tome error.
You are not returning anything if you do not find the string in the array.
You should return something if the condition is never evaluated to true (outside your for loop for instance, you could return -1).
In your case, not all paths return a value.
because if your method need to return something, it should return in all cases:
public int indexOf(String s) {
for(int i=0;i<strArr.length ;++i) {
if (strArr[i].equals(s)){
return i;
}
}
return -1; //if not find
}
it should return if your condition never get satisfied.
public class MyIndexOf {
private String strArr[] = {"x", "y", "z"};
public int indexOf(String s) {
for (int i = 0; i < strArr.length; i++) {
if (strArr[i].equals(s)){
return i;
}
}
return -1;
}
public static void main(String[] args) {
MyIndexOf self = new MyIndexOf();
System.out.println(self.indexOf("x"));
}
}

Java - Returning from a recursive function

I'm trying to return all possible permutations of values in a String array. I've come up with the following code making all possible permutations; it works fine.
private void combineArray(String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
}
If I put in {x, y ,z} it prints to the console:
xyz
xzy
yxz
yzx
zxy
zyx
My problem is that I can't find a way to return these values to the original calling function. So I'd like this function not to return 'void' but a 'String' containing the concatened values of sPrefix.
I've been struggling with this for a while now and I can't seem to see clearly anymore. :) Any help would be appreciated.
Rather than returning a list, I think it might work better to pass in a list as an argument, and populate it inside the method:
private void combineArray(List<String> lOut, String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
lOut.add(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(lOut, sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
}
You can then have a wrapper method that creates the new ArrayList<String>, passes it into the above method, and returns it.
You can have an ArrayList<String> and add all the strings to it.. And then you can return this ArrayList..
List<String> listString = new ArrayList<>();
private void combineArray(String sPrefix, String[] sInput, int iLength) {
if (iLength == sPrefix.length()) {
listString.add(sPrefix);
//This value should be returned and concatenated:
System.out.println(sPrefix);
} else {
for (int i=0; i<sInput.length; i++) {
combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength);
}
}
return listString;
}
Keep appending to the same output.. Like this:
private String combineArray(String sPrefix, String[] sInput, int iLength, String output) {
if (iLength == sPrefix.length()) {
//This value should be returned and concatenated:
System.out.println(sPrefix);
output = output+"|+sPrefix;
return output;
} else {
for (int i=0; i<sInput.length; i++) {
output = combineArray(sPrefix.concat(sInput[i]), ArrayUtils.removeElement(sInput, sInput[i]), iLength, output);
}
}
}
You can also use a ListArray instead of a String, once the basic concept works..

Categories

Resources