Reputation: 11
I am fairly new to Java and have recieved some feedback on my tutor from my work on a program that works out if a word is in ascending order but I don't really understand it. Could anyone help to explain? I'm sorry if it's obvious to others. The feedback is in the comments below.
class Main
{
public static void main( String args[] )
{
System.out.print( "#Please enter a name : " );
String name = BIO.getString();
while(!name.equals("END")){
Boolean inOrder = true;
String nameLC = name.toLowerCase();
char previous = name.charAt(0);
for (int x = 0; x < nameLC.length() && inOrder ; x++) {
inOrder = nameLC.charAt(x) >= previous;
// inOrder must only be set false
previous = nameLC.charAt(x);
}
// The problem is you only want to set inOrder to be false
// If you set it to true as well then you will cancel out
// a possible previous finding of that two letters were out of order
if (inOrder && !name.equals("END"))
{
System.out.print(name + "\t" + "letters in ascending order");
}
else if (!inOrder && !name.equals("END"))
{
System.out.print(name + "\t" + "letters not in ascending order");
}
System.out.print("\n");
System.out.print("#Please enter a name : ");
name = BIO.getString();
}
}
}
Thanks
Upvotes: 0
Views: 62
Reputation: 38939
It appears that your solution already breaks if inOrder
is set to false. You have a compound condition in your for
-loop that exits when inOrder
is false.
for(int x = 0; // Initialize x
x < nameLC.length() && inOrder; // Continue looping UNTIL x == nameLC.length() OR inOrder is false
x++){ // Increment x
inOrder = nameLC.charAt(x) >= previous; // Set inOrder, if it's false the for loop will exit
Upvotes: 0
Reputation: 2939
for (int x = 0; x < nameLC.length(); x++) {
inOrder = nameLC.charAt(x) >= previous;
if(!inOrder) break;
previous = nameLC.charAt(x);
}
If I got you right you want to exit in case one letter is not "in order".
Just add this "break;" statement to your loop and you should be fine.
Greetings Tim
Upvotes: 1