For if loop in Java with array - java

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"));
}
}

Related

Given an array of strings, write a recursive method that searches for a given string in O(n) and returns the index. LMK how to fix error

//this is the method to get the first string in the arraylist
public static Integer findFirstString(ArrayList<String> arrayOfStrings, String stringToFind) {
if (arrayOfStrings.isEmpty()) {
return -1;
}
if (arrayOfStrings.get(0).equals(stringToFind)) {
return 0;
}
//int index = 0;
//Error is line below this
Integer resultArray = findFirstString(arrayOfStrings.get(index), stringToFind);
if (resultArray == -1) {
return resultArray;
}
else {
return resultArray + 1;
}
}
I need help fixing the get(index) part, I'm not sure if initializing it helps or if it is completely incorrect.
In you code your method
findFirstString(ArrayList<String> arrayOfStrings, ....
is expecting an ArrayList, but when you can it as
findFirstString(arrayOfStrings.get(index)...
the method
arrayOfStrings.get(index)
only returns one Object.
Consider change your method so that it passing in an index which should be used like (not tested)
public static Integer findFirstString(ArrayList<String> arrayOfStrings, String stringToFind,
int index) {
if (arrayOfStrings.isEmpty()) {
return -1;
}
if (arrayOfStrings.get(index).equals(stringToFind)) {
return 0;
}
return findFirstString(arrayOfStrings, stringToFind, index++);
}

Java: Number of vowel in a string

I was asked to write a class NumberOcc with these methods:
-method getNbOcc which takes as arguments a string str and a character 'c' and return the number of occurence of the character 'c'.
-method dspNbOcc which displays the value returned by getNbOcc
-method getNbVoy which returns the number of vowel inside a string str
-method dspNbVoy which displays the value returned by getNbVoy
The problem is the value returned by getNbVoy is wrong, example: for str=stackexchange it returns 34 vowels.
public class NumberOcc {
static int count1=0;
static int count2=0;
public static int getNbOcc(String str, char c) {
for(int i=0;i<str.length();i++) {
if (str.charAt(i)==c)
count1++;}
return count1;
}
public static void dspNbOcc() {
System.out.println(count1);
}
public static int getNbVoy(String str) {
String vowel="aeiouy";
for(int j=0;j<vowel.length();j++) {
count2+=getNbOcc(str,vowel.charAt(j));}
return count2;
}
public static void dspNbVoy() {
System.out.println(count2);
}
}
TestClass
public class TestNumberOcc {
public static void main(String[] args) {
String str="stackexchange";
NumberOcc.getNbOcc(str, 'e');
NumberOcc.dspNbOcc();
NumberOcc.getNbVoy(str);
NumberOcc.dspNbVoy();
}
}
Thanks for helping
Remove the static fields, pass the values to the methods. And use them to display the results. Like,
public static int getNbOcc(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
public static void dspNbOcc(String str, char c) {
System.out.println(getNbOcc(str, c));
}
public static int getNbVoy(String str) {
int count = 0;
char[] vowels = "aeiouy".toCharArray();
for (char ch : vowels) {
count += getNbOcc(str.toLowerCase(), ch);
}
return count;
}
public static void dspNbVoy(String str) {
System.out.println(getNbVoy(str));
}
And then testing everything is as simple as
public static void main(String[] args) {
String str = "stackexchange";
NumberOcc.dspNbOcc(str, 'e');
NumberOcc.dspNbVoy(str);
}
the issue is you're not initializing your count1 (nor count2, but that bug doesn't affect anything in this case) at the beginning of your count method... add this line to the beginning of your getNbOcc method before the loop:
public static int getNbOcc(String str, char c) {
count1 = 0; // add this line
for(int i=0;i<str.length();i++) {
The solution is to apply what you did in your countLetterInString function to countVowelsInString. Just remember to use local variables. You will run into issues with static/global variables if the function is called more than once, but local variables will work the same way every time.
public static int countVowelsInString(String str) {
String vowels = "aeiouy";
// Move counter into the function
int numVowels = 0;
for(int j = 0;j<vowel.length();j++) {
numVowels += getNbOcc(str, vowel.charAt(j));
}
return numVowels;
}

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.

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

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.
}
}
}

Error in my Java code

I've got a problem with my Java program. There is an error in my code on line 16 (t = T[i];) which implies an error on line 12. It says :
Syntax error on token "=",VariableInitializer expected after this token.
Could I have some help ?
public class Ngrams {
public static boolean estPrefixe(String t, String s) {
int Longs = s.length();
if (t.substring(0, Longs) == s) {
return true;
} else {
return false;
}
}
public static int nbOccurences(String[] T, String s) {
int compteur = 0;
String t = null;
for (int i = 0; i < T.length; i++) {
t = T[i];
if (estPrefixe(t, s)) {
compteur++;
}
return compteur;
}
}
Notwithstanding the fact that you're comparing Strings with == instead of .equals(), and that a right bracket seems to have gone AWOL, at the end of your program, you're "missing" a return statement in nbOccurences. Even though you have one in the for-loop, if you never enter the loop, you don't return anything.
Move your return statement down one line, outside of the loop instead.
public static int nbOccurences(String[] T, String s) {
int compteur = 0;
String t = null;
for (int i = 0; i < T.length; i++) {
t = T[i];
if (estPrefixe(t, s)) {
compteur++;
}
}
return compteur;
}
The method nbOccurences does not always return an int value. If T is null or empty (length = 0) no value is returned. So you should add another return statement after the for loop.
As others mentioned already you should use equals to compare strings. This however, is not producing a syntax error.
Well there's a serious bug in this line:
if (t.substring(0, Longs) == s) {
This test will always be false, because == compares object references, not values. Change it to:
if (t.substring(0, Longs).equals(s)) {
But the whole method is pointless. Change it to:
public static boolean estPrefixe(String t, String s) {
return t.startsWith(s);
}
Or just delete the method altogether because it adds no value whatsoever.

Categories

Resources