mistake on return statement - java

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.

Related

[JAVA Help using 'for' and reusing methods from other parts of the class

I need some help with 2 methods that I'm using.
My first method looks at each character after the first (0th) in the string s and checks if they're digits but I cannot get it to fully work.
/**
* Forms the latter 5 characters of the accountNum String into a substring
which is checked to
* see if all characters are positive integers
*/
public Boolean hasValidDigits(String s)
{
for(int i=1; i<s.length(); i++)
if (Character.isDigit(s.charAt(i))) {
return true;
}
}
The issue with the method is it's asking for a return statement for the 'for' and I'm not sure why.
My second method calls methods from other parts of the class to check a string s.
/**
* Checks the following three criteria:
* - Is a string of length 6
* - Starts with a capital Letter
* - Subsequent characters are positive integers
*/
public Boolean isValidAccountNum(String s)
{
if (s.isValidLength() s.isValidStart() s.hasValidDigits()) {
return true;
} else {
return false;
}
}
The issue with this method is it's saying "Cannot find symbol - method isValidLength()
I'm guessing it would have same error with the other methods.
The methods I want to call are all made public. I'll include the isValidLength() below.
/**
* Checks if the variable accountNum has a length of 6 characters
*/
public Boolean isValidLength(String s)
{
if (s.length()==6) {
return true;
} else {
return false;
}
}
Your first method might not return anything if your if condition is not true so you need to return something at last line of function.
Your second method does not have passed any parameters and syntactically incorrect as well.
Please check out your language syntax first and practice some basic examples for your understanding of java
Your methods accept a String as a parameter, they are not part of the String class. So you have to do this isValidLength(s) rather than s.isValidLength().
Further, you cant have multiple method calls inside the parenthesis of an if statement, without a logical operator in between (&& for and, || for or).
Also, your hasValidDigits does not do what you think, it will return true if one of the character is a digit, rather than all of them. Also, the first part of the javadoc comment on this method is nowhere near true. It also lacks a return when the if statement never evaluates to true.
So what you want is something like this:
public Boolean isValidLength(String s) {
return s.length == 6;
}
//this checks all characters of the string though,
//your javadoc said something about checking the last 5 characters..
public Boolean hasValidDigits(String s) {
for(int i=1; i<s.length(); i++)
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
public Boolean isValidAccountNum(String s) {
return isValidLength(s) && isValidStart(s) && hasValidDigits(s);
}
The first method might performs a loop but will return at the first iteration if it is a digit it does not check the whole string and there is no false returned e.g.:
public Boolean hasValidDigits(String s) {
for (int i = 1; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
return true;
}
the isValidAccountNum method can just return the statement as it is already a boolean expression
return s.isValidLength() && s.isValidStart() && s.hasValidDigits();
same for the isValidLength method for the same reason:
return s.length()==6;

is it possible to return value from method enclosed in the lambda expression?

i encounter a line java book which state that "when a return statement occurs within a lambda expression,it simply cause a return from the lambda.It does not cause an enclosing method to return".
Does above statement mean we cant return value from method enclosed in the lambda expression.
i couldn't find any example so created a dummy program which wont compile.
Numeric num=(n)->{ // assume interface Numeric{ int func(int n); }
int a=5;
int result=n/a;
resultMethod(n) // assume int resultMethod(int a) is method.
{
return n;
}
return result;
}
System.out.println(num.func(12));
if( n.equals("Null"))
{
}
This will check the entered value is Null text. This will work true if you enter Null as text in the promt. If you want to check n is NULL try the below code
if(n == null)
{
}
See this example :
public static void main() {
funcInt fi = (n) -> {
return n;
}
System.out.println("This will be executed");
}
In above example, the print statement will get printed.
The return statement inside lambda expression, won't lead to return of main without printing the statement.

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

Program not returning a String

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.

Why isnt this returning the new string?

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

Categories

Resources