java - Trying to print the lesser string from standard input, getting mixed outputs -
import java.util.scanner; public class lesserstring2 { public static void main(string args[]) { scanner r = new scanner(system.in); int y = 0; int result = 0; string s = null; string q = null; while (y < 2) { s = r.nextline(); y = y + 1; q = r.nextline(); y = y + 1; } if (y >= 2){ result = s.compareto(q); } if(result == 0) { system.out.println("the strings equal, please try again."); } else if(result == 1) { system.out.println("lesser is: " + s); } else if(result < 0) { system.out.println("lesser is: " + q); } } } i getting mixed results when try submit 2 different sentences through standard input. instance...
c:\users\...>java lesserstring2 how cat jump think lesser is: think c:\users\...>java lesserstring2 jack sprat can eat no fat wife can eat no lean why didn't work second time? how can make work every time? second 1 tried literally outputs nothing... blank line.
the 2 main issues you're using result == 1 need using result > 0 (the positive value compareto may not 1; more in item #3.2 below), , have comparisons backward, you're showing "greater" of 2 strings rather lesser (item #3.1).
but code has variety of other issues, here's list:
the
while (y < 2)loop unnecessary:ystarts @0, add1twice, execute once.the
if (y >= 2)branch unnecessary (see #1).you're misusing return return value of
comparetoin 2 different ways:when value greater
0, you're sayings"lesser" string. value indicatessgreater string.you're comparing
== 1,compareto's contract does not guarantee1, positive number ifsgreaterq,0if they're equal, or negative number ifslessq. positive number may not1.
in java, class names initially-capped.
lesserstring2, notlesserstring2.it's best use meaningful names variables.
the reason you're not getting output #3.2 in above list. you're getting positive value, not 1.
here's version issues above addressed:
import java.util.scanner; public class lesserstring2 { public static void main(string args[]) { scanner inputscanner = new scanner(system.in); int result; string firststring; string secondstring; firststring = inputscanner.nextline(); secondstring = inputscanner.nextline(); result = firststring.compareto(secondstring); if (result == 0) { system.out.println("the strings equal, please try again."); } else if (result < 0) { system.out.println("lesser is: " + firststring); } else { // no need for: if (result > 0) { system.out.println("lesser is: " + secondstring); } } }
Comments
Post a Comment