Methods, more than one return? - methods

I have the following method:
From what I learned methods which are not voids need a return. For the following examples I can see two returns, once after if(), and one at the end.
For this example if String s is not a digit it will return the boolean as false. Which makes sense. If it is a digit then it will check whether it is in the interval. I guess I am confused regarding whether we can have multiple returns in such cases and what the limitations are, if there are any. thank you.
private boolean ElementBienFormat(String s) {
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
return false;
}
}
int n = Integer.valueOf(s);
return (n>=0 && n <=255);

A method will "quit" (return) when control reaches a return. So in this case as soon as a character is not a digit in the input String control will go back to the caller (with the appropriate value).
boolean success = ElementBienFormat( "a" ); // <-- control would go back here with the value of false.
Another quick note is that a void method can have multiple return statements as well
private void Method( int n )
{
if( n < 0 )
return;
//...
//implicit
//return;
}

Related

Java Palindrome always returns true

I tried to create a palindrome java program with JOptionPane by using for loop, but it ends up returning true all the time no matter the input is really a palindrome or not. Can guys please help if you guys know what's wrong with the code below, thanks.
public class program {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
JOptionPane.showMessageDialog(null, "Welcome to The Palindrome!", "Hello", JOptionPane.INFORMATION_MESSAGE);
String str = JOptionPane.showInputDialog("Please input a string");
int len = str.length();
int j = len - 1;
int i = 0;
boolean result;
for(i = 0; i <= (len - 1)/2; i++);
{
if(str.charAt(i) != str.charAt(j))
result = false;
j--;
}
if(result = true)
JOptionPane.showMessageDialog(null, str + " is a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
if(result = false)
JOptionPane.showMessageDialog(null, str + " is not a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
}
Instead of using traditional way to check palindrome, just use the smart way. Here you go
boolean result = str.equalsIgnoreCase(new StringBuffer(str).reverse().toString());
When you check for the value of result, you are using =, which assigns that value to the result variable, and always evaluates to true.
To correct your code, you can either remove the equal sign, or use result == true (usually you use the former, as it is more concise).
However, this may result in an error, as you are not initialising the value of result. I recommend setting it's value to true as the default value.

Sudoku solver with backtracking can't always detect multiple solutions

This is the code I wrote to check if there are multiple solutions to a KenKen puzzle (Similar to Sudoku). Technically it should return true if there are 2 solutions, but it doesn't appear to work because of a logic error in the algorithm.
I can't seem to find the error and after spending a whole day debugging the whole thing step by step I feel like I'll never find out what's wrong.
The code can solve the puzzle without any problems but it doesn't always seem to detect when there are multiple solutions, which is just weird.
boolean solutionFlag = false;
static boolean backtrackingUniqueSolution(int startIndex) {
for (int i=1; i<=sudokuGridElements.length; i++){
sudokuGridCells[startIndex] = i;
if(checkConditons()){
if(endOfBounds || backtrackingUniqueSolution(startIndex + 1))){
if(!solutionFlag){ //Used to "count to 1"
solutionFlag = true;
} else {
return true; //Should return true only after it finds the second solution
}
}
}
sudokuGridCells[startIndex] = null;
}
return false;
}
When you find the first solution, you set the flag, but return false, so that you don't know whether a solution was found further up the recursion stack. The flag tells you that, but you must still look for a second solution to get your answer.
You should distinguish between actually finding a solution when the last cell is reached and cutting recursion short when you already have found a second solution. In the first case, do the delayed counting via the flag. In the second case, just return true if a second solution was found, that is when the recursive function has returned true.
boolean solutionFlag = false;
static boolean multiSolution(int startIndex) {
for (int i = 1; i <= sudokuGridElements.length; i++) {
sudokuGridCells[startIndex] = i;
if(checkConditons()) {
if (endOfBounds) {
if (solutionFlag) return true;
solutionFlag = true;
} else {
if (multiSolution(startIndex + 1)) return true;
}
}
sudokuGridCells[startIndex] = null;
}
return false;
}
(You could get rid of the non-local state flag, if you made the function return an integer or enumerated value which tells you whether no, a single or many solutions were found.)

Exiting a non void method? (Java)

I was wonder how you would go about exiting a method early. If this was a void type, I would just do "return", however since this is an int type, it wants me to return an integer. How do I return to main without returning any integers. Thanks.
public static int binarysearch(String[] myArray, String target, int first, int last)
{
int index;
if (first > last)
{
index = -1;
System.out.println("That is not in the array");
// Return to main here
}
You can't return from a method without a return value, in the traditional sense.
You can either return -1; and declare in your documentation that -1 represents a failed search, or you can throw an exception. If you throw an exception, though, you'll need to catch it. You can read more about that in the linked article.
A couple of options....
1. break;
2. return a value that you know would not be returned from a valid result. Eg 99999999 or -34
Those would be simple choices....
Edit
Of course break would only exit the loop. So youd still need to return a known value.

What is the accepted practise for returning from boolean methods

Okay, this is a simple question, but I'd like some oppinions on the correct practice here. I am not looking at this for performance concerns, because CPU's are so powerful that this wouldn't make any perceivable difference unless called without a looping contruct with thousands of iterations. I just want views on what is the accepted standard.
I have a method that bascially just does a check returns a boolean. However, there are numerous ways to implement this.
Here is how I would normally implement this.
public bool CanUndo()
{
if (_nCurrentUndoIndex > 0)
return true;
else
return false;
}
However, it is often frowned upon to return from the middle of a method. The only time I normally do this is when performing a check on a form submission like this.
if (String.IsNullOrEmpty(firstName.Text))
{
MessageBox.Show("Please enter a first name", "Incomplete");
return;
}
I consider that acceptable.
Back to the undo question, an alternative way to code it would be this.
public bool CanUndo()
{
bool returnVal;
if (_nCurrentUndoIndex > 0)
returnVal = true;
else
returnVal = false;
return returnVal;
}
This however unncessarily allocates a variable and is more verbose code. Another option would be.
public bool CanUndo()
{
bool returnVal = false;
if (_nCurrentUndoIndex > 0)
returnVal = true;
return returnVal;
}
This is more streamlined as it gets rid of the else. However, if the value is true is makes an unneccesary assignment by initializing it to false.
public bool CanUndo () {
return _nCurrentUndoIndex > 0;
}
Personally I don't have a problem with returning from the middle of a method. It complicates cleanup code for C functions but with RAII that argument disappears.
I prefer to exit as soon as is suitable otherwise you get
if (x) {
if (y) {
if (z) {
complete
}
}
}
rather than
if (!x)
return
if (!y)
return
if (!z)
return
complete
This way you avoid nesting, wide lines (horizontal screen space is expensive, vertical space is cheap) and you always know that if you're still in a function then you're not in an error path. Code which works well with this design also works well with exceptions, which is very important.
you should always contract boolean returns to their logical aquivalent, because this is much easier to read for developers, it is faster to write for you and it get contracted by the compiler anyways.
consider an expanded or:
if (a == 1)
return true;
else if (a == 2)
return true;
else if (a == 3)
return true;
else
return false;
and the reason should become obvious when you compare it to the contracted version
return (a == 1) || (a == 2) || (a == 3)
public bool CanUndo()
{
return (_nCurrentUndoIndex > 0);
}

Algorithm to format text to Pascal or camel casing

Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.
For example:
mynameisfred
becomes
Camel: myNameIsFred
Pascal: MyNameIsFred
I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331.
I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-
camelCase("hithisisatest");
The output could be:-
"hiThisIsATest"
Or:-
"hitHisIsATest"
There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language).
I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:-
SetPhraseCase(phrase, CamelOrPascal):
if no delimiters
if camelCase
return lowerFirstLetter(phrase)
else
return capitaliseFirstLetter(phrase)
words = splitOnDelimiter(phrase)
if camelCase
ret = lowerFirstLetter(first word)
else
ret = capitaliseFirstLetter(first word)
for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
return ret
capitaliseFirstLetter(word):
if len(word) <= 1 return upper(word)
return upper(word[0]) + word[1..len(word)]
lowerFirstLetter(word):
if len(word) <= 1 return lower(word)
return lower(word[0]) + word[1..len(word)]
You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.
A C# implementation of the above described algorithm is as follows (complete console program with test harness):-
using System;
class Program {
static void Main(string[] args) {
var caseAlgorithm = new CaseAlgorithm('_');
while (true) {
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) return;
Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
input,
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
}
}
}
public class CaseAlgorithm {
public enum CaseMode { PascalCase, CamelCase }
private char delimiterChar;
public CaseAlgorithm(char inDelimiterChar) {
delimiterChar = inDelimiterChar;
}
public string SetPhraseCase(string phrase, CaseMode caseMode) {
// You might want to do some sanity checks here like making sure
// there's no invalid characters, etc.
if (string.IsNullOrEmpty(phrase)) return phrase;
// .Split() will simply return a string[] of size 1 if no delimiter present so
// no need to explicitly check this.
var words = phrase.Split(delimiterChar);
// Set first word accordingly.
string ret = setWordCase(words[0], caseMode);
// If there are other words, set them all to pascal case.
if (words.Length > 1) {
for (int i = 1; i < words.Length; ++i)
ret += setWordCase(words[i], CaseMode.PascalCase);
}
return ret;
}
private string setWordCase(string word, CaseMode caseMode) {
switch (caseMode) {
case CaseMode.CamelCase:
return lowerFirstLetter(word);
case CaseMode.PascalCase:
return capitaliseFirstLetter(word);
default:
throw new NotImplementedException(
string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
}
}
private string lowerFirstLetter(string word) {
return char.ToLower(word[0]) + word.Substring(1);
}
private string capitaliseFirstLetter(string word) {
return char.ToUpper(word[0]) + word.Substring(1);
}
}
The only way to do that would be to run each section of the word through a dictionary.
"mynameisfred" is just an array of characters, splitting it up into my Name Is Fred means understanding what the joining of each of those characters means.
You could do it easily if your input was separated in some way, e.g. "my name is fred" or "my_name_is_fred".

Resources