I have a recursive method that reversed a string (HW assignment, has to be recursive). I did it....but its only returning the value of the string after the first pass. By analyzing the output after each pass i can see it does do its job correctly. heres my code, and the output i get below it:
String s = "Hello, I love you wont you tell me your name?";
int k=0;
public String reverseThisString(String s) {
if(k!=s.length()) {
String first =s.substring(0,k)+s.charAt(s.length()-1);
String end = ""+s.substring(k, s.length()-1);
k++;
s=first+end;
System.out.println(s);
this.reverseThisString(s);
}
return s;
}
output:
?Hello, I love you wont you tell me your name
I think you need to change this:
this.reverseThisString(s);
to this:
return this.reverseThisString(s);
otherwise the result of the method call is simply discarded.
I would also recommed that you change k to be a parameter to the method rather than a member.
Like Mark said, you forgot the return statement.
Also, there is an easier way to reverse a string (which is my current homework too :P )
public String reverse(String s) {
if(s.length() <= 1)
return s;
return reverse(s.substring(1))+s.charAt(0);
}
Related
I am a Java beginner. When reading a block of Java code, I came across a method which includes a if condition and return "";
Just wondering what does return ""; means…
The example code is below:
public String parse(String d, String u) {
if (d.isEmpty() || u.isEmpty()){
return "";
}
...
}
Could someone explain further to me please? Thank you
I'm just doing to break this down line by line for you.
public String parse(String d, String u)
This line declares a new method which:
Is called parse
Returns a string
Takes two strings as inputs
If youre wondering specifically about the fact that the keyword return is used then you can look at this answer I found from a quick google search.
if (d.isEmpty() || u.isEmpty())
This line checks if the input d is empty OR (expressed by '||') input u is empty. Essentially checking if either of the inputs are empty.
return "";
If the above if statement is met, return""; will be run. This means the method will return an empty String.
I can only guess what is at the end of the method you've posted but to help you further I've whipped up a quick example.
public String parse(String d, String u) {
if (d.isEmpty() || u.isEmpty()){
return "";
} else {
return "not empty";
}
}
public static void main(String[] args)
{
String d = "hi";
String u = ""; //empty
String result = parse(d, u);
System.out.println(result);
String d = "hi";
String u = "bye"
result = parse(d, u);
System.out.println(result);
}
The output we get in the console is:
empty
not empty
This is probably a check before starting parsing those string, you dont want to parse empty strings cause it probably has to do with the parsing mechenism, so it start from checking validation of the arguments, and return empty String if it invalid
EDIT :
ok, sorry for not so clear question. Let's try other way:
We have an ArayList of names : Peter, John, Adam
We are looking for String name;
If ArrayList contains the String, we want to write the String. If ArrayList doesn't contains the String, we want to add the String into the ArrayList.
If I'm looking for "Adam", then this program is not working, because first it finds name "Peter", then "John", and only after that it finds "Adam". So for the first 2 times, it thinks, "Adam" is not in the list, and acts so.
String findName;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().contains(findName)) {
System.out.println(findName);
break;
}
else
arrayList.add(findString);
}
Original question :
I have a String and an Array (ArrayList). I have to do something, if the String is in the Array and something else, if it is not in the Array. How do I do that?
I can't do it like this :
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
break;
}
else
DO SOMETHING ELSE;
}
because it will find the String only once and all the other times it will act, like the arraylist doesn't contains the String.
So I'm doing it like this :
String findString = "0";
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
findString = "2"; //when I find the String, I change this
break;
}
if findString == "0"; //if I have not found the String, this happens
DO SOMETHING ELSE;
}
and I have the feeling, it should be not done like this. ;)
I know I can use booleans instead of this way, but it's the same in other way. Isn't there total different way of doing this correctly?
Cleanest way is as follows: Declare a method which returns whether the string is in the array:
public boolean arrContainsStr(String str, String[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(str)) {
return true;
}
}
return false;
}
Then use this method in your code like this:
String myString;
String[] myArray;
if (arrContainsStr(myString, myArray)) {
DO SOMETHING;
}else {
DO SOMETHING ELSE;
}
This is for primitive string arrays. Note that if you are using an ArrayList or similar, you can simply use the .contains(myString) method to check if the list contains your string. Documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
This question is a bit odd, but just reading your first sentence, if you want to see if a List e.g. ArrayList contains an object (e.g. a String) you can just use the contains(Object o) method rather than looping through. I must be missing your point. In any case, an example:
String stringToFind = "Foo";
List<String> stringList = new ArrayList<>();
stringList.add("Foo");
if (stringList.contains(stringToFind)) {
System.out.println("String found");
} else {
System.out.println("String not found");
}
Output: String found. (In this example).
Couldn't you use .contains as below to check if the String is in the list?
if(arrayList.contains(myString)){
// DO SOMETHING
} else {
// DO SOMETHING ELSE
}
You could set a boolean to true if you find your value then break.
If you don't find the value, the boolean will stay to false.
Then you do the if
Its a little vague so I'm not sure if this is what you want, but if you remove the break in the first segment of code i think you will get what you want. do you want it do DO SOMETHING for every occurrence of the string or just the first one. also if you do need the break you could check the value of i after the loop terminates so
if(i==arrayList.size())
{
//String found
}
else
{
//String not found
}
Hi guys can someone correct my mistake?
The error is on the second line I try to put a void method which converts an integer
Integer g=Integer.valueOf(this.jTextField1.getText()).intValue();
Integer g=Integer.valueOf(this.jTextField1.getText()).intValue();
this.jTextField3.setText(String.valueOf(this.convert(g)));
Hi guys can someone correct my mistake?
return does not work
public String convert(Integer number1) {
Integer [] tab = new Integer[4];
int i=tab.length-1;
do {
tab[i]=number1%10;
number1=number1/10;
i--;
} while(number1!=0);
for(int g=0;g<=tab.length-1;g++) {
if(tab[g]!=null){
String f= String.format("%4s",Integer.toBinaryString(tab[g])).replace(' ', '0');
return f;
}
}
}
My guess, your convert method is printing out a result but not returning a result:
public void convert(int number) {
// do something to the number, creating theConvertedNumber
System.out.println(theConvertedNumber);
}
This is worthless to you since you want to place the converted number into a JTextField, and you can't do this if the method returns nothing. Instead have it return the converted number:
public int convert(int number) {
// do something to the number, creating theConvertedNumber
return theConvertedNumber;
}
Regarding your latest code, you've got your return statement buried within an if block, and the compiler sees this. So what happens if the if condition is false? The method that should return a String will then not have a viable way of returning anything. You must either take the return statement out of the if, and perhaps place it at the end, or give the if block an else block that also has a return statement.
I have troubles returning a value from a loop in method.
I've tried this way: (which returns classname, my initialise String instead of classes.get(i).className)
public String getClassName(){
String cName = "classname";
for (int i=0; i<classes.size(); i++){
cName = classes.get(i).className;
}
return cName;
}
and I've tried this as well: (which returns c instead of classes.get(i).className)
public String getClassName(){
String cName = "classname";
String c = "c";
for (int i=0; i<classes.size(); i++){
c = classes.get(i).className;
}
cName = c;
return cName;
}
Please tell me how to return classes.get(i).className!! Thanks a lot :P
There is nothing stored in classes. Make sure you have in there what you think you do. Try putting this inside the for loop to see what's going on:
System.out.print("class name = " + cName);
If this never prints out, you know that classes is empty. At any time inside the for loop, you can call return, for example if the class name matches something you can test for in an if statement.
for (int i=0; i<classes.size(); i++){
cName = classes.get(i).className;
return cName;
}
Also, could you upvote, or mark someone as correct? (I'm new and would love to have some good answers marked as such :) )
I don't know what are you trying to do, but your code is equivalent to:
public String getClassName() {
return classes.get(classes.size() - 1).className;
}
Are you sure this is what you want to return? You should be careful in case classes is empty as you might get ArrayIndexOutOfBoundsException.
While Maroun is right bout the code only returning the last value in the classes collection, the reality is that in your example the collection is always empty, and thus the for loop does not execute even once. Make sure the classes collection contain what you think it should!
That should be because you dont enter the for loop mainly because you list "classes" is empty.
You can check it this way-
if(classes.size()==0)
System.out.println("Classes is empty");
Method:
public String getRowsOf3Stars (int rows)
Description:
Compulsory Exercise 2) Complete the getRowsOf3Stars method which is
passed an int(rows) as a parameter. The method returns a String
containing that number of 3-stars rows.
For example,
getRowsOf3Stars(2) // returns “***\n***\n”
If rows is less than 1, returns an empty String.
An example:
getRowsOf3Stars(2) // should return "***\n***\n"
What I wrote:
public String getRowsOf3Stars (int rows) {
String getRowsOf3Stars="***\n";
if (rows<1){
String none="";
return none;
}
else{
for(int starRows=1;starRows<rows;starRows++){
return getRowsOf3Stars;
}
}
}
The error I recieve on CodeWrite:
private String getRowsOf3Stars(int rows) throws Exception {
>> This method must return a result of type String
Can someone please explain why my program isn't returning a String?
change this
for(int starRows=1;starRows<rows;starRows++){
return getRowsOf3Stars(starRows); // your code here don't return any thing here.
Put return ""; as last line of your method to get rid of the error. It's complaining because there is a chance your current lines where you're returning might never be called due to the conditions you have.
If for example you provide an argument rows = 1, the return will never happen.
Java compiler would make sure that there is a string return from the method.
Now see the code,
1) if(rows<1)
then only if will work and return a string.
2)But if (rows>=1)
then it will go to the for loop, and the compiler cannot determine at the compile time that the for loop will execute or not, as this is a runtime mechanism.So its not sure for the compiler that for loop will execute or not.
And if for loop doesn't execute, your method will not return anything.
Now since compiler has to make it sure, that there should be a string return, it is showing that error.
So what you can do is that, in the else clause after for loop you can return a default string as return ""; or as per your requirement.
In addition to the issue of not returning a string, I don't see a reason for the internal loop as you are issuing a return inside the loop. I think this would accomplish what you want:
public String getRowsOf3Stars (int rows) {
String ROWOF3STARS = "***\n";
String returnString = "";
if (rows > 0){
for(int starRows=1;starRows<rows;starRows++){
returnString += ROWOF3STARS;
}
}
return returnString;
}
Hope this helps.