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.
Related
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 a method where I pass two int arguments, and returns a string. A loop will make sure that if the first argument(the greater value) is greater than the second, that the first will decrement until it is equal the value of the second argument(the lesser value).
The problem I'm having is that I am trying to return the value of the decremented value after each time that the loop runs. I would like to return the values as a string like "8,6,4,2".How would i set that up?
public String countDown(int arg1, int arg2){
if (arg1>arg2){
for (int i = arg1; arg1>arg2;i--){
//???
return i;
}
}
Use a StringBuilder:
public String countDown(int arg1, int arg2){
final StringBuilder stringBuilder = new StringBuilder();
if (arg1>arg2){
for (int i = arg1; arg1>arg2;i--){
//???
stringBuilder.append(/*whatever*/);
}
}
return stringBuilder.toString();
}
You need to put your return outside the loop.
And you need to declare an object before the loop, in which store the values as you encounter them, before finally returning it at the end.
String out = "";
for(int i = arg1; i>arg2; i--) {
out = out + i + ",";
}
return out;
This has a couple of issues:
There is always an extra "," at the end of the returned String
Although it might be a good enough solution to your homework problem, returning a String from a method like this isn't usually the best design. It would be better to return, for example, a List of integers, because that's a structure that retains the actual "meaning" of the data more than a String does in this case.
You can find help with both of those by searching on this site (there is no need to ask another question) - or by reading ahead in your Java textbook.
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");
Im writing a method to return a specific record in an array however it throws up two errors and Im not sure how to fix it. Can anyone explain what I'm doing wrong?
public String find(String searchName)
{ // ERROR - MISSING RETURN STATEMENT
Iterator<TelEntry> iterator = Directory.entries.iterator();
boolean hasFound = false;
while (iterator.hasNext())
{
TelEntry entry = iterator.next();
if (entry.name.equalsIgnoreCase(searchName)) {
return entry.name + entry.telNo;
hasFound = true; // ERROR UNREACHABLE STATEMENT
}
}
if (hasFound==false)
{
System.out.println("sorry, there is noone by that name in the Directory. Check your spelling and try again");
}
}
Can anyone explain what I've done wrong?
The basic problem you have is that when a match is not found, you have no return statement. Usually, a method will return null is such cases, but you may want to return searchName, or even the error message - it depends on what the intention/contract of the method is (not stated).
However, the other problem you have is that your code is way too complicated for what it's doing, especially the hasFound variable is completely useless.
Change your code to this, which does exactly the same thing but is expressed more elegantly:
public String find(String searchName) {
for (TelEntry entry : Directory.entries) {
if (entry.name.equalsIgnoreCase(searchName)) {
return entry.name + entry.telNo;
}
}
System.out.println("sorry, there is noone by that name in the Directory. Check your spelling and try again");
return null; // or return "searchName", the error message, or something else
}
return statement should be last staetement in a block. Change your code below:
if (entry.name.equalsIgnoreCase(searchName)) {
hasFound = true; // ERROR UNREACHABLE STATEMENT
return entry.name + entry.telNo;
}
If a method is declared as returning a String, it must return a String, or throw an exception. Not returning anything is not acceptable. So you should decide what to do when the string is not found. You basically have two choices:
returning null
throwing an exception
Printing an error is not a good idea. Such a method shouldn't deal with the user interface. That's not its responsibility, and a method should only have one responsibility. Returning a string with an error message is not a good idea either: the caller would have no way to know if the returned string is the one which has been found, or an error string.
Moreover your code is overly complicated. It could be reduced to the following (assuming Directory.entries() implements Iterable, as it should):
public String find(String searchName) {
for (TelEntry entry: Directory.entries()) {
if (entry.name.equalsIgnoreCase(searchName)) {
return entry.name + entry.telNo;
}
}
return null;
}
I would change the return type, so, and make it return a TelEntry instance. Let the caller deal with the concatenation. It's not the responsibility of this method either.
Your code is incorrect : you cannot have instructions after a return in the same block: how could it be executed, since the function has returned ... ?
That's what the compiler is telling you : unreachable statement
Prefer return the string itself. Indeed, print it to screen directly violates SRP (Single Responsibilty principle and also avoid to return something as the method expects).
No need for boolean checker.
public String find(String searchName) {
Iterator<TelEntry> iterator = Directory.entries.iterator();
while (iterator.hasNext()) {
TelEntry entry = iterator.next();
if (entry.name.equalsIgnoreCase(searchName)) {
return entry.name + entry.telNo;
}
}
return "sorry, there is noone by that name in the Directory. Check your spelling and try again";
}
Can anyone explain what I've done wrong?
My explanations are in comments below:
public String find(String searchName)
{ // ERROR - MISSING RETURN STATEMENT
Iterator<TelEntry> iterator = Directory.entries.iterator();
boolean hasFound = false;
while (iterator.hasNext())
{
TelEntry entry = iterator.next();
if (entry.name.equalsIgnoreCase(searchName)) {
return entry.name + entry.telNo;
/*The "return" statement above stops executing
the current method and transfers control to the
place from where "find" method was called. The
statement below this line is NEVER executed.*/
hasFound = true; // ERROR UNREACHABLE STATEMENT
}
}
if (hasFound==false)
{
System.out.println("sorry, there is noone by that name in the Directory. Check your spelling and try again");
}
/*This method starts with "public String". That means that
it MUST return a String object or null when the method
finishes executing.
The best place to return is here.*/
}
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);
}