Compile problems -- must return a String [duplicate] - java

This question already has answers here:
Why do I receive the error "This method must return a result of type ..."?
(5 answers)
Closed 6 years ago.
I am working on a codingbat problem and trying to remove an char from a String and return a string without that char. Below is my code. Please tell me what's wrong with it as I keep getting an error message saying it must return a String.
public String missingChar(String str, int n) {
if (str.length() < n) {
int idx = str.indexOf(n);
String a = str.substring(0,idx);
String b = str.substring(idx+1, str.length());
return a + b;
}
}
Compile problems:
Error: public String missingChar(String str, int n) {
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type String

You need to return String even if the str.length() < n condition is not met
public String missingChar(String str, int n) {
if (str.length() < n) {
int idx = str.indexOf(n);
String a = str.substring(0,idx);
String b = str.substring(idx+1, str.length());
return a + b;
}
return str;
}

As the other answers and my comment already mentioned your code is missing a return statement in the else case. But your code logic is also quite flawed:
do not do int idx = str.indexOf(n);
invert the entire if logic
That will yield:
public String missingChar(String str, int n) {
if (n < str.length()){
String a = str.substring(0,n);
String b = str.substring(n+1, str.length());
return a + b;
}
return str;
}
Which results in the output hllo for given input "hello", 1.
Note that my assumption of the flaws logic results of you trying to compare n with the length of the string in the first place: comparing it to the length tells me n is supposed to be a index of the string - but then it makes absolutely no sense to call indexOf with that n. At the same time it could be that n is actually the char in the string you want to remove, but then its type should be char and you should some error handling in case the character is not found in the string.

The error is quite clear/simple
your method MUST return a string even if this condition is not met
if (str.length() < n){
modify the method in a way that you meet the contract with the return value.
public String missingChar(String str, int n) {
if (str.length() < n){
int idx = str.indexOf(n);
String a = str.substring(0,idx);
String b = str.substring(idx+1, str.length());
return a + b;
}else{
return something;
}
}

The problem is that all the return paths must return a string, and here you return string only in one of them...

If str.length() >= n, you have no return!

Related

Java: "Unexpected Type; required: Variable; found: value" by trying to return a value

If I want to compile this on BlueJ, it throws me an "Unexpected Type; required: Variable; found: value" Error at the first "" on line 3.
public static String binaryCode(int i){
if(i<=1){
return "" += i%2;
}
return "" += i%2 += binaryCode(i/2);
}
Btw, it has to be a recursion, I know a Loop would work too but it has to be solved within a recursion. The program should return the binary value as a string from an int.
Use + operator, not +=
public static String binaryCode(int i) {
if (i <= 1) {
return "" + i%2;
}
return "" + i%2 + binaryCode(i/2);
}
Note that this is very inefficient solution. A lot of String objects gets created and has to be destroyed (Strings are immutable in Java). Much better solution would be to use a loop and StringBuilder.
Solution with StringBuilder (in case you want to boost your performance, this code executes about 4 times faster):
public static String binaryCode(int n) {
StringBuilder sb = new StringBuilder();
for(int i = n; i > 0; i /= 2) {
sb.append(i%2);
}
return sb.toString();
}

Switching last two char in a string

Learning java as my first language and I found a solution for the problem at codingbat but I don't understand why my solution doesn't work and would love your help.
Given a string of any length, return a new string where the last 2
chars, if present, are swapped, so "coding" yields "codign".
lastTwo("coding") → "codign" lastTwo("cat") → "cta"
lastTwo("ab") → "ba"
This is my not working code:
public String lastTwo(String str) {
int strLength = str.length();
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
if(strLength<2)
return str;
return str.substring(0, strLength-2)+last+bLast;
}
This are the errors and I cant figure out why:
lastTwo("a")
→"Exception:java.lang.StringIndexOutOfBoundsException: String
index out of range: -1 (line number:5)" lastTwo("")
→"Exception:java.lang.StringIndexOutOfBoundsException: String
index out of range: -1 (line number:4)"
It seems there is a problem when input is less than 2 chars but I can't figure out why. To me, the if logic looks okay.
You need to move if condition up in the method as:
public static void main(String[] args) {
System.out.println(lastTwo("coding"));
System.out.println(lastTwo("cat"));
System.out.println(lastTwo("ab"));
System.out.println(lastTwo("a"));
}
public static String lastTwo(String str) {
int strLength = str.length();
if(strLength<2)
return str;
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
return str.substring(0, strLength-2)+last+bLast;
}
This will print:
codign
cta
ba
a
In the method if length of str is less than 2 (e.g. 1) in that case it will be returned else it will compute last and blast and then perform the operation.
When the input is is 1 char, strLength-2 is -1. The methodsubstring throws the error because such index doesn't exist. (The same applies to 0 char and strLength-1)
You have to put this verification on top
if(strLength<2)
return str;
When you have this code, if the string is "", it is trying to get the substring between positions -1,0 and -2,-1. You can't get the substring in a position lower than 0.
int strLength = str.length();
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
One of the overloads for substring can take the starting index , it figures out the last index. So the following should give you the last two chars:
str.substring(java.lang.Math.max(0,str.length()-2))
public String lastTwo(String str) {
if(str != null ) {
int strLength = str.length();
if (strLength < 2)
return str;
String last = str.substring(strLength-1,strLength);
String bLast = str.substring(strLength-2,strLength-1);
return str.substring(0, strLength-2)+last+bLast;
}
return null;
}
Problem in your code is String bLast = str.substring(strLength-2,strLength-1);
when strLength = 1 and you subtract by 2 and your index will be -1, hence IndexOutOfboundException occure.
Use above code your problem solved.
Simpler solution is to take the start-of-string and
append the last-char and then
append the before-last-char:
public static String lastTwo(String str) {
if (str.length()<2){
return str;
} else{
return str.substring(0, str.length() - 2) +
str.charAt(str.length() - 1) +
str.charAt(str.length() - 2);
}
}

Is this error due to type mismatch? How can I avoid this in the future?

for this question:
Given a non-empty string and an int N, return the string made starting
with char 0, and then every Nth char of the string. So if N is 3, use
char 0, 3, 6, ... and so on. N is 1 or more.
everyNth("Miracle", 2) → "Mrce"
everyNth("abcdefg", 2) → "aceg"
everyNth("abcdefg", 3) → "adg"
I get a "Type mismatch: cannot convert from char to String" when trying the following:
public String everyNth(String str, int n) {
for (int i=0; i<str.length(); i = i +n) {
return str.charAt(i);
}
}
However, if I use this:
public String everyNth(String str, int n) {
String result = "";
// Look at every nth char
for (int i=0; i<str.length(); i = i + n) {
result = result + str.charAt(i);
}
return result;
}
then the results are fine.
Is this error because I was trying to return an int when the question is originally in String?
How can I avoid this in the future?
Any tips?
Thanks in advance.
A char and a String are different types. Your second solution is correct. It is defined as String and it returns a String. Your first solution is wrong in two ways: it returns a char when a String is expected, and it puts a return statement in a for loop. You can only return once from a function, so the for loop is useless in that function.
Yes, this is a type mismatch
public String everyNth(String str, int n) {
says that your method returns type String, but
return str.charAt(i);
is actually returning a character.
you can change that line to
return Character.toString(str.charAt(i));
or
return String.valueOf(str.charAt(i));
str.charAt(i) returns a char. This is not the same as a String, which is why the compiler complains about type mismatch.
You could use String.valueOf(theChar) to convert it.
Or you could use str.substring(i, i+1) to get a String (with just a single character) instead of a char.
This loop:
for (int i=0; i<str.length(); i = i +n) {
return str.charAt(i);
}
returns the first char of the string, because the loop terminates (due to the return) on the first iteration, but the method is declared to return String (not char).
Incidentally, you can solve the whole task in one line:
public String everyNth(String str, int n) {
return str.replaceAll("(?:.{" + --n + "}(.))|.*", "$1");
}

PrefixAgain solution in codingbat

I'm currently doing codingbat problems for fun, and I just done this problem.
"Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume
that the string is not empty and that N is in the range 1..str.length(). prefixAgain("abXYabc", 1) → true prefixAgain("abXYabc", 2) → true prefixAgain("abXYabc",
3) → false"
http://codingbat.com/prob/p136417
And my solution is:
public boolean prefixAgain(String str, int n) {
return (str.replaceFirst(Character.toString(str.charAt(n-1)),"").contains(Character.toString(str.charAt(n-1))));
}
Now, I didn't really understand the problem while writing this code and I thought only to find the occurance of the character of the specified index and
ignore the characters before it using the .contains() method. So I'm really not finding the prefix as the problem instructed. I just found my mistake after submitting it. However, this solution passed the exercise.
When I test it with my own input, such as
prefixAgain("abcccccbx", 2);
it returned true instead of false. So am I missing some reason why codingbat accepted my solution even though it's totally wrong?
public boolean prefixAgain(String str, int n)
String prefix = str.substring(0, n);
int length = str.length();
for (int i = n; i <= length - n; i++) {
if (prefix.equals(str.substring(i, i + n))) {
return true;
}
}
return false;
}
Restate your strategy (algorithm): Do the first N characters in a string appear anywhere else in the string? Simplest solution would be to look for that string in the 2nd through last characters of the original string. Like below (even if someone gives you an assumption, always check!)
public boolean prefixAgain(String str, int n) {
boolean result = false;
if (n < str.length() &&
(str.substring(1)).indexOf(str.substring(0,n)) > -1
) {
result = true;
}
return result;
}
Maybe i missed something but this seems correct and elegant:
public boolean prefixAgain(String str, int n) {
if(str.substring(n).contains(str.substring(0, n))) return true;
return false;
}
If n > str.length() it returns false.
public boolean prefixAgain(String str, int n) {
int l= str.length();
String test = str.substring(0,n);
boolean flag = false;
str = str.substring(1);
l= str.length();
for(int i=0;i<l;i++){
if((i+n <= l)){
if((str.substring(i,n+i).equals(test)))
return true;
}
}
return flag;
}
This is mine (considering that indexOf() is not introduced yet):
public boolean prefixAgain(String str, int n) {
for (int i=1; i <= str.length()-n; i++)
if (str.substring(i, i+n).equals(str.substring(0, n)))
return true;
return false;
}
But I found this solution the most elegant so far:
public boolean prefixAgain(String str, int n) {
return (str.indexOf(str.substring(0, n), 1) != -1);
}
public boolean prefixAgain(String str, int n) {
return str.substring(n).contains(str.substring(0,n));
}
just looking the prefix(str.substring(0,n)) in the substring of str without the prefix this means starting from n which is (str.substring(n)).
public boolean prefixAgain(String str, int n) {
return (str.substring(n).contains(str.substring(0,n)));
}
This has been posted basically, but I revised it a little to make it super easy to read instead of going for the one liner.
public boolean prefixAgain(String str, int n) {
String prefix = str.substring(0, n);
String afterPrefix = str.substring(n);
return afterPrefix.contains(prefix);
}
First, we grab the prefix which will start at index zero and go up to not including n. afterPrefix is simply the rest of the string which will start at n. Finally, return whether everything after the prefix contains the prefix.
public boolean prefixAgain(String str, int n) {
String pre = str.substring(0, n);
for (int i=n; i<str.length()-n+1; i++)
{
if (str.substring(i, i+n).equals(pre))
return true;
}
return false;
}
A solution, not the fastest but clear.
public boolean prefixAgain(String str, int n) {
String prefix = str.substring(0,n); // prefix String
int index = str.indexOf(prefix); //first loc of prefix
if(str.lastIndexOf(prefix) > index){ //see if it appears again
return true;
}
else return false; //if we get here, doesn't appear again, false
}

How do I create a padString function in Java?

Every other question I have seen in my book I had at least some understanding of what the book was asking but this one I have no idea on how to approach it. It goes:
"Write a method called padString that accepts two parameters: a String and an integer representing a length. For example,
padString ("hello", 8)
should return "hello " (that's three spaces in there at the end). If the string's length is already at least as long as the length parameter, your method should return the original string. For example,
padString ("congratulations", 10)
should return "congratualtions".
I have no idea on how to approach this being pretty new to Java. This is supposed to be a beginner's homework so I suppose the method is very simple. Please show me how to do this and explain the steps if you can. Please and Thank you to whoever helps.
So your function should do something like this:
Determine number of padding characters required.
Need <= 0 padding characters? return input string
Otherwise, create a string with required padding characters, then return input string + required padding characters
You can find a string's length with the .length() method.
You could use the printf method in System.out (needs Java 1.6 or later, it's a new PrintStream method). Hake a look at an interesting example below, where the output is (specified below code). The padding is specified in the printf argument as 30, and is justified left:
package pft;
public class PrintfTest {
public static void main(String[] args) {
int padding = 30;
String s = "hi!";
System.out.printf("'%0$-" + padding + "s'", s);
}
}
prints: 'hi! '.
Taking it piece at a time (and without giving you all the code):
"Write a method called padString that
accepts two parameters: a String and
an integer representing a length."
public static ??? padString(String str, int len)
"For example,padString("hello", 8)
should return "hello"."
public static String padString(String str, int len)
{
throw new Error("not implemented yet");
}
"If the string's length is already at
least as long as the length parameter,
your method should return the original
string. For example,
padString("congratulations", 10)
should return "congratualtions"."
EDIT: you fixed the question...
public static String padString(String str, int len)
{
// if the str.length is greater than len
// return str
// this next part is very simple, not a very good way but gets you
// started. Once you have it working look at StringBuilder and .append.
// int val = the difference in length between the two strings
// for i = 0; i is less than val; i++
// str += " ";
// return str
}
public class PadString {
public static void main(String[] args) {
String str = "hello";
str = padStr(str, 10, ' ');
}
static String padStr(String s, int len, char c) {
int n = len - s.length();
if (n <= 0)
return s;
StringBuilder b = new StringBuilder(s);
for (int i = 0; i < n; i++)
b.append(c);
return b.toString();
}
}
Even thought this post is about 2 years old. I just recently had this
question for a homework. And I thought it might help other beginners
that might come across this problem to see a simpler way of solving
this problem.
One that will probably be more in line to where they are in their
beginner java course assuming they are getting this around the same
time that I did.
Of course you should remove the dashes in the loop and use spaces to
get credit for the assignment, that is there just to show you that it
works.
public class ex3_11_padString {
public static void main(String[] args) {
padString("hello",10);
}
public static String padString( String s, int len) {
int s_length = s.length();
int diff = len - s_length;
String newString;
newString = "";
for (int x = 0 ; x < diff; x++) {
newString += "-";
}
newString = newString + s;
return new String;
}
}
You may want to take a look at Java's String class documentation. Look for a method that returns the length of the string...
public static String padString(String str, int len)
{
int lengt=str.length();
if(lengt==len||lengt>len)
return str;
else if(lengt<len){
String spacstr="";
for(var i=lengt;i<len;i++){
spacstr+="$";
}
return str+spacstr;
}
}
///more generalized by accepting pad character
public static String padString(String str, int len,String padChar)
{
int lengt=str.length();
if(lengt==len||lengt>len)
return str;
else if(lengt<len){
String spacstr="";
for(var i=lengt;i<len;i++){
spacstr+=padChar;
}
return str+spacstr;
}
}
public String padString (String s, int padding) {
return String.format("%-" + padding + "s", s);
}
This is the better solution for me. Taken from the comment of #John C, with the "%-" added.
Sorry #John C I cannot edit your comment or add one below yours.

Categories