I am currently writing a palindrome tester in Java for a class I am taking in high school. I have asked my teacher for assistance and he is also confused as well. I was hoping the community on stackoverflow could help me out. Thank you.
public class Palindrome
{
private String sentence;
public Palindrome(String s)
{
sentence = s;
}
public boolean isPalindrome()
{
if(sentence.length() <= 1)
{
return true;
}
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
else
return false;
}
}
You need return isPalindrome();. Otherwise the method isn't returning anything in that case, and it's declared to return a boolean.
Change
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
to
if (sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
In order to have the method complied, JVM need to make sure the method has a return statement for every possible case (which is something you haven't done).
If your code takes this path there is no return statement. If your teacher is confused, you need a new teacher.
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
isPalindrome();
}
your last if clause misses a return, if you really want to return false in the else-clause.
You want to use a recursive way to check if the sentence is palindrome. you'd better to return isPalindrome() method inside following snippet
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
This is my code:
public class palindrome
{
private String sentence;
public palindrome(String s)
{
sentence = s;
}
public boolean isPalindrome()
{
if(sentence.length() <= 1)
{
return true;
}
if(sentence.charAt(0) == sentence.charAt(sentence.length()-1))
{
sentence = sentence.substring(1, sentence.length()-1);
return isPalindrome();
}
else
return false;
}
public static void main(String [] args)
{
palindrome p=new palindrome("aabbaa");
if(p.isPalindrome())
System.out.println("yes");
else
System.out.println("no");
}
}
Related
I'm trying to increase numberOfQuestion by 1 at any time I call isOdd() method as shown below. I got an error said "
unreachable code
". how I could do it right?!
import java.util.Scanner;
public class Geek {
private String geekName;
private int numberOfQuestion;
public Geek (String name) {
geekName=name;
numberOfQuestion=0;
}
public int getNumberOfQuestion() {
return numberOfQuestion;
}
public boolean isOdd(int num) {
if(num%2==0) {
return false;
}
else {
return true;
}
numberOfQuestion++;
}
}
Put numberOfQuestions++ as the first line in method public boolean isOdd(intNum)
The message is correct, your line is unreachable since you return from method before incrementing it.
numberOfQuestion++; is considered unreacheable code because in either case:
if num is odd, your method returns true and exit the method.
if num is even, your method returns false and exit the method as well.
As you can see there is no way it will be able to reach the line:
numberOfQuestion++;
Hence, if you want to do something, you need to do it before your method ends:
public boolean isOdd(int num) {
//whatever you want to do here.. such as numberOfQuestion++;
return (num % 2 != 0);
}
put the increace statement at first line:
public boolean isOdd(int num) {
numberOfQuestion++;
if(num%2==0) {
return false;
}
return true;
}
At last line it is unreachable, because you return in if and in else
After return method closed and numberOfQuestion++ never done.
You need this:
public boolean isOdd(int num) {
numberOfQuestion++;
if(num%2==0) {
return false;
}
else {
return true;
}
}
It is because in function 'isOdd', whatever the 'num' may be, the function get returned and the last line,
numberOfQuestion++;
will never execute, So it's an unreachable code.
just make the code like this,
public boolean isOdd(int num) {
numberOfQuestion++;
if(num%2==0) {
return false;
}
else {
return true;
}
}
For my CS class, I had to create a boolean function isBalanced(String x) that takes a string and evaluates the amount of brackets/parentheses and returns true if the brackets match up to its pair (e.g; { is a pair of }, ( is a pair of ), [ is a pair of ], etc.). The function would return true if the brackets correctly matched up, false if otherwise. For clarification, MyStack() is my own implementation of the Java stack interface if you are wondering what that Object was.
Examples of how the code would work and return:
{A(B[C])D} would return true.
{A(B[C)]D} would return false.
The problem in my code is a logic error. For some reason, my function is returning true if there is a missing bracket, which should return false.
{A(B)C would return false, but my code reads it as true. Do you have any solutions that would help my code work properly? Thanks!
Balancer.java
public static boolean isBalanced(String x) {
MyStack<String> stack = new MyStack();
if (x.substring(0,1).equals("}") || x.substring(0,1).equals(")") || x.substring(0,1).equals("]")) {
return false;
}
for (int i=0; i<x.length(); i++) {
if (x.substring(i,i+1).equals("{") || x.substring(i,i+1).equals("(") || x.substring(i,i+1).equals("[")) {
stack.add(x.substring(i,i+1));
}
if (x.substring(i,i+1).equals("}") || x.substring(i,i+1).equals(")") || x.substring(i,i+1).equals("]")) {
if (x.substring(i,i+1).equals("}") && stack.peek().equals("{")) {
stack.pop();
} else if (x.substring(i,i+1).equals(")") && stack.peek().equals("(")) {
stack.pop();
} else if (x.substring(i,i+1).equals("]") && stack.peek().equals("[")) {
stack.pop();
} else {
return false;
}
}
}
return true;
}
This file, labeled Main.java, is just a tester. I have omitted the other cases where the code works. The reason why the function should return false is that there is a missing } which should be at the end, but there is none, yet my function returns true for some reason.
Main.java
public static void main(String[] args) {
...
String test4 = "{AA[B(CDE{FG()T})V]";
System.out.println("Missing final close (empty stack case)");
System.out.println("Should be false, is: " + Balancer.isBalanced(test4)); // does not work
}
You have a series of conditions that only pop the stack if a matching pair of brackets are found. I think you're overcomplicating things - if an opening bracket is found, push it to the stack. If a closing parenthesis is found, pop the stack and make sure that they match. E.g.:
private static final Map<Character, Character> CLODSE_TO_OPEN = new HashMap<>();
static {
CLODSE_TO_OPEN.put(')', '(');
CLODSE_TO_OPEN.put(']', '[');
CLODSE_TO_OPEN.put('}', '{');
}
public static boolean isBalanced(String x) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < x.length(); ++i) {
char c = x.charAt(i);
if (CLODSE_TO_OPEN.containsValue(c)) {
stack.push(c);
} else if (CLODSE_TO_OPEN.containsKey(c)) {
try {
if (!CLODSE_TO_OPEN.get(c).equals(stack.pop())) {
return false;
}
} catch (EmptyStackException e) {
return false;
}
}
}
return stack.isEmpty();
}
I am getting output as false, everytime.
My aim is to print true, if String t is present in the same order in String s.
For example:
String s = "gagbgcgd";
String t = "abcd";
Expected output:
true
String s = "gagcgdgb";
String t = "abcd";
Expected output:
false
Here is the code.
public class StringCompare {
public static boolean stringCompare(String t,String s) {
if (t.length() == 0) {
return true;
}
if (s.length() == 0) {
return false;
}
if (t.charAt(0) == s.charAt(0)) {
stringCompare(t.substring(1), s.substring(1));
}
else {
stringCompare(t, s.substring(1));
}
return false;
}
public static void main(String[] args) {
String s = "acaoadaianaga";
String t = "coding";
System.out.println(stringCompare(t,s));
}
}
When you recurse, you don't return the result of the recursion. Change
if(t.charAt(0)==s.charAt(0)){
stringCompare(t.substring(1), s.substring(1));
}
else{
stringCompare(t, s.substring(1));
}
to something like
if(t.charAt(0)==s.charAt(0)){
return stringCompare(t.substring(1), s.substring(1));
}
else{
return stringCompare(t, s.substring(1));
}
The main problem of your code is in the first execution of the recursion always return false no matter what the return value of remaining execution in the recursion.
You should change your code to something like:
if(t.charAt(0)==s.charAt(0)){
return stringCompare(t.substring(1), s.substring(1));
}
else{
return stringCompare(t,s.substring(1));
}
and remove the last return false; statement.
This is because the outer recursive calls you always returns false
except
if(t.length()==0){return true;}
look at Elliott Frisch's answer.
You should use .contains. Example:
boolean istrue = t.contains(s);
This question already has answers here:
How to check if a String is numeric in Java
(41 answers)
Closed 6 years ago.
I have a gpa program, and it works with the equalsIgnoreCase() method which compares two strings, the letter "a" to the user input, which checks if they put "a" or not. But now I want to add an exception with an error message that executes when a number is the input. I want the program to realize that the integer input is not the same as string and give an error message. Which methods can I use to compare a type String variable to input of type int, and throw exception?
Many options explored at http://www.coderanch.com/t/405258/java/java/String-IsNumeric
One more is
public boolean isNumeric(String s) {
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
Might be overkill but Apache Commons NumberUtils seems to have some helpers as well.
If you are allowed to use third party libraries, suggest the following.
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html
NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean
Use this
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
}catch (NumberFormatException e) {
ret = false;
}
return ret;
}
You can also use ApacheCommons StringUtils.isNumeric - http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isNumeric(java.lang.String)
Simple method:
public boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
public boolean isOnlyNumber(String value) {
boolean ret = false;
if (!isBlank(value)) {
ret = value.matches("^[0-9]+$");
}
return ret;
}
Use below method,
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
If you want to use regular expression you can use as below,
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
public static boolean isNumeric(String string) {
if (string == null || string.isEmpty()) {
return false;
}
int i = 0;
int stringLength = string.length();
if (string.charAt(0) == '-') {
if (stringLength > 1) {
i++;
} else {
return false;
}
}
if (!Character.isDigit(string.charAt(i))
|| !Character.isDigit(string.charAt(stringLength - 1))) {
return false;
}
i++;
stringLength--;
if (i >= stringLength) {
return true;
}
for (; i < stringLength; i++) {
if (!Character.isDigit(string.charAt(i))
&& string.charAt(i) != '.') {
return false;
}
}
return true;
}
I wrote this little method lastly in my program so I can check if a string is numeric or at least every single char is a number.
private boolean isNumber(String text){
if(text != null || !text.equals("")) {
char[] characters = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
if (characters[i] < 48 || characters[i] > 57)
return false;
}
}
return true;
}
You can use Character.isDigit(char ch) method or you can also use regular expression.
Below is the snippet:
public class CheckDigit {
private static Scanner input;
public static void main(String[] args) {
System.out.print("Enter a String:");
input = new Scanner(System.in);
String str = input.nextLine();
if (CheckString(str)) {
System.out.println(str + " is numeric");
} else {
System.out.println(str +" is not numeric");
}
}
public static boolean CheckString(String str) {
for (char c : str.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
}
Here's how to check if the input contains a digit:
if (input.matches(".*\\d.*")) {
// there's a digit somewhere in the input string
}
To check for all int chars, you can simply use a double negative.
if (!searchString.matches("[^0-9]+$")) ...
[^0-9]+$ checks to see if there are any characters that are not integer, so the test fails if it's true. Just NOT that and you get true on success.
This is the question:
Problem I.
We define the Pestaina strings as follows:
ab is a Pestaina string.
cbac is a Pestaina string.
If S is a Pestaina string, so is SaS.
If U and V are Pestaina strings, so is UbV.
Here a, b, c are constants and S,U,V are variables. In these rules,
the same letter represents the same string. So, if S = ab, rule 3
tells us that abaab is a Pestaina string. In rule 4, U and V represent
Grandpa strings, but they may be different.
Write the method
public static boolean isPestaina(String in)
That returns true if in is a Pestaina string and false otherwise.
And this is what i have so far which only works for the first rule, but the are some cases in which doesnt work for example "abaaab":
public class Main {
private static boolean bool = true;
public static void main(String[] args){
String pestaina = "abaaab";
System.out.println(pestaina+" "+pestainaString(pestaina));
}
public static boolean pestainaString(String p){
if(p == null || p.length() == 0 || p.length() == 3) {
return false;
}
if(p.equals("ab")) {
return true;
}
if(p.startsWith("ab")){
bool = pestainaString(p, 1);
}else{
bool = false;
}
return bool;
}
public static boolean pestainaString(String p, int sign){
String letter;
char concat;
if("".equals(p)){
return false;
}
if(p.length() < 3){
letter = p;
concat = ' ';
p = "";
pestainaString(p);
}else if(p.length() == 3 && (!"ab".equals(p.substring(0, 2)) || p.charAt(2) != 'a')){
letter = p.substring(0, 2);
concat = p.charAt(2);
p = "";
pestainaString(p);
}else{
letter = p.substring(0, 2);
concat = p.charAt(2);
pestainaString(p.substring(3));
}
if(letter.length() == 2 && concat == ' '){
if(!"ab".equals(letter.trim())){
bool = false;
//concat = 'a';
}
}else if((!"ab".equals(letter)) || (concat != 'a')){
bool = false;
}
System.out.println(letter +" " + concat);
return bool;
}
}
Please tell me what i have done wrong.
I found the problem i was calling the wrong method.
You are describing a Context Free Language, which can be described as a Context Free Grammer and parsed with it. The field of parsing these is widely researched and there is a lot of resources for it out there.
The wikipedia page also discusses some algorithms to parse these, specifically - I think you are interested in the Early Parsers
I also believe this "language" can be parsed using a push down automaton (though not 100% sure about it).
public static void main(String[] args) {
// TODO code application logic here
String text = "cbacacbac";
System.out.println("Is \""+ text +"\" a Pestaina string? " + isPestaina(text));
}
public static boolean isPestaina(String in) {
if (in.equals("ab")) {
return true;
}
if (in.equals("cbac")) {
return true;
}
if (in.length() > 3) {
if ((in.startsWith("ab") || in.startsWith("cbac"))
&& (in.endsWith("ab") || in.endsWith("cbac"))) {
return true;
}
}
return false;
}
That was fun.
public boolean isPestaina(String p) {
Set<String> existingPestainas = new HashSet<String>(Arrays.asList(new String[]{"ab", "cbac"}));
boolean isP = false;
int lengthParsed = 0;
do {
if (lengthParsed > 0) {
//just realized there's a touch more to do here for the a/b
//connecting rules...I'll leave it as an excersize for the readers.
if (p.substring(lengthParsed).startsWith("a") ||
p.substring(lengthParsed).startsWith("b")) {
//good connector.
lengthParsed++;
} else {
//bad connector;
return false;
}
}
for (String existingP : existingPestainas) {
if (p.substring(lengthParsed).startsWith(existingP)) {
isP = true;
lengthParsed += existingP.length();
}
}
if (isP) {
System.err.println("Adding pestaina: " + p.substring(0, lengthParsed));
existingPestainas.add(p.substring(0, lengthParsed));
}
} while (isP && p.length() >= lengthParsed + 1);
return isP;
}