I have a simple program run in the console which accepts inputs, creates objects based on these and saves those objects into a list. If however a "x" is entered, the function stops.
public static void input(List<Things> slist) {
String strA = new java.util.Scanner(System.in).nextLine();
if(!xcheck(strA) {return;}
Things s = new Things(strA);
slist.add(s);
}
public static boolean xcheck(String xStr){
if(xStr == "x"){
return false;
} else {
return true;
}
}
The problem is that the function xcheck never returns false. It does recognise that the input string contains "x" (xStr.contains("x")), but it doesn't seem to think that the input is only "x", even though when ouptutting the string into the console, it definately only outputs the "x" without anything else and the length of the String is 1.
Strings are comared with equals not ==.
Try:
public static boolean xcheck(String xStr){
if("x".equals(xStr)){
return false;
} else {
return true;
}
}
Use xStr.equals("x") instead of xStr == "x".
Related
I am more interested about why does not the return function work. Not about the optimization or my method of thinking.
I have tried a simple program to check recursively if a String is palindrome or not.
package palindrom;
public class PalindromString {
public static boolean isPalindrom(String myText) {
char f = myText.charAt(0);
char l = myText.charAt(myText.length() - 1);
if (f != l) {
return false;
}
else {
if (myText.length() > 1) {
isPalindrom(myText.substring(1, myText.length() - 1));
} else {
return true;
}
}
return true;
}
public static void main(String[] args) {
String text = "cococbc";
System.out.println(isPalindrom(text));
}
}
For the first step , the program takes that first "c" char and the last one and it compares them, then the function is called again , this time with the "ococb" String.
The function takes the "o" char and "b" , it compares them , it sees that they are not equal , it goes to the "return false;" statement , and yet it returns true ?
Can you help me with this ? I really want to understand why it behaves this way :|.
it sees that they are not equal , it goes to the "return false;" statement , and yet it returns true ?
Yes, isPalindrom("ococb") returns false, but when that recursive call returns, you ignore its return value, and therefore isPalindrom("cococbc") returns true. You need to return isPalindrom(myText.substring(1, myText.length() - 1)) in order to fix that.
Besides that issue, you should also change the condition to require myText.length() is at least 3, otherwise you may pass an emptyString` to the recursive call, since you are removing the first and last characters.
if (myText.length() >= 3) {
return isPalindrom(myText.substring(1, myText.length() - 1));
} else {
return true;
}
After you make that change you should remove the final return true;, which will no longer be reachable.
You might also consider adding a check for a null or empty String at the beginning, in order for your method not to throw an exception when called for a null or empty String.
import java.util.Scanner ;
public class ProcessNumbers
{
public static void main( String[] args )
{
Scanner in = new Scanner(System.in) ;
System.out.print("Please enter an integer between 6 and 12, inclusive: ") ;
int num = in.nextInt() ;
boolean result = shouldProcess(num);
String result1 = String.valueOf(result) ;
}
public static boolean shouldProcess(int n)
{
if (n>=6 && n<12)
{
return true;
}
else
{
return false;
}
}
public static boolean processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
return result2 ;
}
}
now I am getting the output which is partially right but has forgot the yes or no output in the second method
Please enter an integer between 6 and 12, inclusive:
when it should also include the yes or not output
You are sending in a boolean value in the method parameter of processInput but you are catching it as a String. You need to change it to boolean. Further, you want to check if its value is true with equal signs like below:
public static void processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
}
EDIT 2:
Also, you need to change String result1 = String.valueOf(result); to processInput(result);
EDIT 3:
If you want the number printed too that you just entered and then you want a "yes" or "no", then between int num = in.nextInt(); and boolean result = shouldProcess(num);, add this line: System.out.println(num);
There's apparently some code missing, so I'm guessing this is just part of the full thing. So I will only tackle your output issue.
I won't talk about the code in: public static boolean processInput(boolean result2), because you're not running it anywhere in your main method public static void main( String[] args ) anyway.
Now, in your code at:
public static boolean shouldProcess(int n)
if you look at your code, you are assigning the value of the boolean to the new String result1, so result1 now has the new value, but you are not running its output anywhere, so there's no way the program can guess you want to output that value. You need to assign the output:
System.out.print(result1);
However, if you only want to output the boolean, there's no need to assign that boolean value to a new String and then output the new String, you could just:
System.out.print(result);
Unless you're going to use that value somewhere else where creating a new variable would arguably be a good choice.
Also, it seems you want to return either a "Yes" or "No" on your class: public static boolean processInput(boolean result2).
Remember a class that does not return a value, but rather executes a code, has to be written as void. In other words, your:
public static boolean processInput(boolean result2)
should really be:
public static void processInput(boolean result2)
Because if not, you are just making your program return result2;, which in this case can only be either true or false. By adding void to the class, makes the class understand it will be executing your System.out.print code, rather than returning a value for you to use. But also, depends on what you want to afterwards.
I am writing a Data Acquisition Software using Sparrow's platform Kmax. This platform has it's own classes and methods, that one has to have worked with it to be familiar. I am trying to make a checkbox button to do a job. To do that, I need to convert a string 1 or 0 to boolean true or false respectively. For this task I built the simple method that follows
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
}
When I am trying to compile it I get an error
Runtime.java:30: error: missing return statement }
Note that line 30 is the last line(i.e. } ) of the previous code.
I don't see any point on what could be wrong. Any ideas?
Say those cases aren't true (that s is not equal to "1" or "0"), then what? You must return a default value at the end (which doesn't seem to be a good idea for your code if you are only expecting those two values) or throw an Exception:
public static boolean stringToBool(String s) {
if (s.equals("1")){
return true;
}
if (s.equals("0")){
return false;
}
throw new Exception("0 or 1 Required");
}
There needs to be a return statement executed in all cases, but you don't have a return statement if both if statements are false.
Provide a default case at the end:
return true;
}
The compiler does not know that your String will always be "1" or "0". Therefore, as a safety measure, it ensures that you are required to return some value (although you may never actually return it in practice).
I suggest you return false by default.
public static boolean stringToBool(String s) {
if (s.equals("1")){
return true;}
if (s.equals("0")){
return false;}
return false;
}
You have several options. You code cannot compile because your code must have a return statement always, but, when you put it within the if statemens the compiler cannot find a return for every possible execution path.
public static final String TRUE = "1";
public static final String FALSE = "0"
public static boolean stringToBool(String s) {
boolean result = false;
if (s.equals(TRUE)){
return true;
}
return result;
}
public static boolean stringToBool2(String s) {
boolean result = false;
switch(s) {
case FALSE:
result = false;
break;
case TRUE:
result = true;
break;
default:
// Uuups. Throw exception or return false
}
return result;
}
I am interested in a very simple string verification problem to see if the starting character in a string starts with an upper case letter and then have the console to display true or false. From my understanding you wouldn't have to invoke something like System.console().printf("true", s) in order to make this happen. I could swear I've seen similar elementary implementations achieved using the following sample code:
public class Verify {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
but when I run this, nothing displays. If I make a slight modification by adding in conditional printouts before returning T/F, e.g.
public class Verify2 {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
System.out.println("yep");
return true;
}
else {
System.out.println("nope");
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
the issue is somewhat resolved, as the console displays either "yep" or "nope", yet unresolved because I just want the console to display true or false. That's it. Advice?
As the question has already been answered, I'd like to point out there is no need for RegExes to solve this (and they are expensive operations). You could do it simply like this:
static boolean startsWithUpperCase(String toCheck)
{
if(toCheck != null && !toCheck.isEmpty())
{
return Character.isUpperCase(toCheck.charAt(0));
}
return false;
}
yet unresolved because I just want the console to display true or false
Calling checkStartChar method will return value, that doesn't mean it will print value to console. You need to code how you would like to handle return value. If you want to print return value, then you should do:
System.out.println(checkStartChar(str));
Will print what ever the return of checkStartChar method
if(s.startsWith("[A-Z]")){
String.startsWith(prefix) doesn't take regex as a parameter, you should be using regex APi instead.
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(new Character(s.charAt(0)).toString());
if(m.find()){
return true;
}else{
return false;
}
String str = "AbCD";
System.out.println(checkStartChar(str));
Output:
true
In your code checkStartChar(str); is returning a boolean value which is not being used in your program.Then if you want to display true or false then you can use.
System.out.println(checkStartChar(str));
Hello
Why my reverse method that uses recursion isn't working?
The print statement shows that the operation is done correctly but at the end it seems like only the very ast char of the entire String is assigned to h.
public static String reverse(String s,String h){
if(s.length()==0){
return s;
} else {
h+=s.charAt(s.length()-1);
System.out.println(h);//FOR TEST
s=s.substring(0,s.length()-1);
reverse(s,h);
return h;
}
}
Any advice?
Use
return reverse(s,h);
instead of
return h;
i.e:
public static String reverse(String s,String h){
if(s.length() == 0){
return h;
} else {
h+=s.charAt(s.length()-1);
System.out.println(h);//FOR TEST
s=s.substring(0,s.length()-1);
return reverse(s,h); //NOTICE THE CHANGE HERE,
}
}
Strings in Java are immutable. So in this code:
private static void foo(String x) {
x += "bar";
}
public static void main() {
String a = "foo";
foo(a);
System.out.println(a);
}
Only "foo" will be printed. It works the same way as if the type were int.
So your reverse function needs to do something with the return value. When you call reverse(s,h) you are throwing away the return value from the recursive call. You need to incorporate it:
String rec = reverse(s,h);
return ... something involving rec ...;
2 things:
public static String reverse(String s,String h){
if(s.length()==0){
return h; /// This needs to return the reversed string (h).
} else {
h+=s.charAt(s.length()-1);
System.out.println(h);//FOR TEST
s=s.substring(0,s.length()-1);
h = reverse(s,h); /// You need to use the return value
return h;
}
}
It looks like you were trying to change h using a return-by-reference-parameter. You have to remember that in Java everything (including references to objects) is passed by value. Once you write s=s.substring(0,s.length()-1);, s becomes a reference to a different String object, and that change is not propagated to the calling function.
Also, there is a way to implement this with only one input parameter.
I think this way is better for reversing a string using a recursive method :
public class Reversestringbyrecursivefunction {
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
while(true)
{
System.out.print("[?] Enter String('q' for exit)> ");
String str=input.next();
if(str.equals("q"))
break;
System.out.println("this string created by reversed recursive function : "+revers(str));
System.out.print("\n==========================\n");
}
System.out.print("\n\n\t\t\t[ GOOD LUCK!!! ]\n");
}
static String revers(String str)
{
if(str.length()<=1)
return str;
else
return revers(str.substring(str.length()-1, str.length()))+revers(str.substring(0, str.length()-1));
}
}
but , for best performance you should change this line :
return revers(str.substring(str.length()-1, str.length()))+revers(str.substring(0, str.length()-1));
to :
return str.substring(str.length()-1)+revers(str.substring(1, str.length()-1)+str.substring(0,1);
in prior line: in best performance and in one stage you can swap only 1 character of input string . but , in new line: in one stage you can swap 2 character of input string