import java.util.Scanner;//import Scanner
public class review{ //name of the program
public static void main(String[]args){ // main statement
Scanner i=new Scanner(System.in);
System.out.println("Enter a string");
String b=i.nextLine();
System.out.println("Enter a letter");
char c=i.next().charAt(0);
System.out.println("Answer is "+test1(b,c));
}
public static boolean test1(String a, char b){
boolean result= true;
for(int i=0;i<a.length();i++)
if(a.charAt(i)==b)
result =true;
else
result=false;
return result;
}
}
this program is looking for checking the char is in the string or not.
Hello, E = true
Hello, a = false
In this method test1, your forloop will traverse the whole line although it finds the letter into the string. so update it like this:
public static boolean test1(String a, char b){
for(int i=0;i<a.length();i++) {
if(a.charAt(i)==b)
return true;
}
return false;
}
Because, if the letter is found into the string you don't need to check further, hence:
if(a.charAt(i)==b) // if condition finds true path
return true; // so return true
Note that, return statement causes execution to leave the current function or tersely current subordinate.
You're never breaking out of the loop. Consider "Hello" and 'e'
see H: result = false
see e: result = true
see l: result = false...
break from the loop. Or, just use String.indexOf(char)
after each check you are changing result, without considering the option the the character is already found.
you can see is in twentylemon's answer.
i just wanted to say something that will be more correct and efficient.
insted of using break and return result you can do return true if the character is found.
in the end of the loop return false.
in this way, you dont need the result variable and the break.
this is how you write it as i suggested:
public static boolean test1(String a, char b)
{
for(int i=0;i<a.length();i++)
{
if(a.charAt(i)==b)
{
return true;
}
}
return false;
}
if you will check it, you will see how simple and good it is :)
Related
I'm trying to build a palindrome. I think I might be overthinking the solution with way too many conditional loops inside my if statement. I'm having trouble trying to update the while loop to check whether it has gone through and checked for equality throughout each character of the string, and to update it. Can someone point me in the right direction, and also how can I do a cleaner job with code?
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.isPalindrome("saippuakivikauppias");
main.isPalindrome("Hello World");
main.isPalindrome("Was it a car or a cat I saw");
}
private boolean isPalindrome(String word) {
int first = word.charAt(0);
int last = word.charAt(word.length() - 1);
if(word.length() <= 1) {
return true;
} else if(word.trim().length() > 1) {
if(Character.isLetter(first) && Character.isLetter(last)) {
while(first == last) {
first++;
last--;
//if loop to check if the while loop as gone through the entire string?
//update?
}
} else {
return false;
}
}
return false;
}
}
You really overthought this one - you should think a bit more basic about your problem:
A palindrome is a string that is the same read backward and forward -> create a reverse of word and compare to word
public static boolean isPalindrome(String word){
StringBuilder reverse = new StringBuilder(word).reverse();
return word.equals(reverse.toString());
}
You could even do this - depending on your coding style - in one line.
import java.util.*;
public class help {
public static void main(String[] args) {
System.out.print(isAllVowels("ugh".toLowerCase()));
}
public static boolean isAllVowels(String Str) {
if( Str.length() == 0) {
return true;
}
int b = Str.length();
for( int a=0; a<b; a++) {
char c = Str.charAt(a);
if(c!='a' || c!='e' || c !='i' || c!='o' || c!='u') {
return true;
}
}
return false;
}
}
Hi there, I'm new to java and the char comparing element that returns true always does so. I was wondering why it always does so? Additinally IntelliJ tells me that a is always less than b. Why is that so?
Thanks.
The problem isn't that you're using a ton of or statements.
You're confusing the meaning of and and or. and is exclusive, returning true if both conditions are satisfied. or is inclusive, returning true if either condition is satisfied.
Think about it like this: let's say you need to buy a new pair of shoes, but you're picky. The shoes must be blue and suede. A pair of blue Chuck Taylor All-Stars satisfies the first condition, but not the second. Will you buy the Chucks? False. Someone robs Graceland and steals a pair of Elvis Presley's shoes and offers them to you. The shoes are blue and suede. Will you buy them? True.
If you're a less picky person, you'll take blue shoes or suede shoes. Blue Chucks, brown suede loafers, tan suede slippers, or blue flip flops all meet one of two criteria, and will therefore be true.
Your code, in plain English, is asking "if the character is not a, e, i, o or u, return true." Even though u is a vowel, u is not a, not e, not i and not o, so it returns true.
Using a bunch of or just means if any one of those conditions is true, then return true.
if you are expecting the code to return true if all the characters in the string
are vowels and false if any one of the character is no-vowel,
check the following code.
public class help
{
public static void main(String[] args)
{
System.out.print(isAllVowels("aseiou".toLowerCase()));
}
public static boolean isAllVowels(String Str)
{
if( Str.length() == 0)
{
return true;
}
for( int a=0; a<Str.length(); a++)
{
char c = Str.charAt(a);
if(c=='a' || c=='e' || c =='i' || c=='o' || c=='u')
{
continue;
}
else return false;
}
return true;
}
}
The program is running as expected.
The condition
if(c!='a' || c!='e' || c !='i' || c!='o' || c!='u') will return true for your given input.
I need to write a short recursive program for a class that checks if a string - t is transformation of another string - s. It simply needs to check if every character in s is also in t.
For ex:
"sddbs" is not a transformation of "sdb"
"sddbs" is a transformation of "sddb".
public static boolean isTrans (String s, String t)
{
if (t.indexOf(s.charAt(0)) != -1)
return true;
else
return false;
return isTrans(s.substring(1), t);
}
And still.. the code doesn't work as expected. "unreachable statement" in the last line of the code.
The reason is quite simple:
there is no possible way to execute this line:
return isTrans(s.substring(1), t);
why?:
you have a return IF this condition (t.indexOf(s.charAt(0)) != -1) is met and another if not....
It's because of the Law of Excluded Middle. You can treat return as exit function.
public static boolean isTrans (String s, String t) {
if (condition)
return true;
else
return false;
//the condition must have been true or false so the method has already exited.
return isTrans(s.substring(1), t);
}
If the condition is true, you return true, if it's false you return false. Otherwise you call recursively. There is no otherwise.
You final return statement is unreachable because your method body contains return statement for both if and else condition, hence assuring that the last return statement will never be reached.
But besides this I don't understand why you need to write a recursive function, though a non-recursive function using similar method calls will do the same thing:
public static boolean isTrans (String s, String t)
{
if (t.indexOf(s) > -1)
return true;
else
return false;
}
Edit:
As suggested by #Holger you can avoid unnecessary if else and replace your code with:
public static boolean isTrans (String s, String t)
{
return (t.indexOf(s) > -1) //returns true or false just like your if else
}
or even shorter:
public static boolean isTrans (String s, String t)
{
return t.contains(s); //internally contains() calls indexOf(), similar to what you are doing
}
According to your recursion method once you enter the if condition it would either return a true or false output. so your code never reaches the recursion statement.
I would like to suggest my way of implementing your transformation program using recursion.
import java.util.Scanner;
public class Recursion {
static int flag;
public void isTransformation(String str1, String str2) {
flag = str2.length();
char ch1[], ch2[];
ch1 = str1.toCharArray();
ch2 = str2.toCharArray();
if (ch1[0] == ch2[0]) {
flag--;
if (flag == 0) {
System.out.println("Transformation");
return;
}
isTransformation(str1.substring(1), str2.substring(1));
} else
System.out.println("Not a Transformation");
}
public static void main(String args[]) {
String str1, str2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter string 1: ");
str1 = sc.nextLine();
System.out.print("Enter string 2: ");
str2 = sc.nextLine();
Recursion r = new Recursion();
if (str1.length() >= str2.length())
r.isTransformation(str1, str2);
else
r.isTransformation(str2, str1);
sc.close();
}
}
http://codingbat.com/prob/p126880
Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: str.toLowerCase() returns the lowercase version of a string.
I cannot get when it is true, it always gives false.
public boolean endOther(String a, String b)
{
//variables
a.toLowerCase();
b.toLowerCase();
String f1="";
String f2="";
int d=0;
int sum=0;
//Program code;
if(a.length()-b.length()>0)
{
(f1).equals(a);
(f2).equals(b);
d=a.length();
}
else if(a.length()-b.length()<0)
{
(f1).equals(b);
(f2).equals(a); //gett**ing bigger and lower String**
d=b.length();
}
else if((a).equals(b))
sum++;
// I think problem is because it is not enter the for.
for(int i=0; i>d; i++)
{
if((f1.substring(i,i+f2.length())).equals(f2))
sum++;
}
if(sum>0)
return true;
else
return false;
}
This is a working example of what you are trying to achieve to test in your Java IDE like Netbeans or Eclipse whatever. This is really simple, the String object has an endsWith method so why try to invent something yourself.
If you have any troubles reading this code hit me up, should be quite straight forward. You will just have to convert your string to lowercase, that's for you to add.
public class StringEnds {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.printf("String a: ");
String a = scanner.next();
System.out.printf("String b: ");
String b = scanner.next();
// Compare a and b
if (endsWith(a, b)) {
System.out.printf("Succes\n");
} else {
System.out.printf("Fail\n");
}
}
public static boolean endsWith(String firstString, String secondString) {
return firstString.endsWith(secondString) || secondString.endsWith(firstString);
}
}
Here's your codebat solution (it is quite short):
public boolean endOther(String a, String b) {
return a.toLowerCase().endsWith(b.toLowerCase()) || b.toLowerCase().endsWith(a.toLowerCase());
}
This is my answer. I tried both ways, hope it helps.
public boolean endOther(String a, String b) {
int small = Math.min(a.length(), b.length());
if (a.length()==b.length() && a.equalsIgnoreCase(b)) {
return true;
}
if (small==a.length()) {
if (b.substring(b.length()-small).equalsIgnoreCase(a)) {
return true;
}
// from here is the toLowerCase() method.
a = a.toLowerCase();
b = b.toLowerCase();
} else if (small==b.length()) {
if (a.endsWith(b)) {
return true;
}
}
return false;
}
First of all this is not homework. Just me practicing.
I'm trying to recursively determine the number of times "hi" appears in the given string, but in every case it skips to the last else if statement and things the string is empty. Any ideas?
Basically,
if(string starts with "hi")
increment count by 1 and recurse with the string after the 2nd index to skip over the "hi" it just counted
else if(string does not start with "hi" and string is not empty)
recurse with the string after its 1st index to see if it starts with "hi" the next time around.
else if(string is empty)
Print("End of text reached")
return count;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
This is a good opportunity to practice debugging recursive functions calls -- actually quite difficult. Suggestions:
use strategically placed print-statements to ensure that the arguments are being changed correctly from one recursive invocation to the next
refactor the order of case-analysis in the if-statement to make it more clear. For example, 1) check if the string is empty (base case), 2) check if the string starts with "hi", 3) catch-all -- not empty and doesn't start with "hi"
As #Steve mentioned, you have to use the return value that recur returns.
See below for a modified version of your code, I also simplified your if/else statements:
public int recur(String str, int counter) {
if (str.startsWith("hi")) {
return recur(str.substring(2), counter+1);
} else if (!str.isEmpty()) {
return recur(str.substring(1), counter);
} else {
System.out.println("End of text reached");
return counter;
}
}
public static void main(String args[]) {
String str = "xxhixhixx";
Practice p = new Practice();
System.out.println(p.recur(str, 0));
}
You aren't using the value returned from recur.
public int countHi(String str) {
if (str.length() <= 1) {
return 0;
}
int count = 0;
if (str.substring(0, 2).equals("hi")) {
count = 1;
}
return count + countHi(str.substring(1)); //substring off
}
All this does is recursively count the number of the String "hi" inside a larger String. The rest of the implementations should be a piece of cake, happy Coding!
Your program printing 'End of text' is correct as finally as per the logic it will reach there, reason for count always coming as 0 is that in every iteration they change there own copy and finally when the termination condition is reached(String is empty) the result is popped out of the stack, hence final outcome that you receive is the pop of the first iteration where count was 0, so you have to return the value returned by recur at every step instead of returning count.
public static int recursive(String givenStr) {
int count =0 ;
Pattern pattern = Pattern.compile("hi");
Matcher match = pattern.matcher(givenStr);
while(match.find()){
System.out.println(match);
count++;
}
return count;
}
This Will return number of times "hi" has appeared into the String