checking if first char is equal to last char - java

I'm fairly new to java and I was wondering on how to return my code to false if the 1st and last letter aren't the same
he whole instruction was to define and test a method called checkString that will take in the word as a parameter and checks whether the String begins and ends with the same letter. If both letters are the same the method returns true otherwise false (returns a boolean). The program treats lower and uppercase letters as equivalent
here's what I have:
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("%s begins and ends with the same letter.", checkString(word));
}
public static boolean checkString (String word) {
int stringLength = word.length();
String letter1 = (word.substring (0,1)).toUpperCase();
String lastletter = (word.substring ((stringLength-1),(stringLength))).toUpperCase();
if (letter1.equals(lastletter)){
return true;
} else {
return false;
}
}
}

As per your code; instead of:
if (letter1.equals(lastletter)) {
return true;
} else {
return false;
}
Just do:
return letter1.equals(lastletter);
However your checkString() {...} code should be:
public static boolean checkString (String word) {
int len = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(len - 1);
return firstLetter == lastLetter;
}
Also instead of:
System.out.printf (word + " begins and ends with the same letter.", checkString(word));
Use print():
System.out.print(word + " begins and ends with the same letter: " + checkString(word));
Edit:
If you want to use printf() try something like:
System.out.printf("%s begins and ends with the same letter. %s", word , checkString(word));
%s is like a place holder for word and the value returned by checkString(word).

You could do the following:
public boolean firstAndLast(String word)
{
return Character.toUpperCase(word.charAt(0)) == Character.toUpperCase(word.charAt(word.length()-1));
}
This checks the positions of 0 and length - 1 to see if they're equal to each other. If they are, it returns true, if not, false.

If you want to one-line it:
return (word.substring (0,1)).toUpperCase().equals(word.substring(word.length()-1).toUpperCase());
Before the .equals(...) it fetches the first character, converts it to one case, doesn't matter which one as long as you are using the same case later on.
word.substring(string.length()-1).toUpperCase();
Fetches the last key and converts it to upper case.
This is how I would write it most likely
private boolean isFirstAndLastEqual (String word) {
char first = Character.toUpperCase(word.charAt(0));
char last = Character.toUpperCase(word.charAt(word.length()-1));
return first == last;
}

You do not need such a complicated code.
Here is a very simple written method that does the work perfectly.
Code
public static boolean checkString (String word) {
return word.toLowerCase().charAt(0) == word.toLowerCase().charAt(word.length()-1);
}
Explaination
It compares the first and the last character of the String input put to lowercase so that it matches the lower and uppercases.

Your use of printf is wrong as you are not printing out the true/false value. Either add a boolean specifier to your output string or use println instead.
System.out.printf (word + " begins and ends with the same letter - %b\n", checkString(word));
System.out.println (word + " begins and ends with the same letter " + checkString(word));

You could do the following
public static boolean checkString(final String word) {
final String checkedString = word.toLowerCase();
final char[] chararray = checkedString.toCharArray();
if (chararray.length > 1) {
return chararray[0] == chararray[chararray.length-1];
} else {
return true;
}
}
This will convert the String to lower case. (You could also achieve this with word.toUpperCase();) After that the String is converted to a char Array and then checks the first and the last "char". if the given String is of length "0" then true will be returned. Depending on how you want to decide for emtpy Strings you could also change this to false

This should give you what you're looking for.
This gets the first letter (character at index 0): firstletter = (word.charAt(0)).toUpperCase();
This gets the last letter: firstletter = (word.charAt(0)).toUpperCase();The last character is at index word.length-1. For example, if your word is "apple", it has a length of 5, but the last character is at index 4 (remember, 0-4 not 1-5; letter1 is misleading, it's actually letter0).
As mentioned by Savior Self, using charAt is more efficient. Also, being that you'd use char's rather than String's and == to compare them.
Also, you would assign the return value to a variable when you call checkString. For instance, boolean checkStr = checkString(word); and then use checkStr in your print statement.
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
boolean checkStr = checkString(word);
System.out.println(word + " begins and ends with the same letter: " + checkStr;
}
public static boolean checkString (String word) {
char firstletter = (word.charAt(0)).toUpperCase();
char lastletter = (word.charAt(word.length-1)).toUpperCase();
return (firstletter == lastletter);
}
}
Also, since I don't have enough points to comment, a better one-liner would be:
return (word.charAt(0)).toUpperCase() == (word.charAt(word.length-1)).toUpperCase());

Related

charAt(0) Not returning first number but second

Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Assignment_4_Piglatin {
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
String vowels = "aeiou";
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
if (vowels.contains(String.valueOf(word.charAt(index)))) {
System.out.print(index);
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
}
}
}
System.out.println(firstVowel);
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:
String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
if(vowels.contains(String.valueOf(word.charAt(i)))){
System.out.println(word.charAt(i));
break;
}
}
Please note that you need to do toLowerCase on the actual word in order for contains to work.
There are a few problems I can see off the bat, but the one that is likely causing this error is in these lines:
String firstNumber = Integer.toString(index);
firstVowel = Character.toString(firstNumber.charAt(0));
Think about what this is doing. First, you are making a String out of the index value, then you are saying that the first vowel is at the 0th index of that string.
Think of this example: hello
The program will run and assign "4" to firstNumber and firstVowel which isn't what you want.
However, if you only have one vowel, your program will "work".
What happens if you have over ten vowels? I know this isn't a realistic example, but say it happens. Your program will assign the index of the last vowel to firstNumber (say it's 15), then it will assign the first character of that to firstVowel (1). This doesn't make much sense at all, does it, especially if you don't have a vowel in index 1.
The main problem you are encountering for words less than 10 letters in length is that you are not just outputting the second number, you are outputting the last one. One way I like to deal with this is to go through the code and put in print statements where I'm not sure what a certain value is. For example, I'd put another print statement in your loop which tells you what letter you're looking at, like so:
System.out.println("LETTER: "+ String.valueOf(word.charAt(index)));
This will help you avoid confusion. The proper way to do this problem would be to use a break statement, such as in Darshan's answer. Alternatively, you could use the properties of the for loop:
firstVowel = "";
for (int index = 0; index < word.length() && firstVowel == ""; index++) {
CODE
}
Note that the second part of the for loop is a conditional statement. You already know that this can be used to cycle through the word's characters, but you can insert any logical statement there that you want. For this example, I set the default value of firstVowel to "" (setting it to null is a faux-pas, but that's another story). Then, each time the loop runs, it checks to see if the value of firstVowel has been changed, which will of course happen on the first time a vowel is run through the loop.
So in short, you need to modify the two lines at the beginning of my post and you need to find a way to break your loop when you find the first vowel. One solution has been given here, and another in Darshan Mehta's post.
public static void main(String[] args) {
Scanner userWord = new Scanner(System.in);
System.out.println("K. Caleb Swallow");
System.out.println("Welcome to the Pig Latin Translator!");
boolean run = true;
while (run) {
System.out.println("Please enter a word(or press Q to quit):");
String firstLetter = "something";
String firstVowel = "test";
String word = userWord.next();
ArrayList<Character> vowels = new ArrayList<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
if (word.equals("Q")) {
System.exit(0);
}
firstLetter = Character.toString(word.charAt(0));
if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
System.out.println(word + "way");
} else {
for (int index = 0; index < word.length(); index++) {
char indchar = word.charAt(index);
if (vowels.contains(word.charAt(index))) {
System.out.println(index);
firstVowel = Character.toString(word.charAt(index));
System.out.println(firstVowel);
index = word.length();
}
}
}
}
}
This is how I would do it. I changed the vowels String to an ArrayList so you can easily check if the char in the String word with the index is a vowel and the code works absolutely fine. It returns you the index where the first vowel is and what vowel it is.

Pig Latin String Encryption

I am writing a program that takes a string, splits it into words, converts the words into pig latin, and then returns the result string. I have it working to a certain point.
For example if I enter these words that do not start with a vowel into the program I get:
pig -> igpay
trash -> rashtay
duck -> uckday
(for words that do not start with vowels, they have their first letter removed, added to the end of the word along with "ay")
It also works when the word starts with a vowel (just take the word and add "yay" to the end).
For example if I enter these words into the program I get:
eat -> eatyay
areyay -> areyay
omelet -> omeletyay
Now the issue I am having is if I combine 2 words, one that starts with a vowel and one that doesn't, it prints out both like they both start with vowels.
For example if I enter these words into the program I get:
pig -> pigyay (should be igpay)
eat -> eatyay (correct)
It might be worth mentioning that the methods "isVowel" & "pigLatinEncrypt" are required to have in this program. Please disregard the other methods that are in the program.
public static void main(String[] args) {
// TODO code application logic here
String input, message;
int ans1, ans2, key;
input = JOptionPane.showInputDialog("1. to decrypt a message\n2. to encrypt a message");
ans1 = Integer.parseInt(input);
input = JOptionPane.showInputDialog("1. for an entire message reversal encryption\n"
+ "2. for a Pig-Latin encryption\n3. for a simple Caesar style encryption");
ans2 = Integer.parseInt(input);
if (ans2 == 3) {
input = JOptionPane.showInputDialog("Please enter a key for encryption");
key = Integer.parseInt(input);
}
input = JOptionPane.showInputDialog("Please enter the message to encrypt or decrypt");
message = input;
if (ans2 == 1) {
reverseEncryptandDecrypt(message);
}
if (ans2 == 2) {
String[] words = message.split(" ");
if (ans1 == 2) {
boolean isVowel = isVowel(words);
pigLatinEncrypt(words, isVowel);
}
if (ans1 == 1) {
pigLatinDecrypt(message);
}
}
}
public static void reverseEncryptandDecrypt(String message) {
char[] stringToCharArray = message.toCharArray();
System.out.print("You entered the message: ");
for (char c : stringToCharArray) {
System.out.print(c);
}
int i = stringToCharArray.length - 1, j = 0;
char[] reverse = new char[stringToCharArray.length];
while (i >= 0) {
reverse[j] = stringToCharArray[i];
i--;
j++;
}
System.out.print("\n\nThe result is: ");
for (char c : reverse) {
System.out.print(c);
}
System.out.println();
}
public static void pigLatinEncrypt(String[] words, boolean isVowel) {
for (String word : words) {
if (isVowel == true) {
System.out.print(word + "yay ");
} else {
System.out.print(word.substring(1) + word.substring(0, 1) + "ay ");
}
}
}
public static boolean isVowel(String[] words) {
boolean isVowel = false;
for (String word : words) {
if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o")
|| word.startsWith("u")) {
isVowel = true;
}
}
return isVowel;
}
}
This method:
public static void pigLatinEncrypt(String[] words, boolean isVowel)
takes an array of words and a single isVowel boolean. Thus, if there is more than one word, and some, but not all, of them begin with vowels, there's no way to tell the method that.
You'll need to change the method definition. Either it should take only one word String (simplest), or it needs to take an array of isVowel booleans that correspond to the array of word
Edit: When I wrote this, I didn't look carefully at the rest of your code. But the isVowel method has the same problem: it takes an array of words, but returns a single boolean. This can't work, for the same reason--if some of the words start with vowels and some don't, what would the method return?
If you can make the isVowel method take a single String argument, that would be simplest. Then you'd call it multiple times. If you want to make isVowel return a boolean[], the method would do something like
boolean[] result = new boolean[words.length];
to create an array of boolean that has the same number of elements as words.

Method that check first and last char if equals

I have this instruction:
Define and test a method called checkString that will take in the word as a parameter and checks whether the String begins and ends with the same letter. If both letters are the same the method returns true otherwise false (returns a boolean). The program treats lower and uppercase letters as equivalent.
Also I need to use the printf statement
Sample output would be:
Type a string: abba
abba begins and ends with the same letter
Here's what I have so far:
import java.util.Scanner;
public class Excercise5 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
System.out.printf ("%s begins and ends with the same letter." , checkString(word));
}
public static boolean checkString (String word) {
int length = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(length - 1);
return firstLetter == lastLetter;
}
}
It appears you've basically figured it out already, but here's a slightly updated version.
import java.util.Scanner;
public class Excercise5{
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Type a string: ");
String word = keyboard.nextLine();
if(checkString(word)) {
System.out.printf("%s begins and ends with the same letter.\r\n" , word);
} else {
System.out.printf("%s does not begin and end with the same letter.\r\n", word);
}
}
public static boolean checkString (String word) {
int length = word.length();
word = word.toUpperCase(); //since you are testing them as upper case
char firstLetter = word.charAt(0);
char lastLetter = word.charAt(length - 1);
return firstLetter == lastLetter;
}
}
The method will return true if the first letter and the last letter of the received String is the same. Otherwise it will return false. In the main: do the required definitions and ask the user to enter a String.

How to pass a char array to a method and return a boolean value

I am trying to write a program which checks whether a word is a palindrome or not. My code compiles butthe code in the isItPalindrome method doesn't seem to be run at all. I'm hoping someone can point out where i have gone wrong. Here is my code:
class Main
{
public static void main ( String args[] )
{
System.out.print ("#Enter word");
String word = BIO.getString();
String wordLowerCase = word.toLowerCase(); // converts word to lower case (only way i could think of to ignore case)
char letters[] = wordLowerCase.toCharArray(); // converts string into an array of character
while ( !word.equals ("END")){
if (isItPalindrome(letters) == true)
{
System.out.print (""+word+"");
System.out.println (" is a palindrome");
}
else if (isItPalindrome(letters) == false)
{
System.out.print (""+word+"");
System.out.println (" is not a palindrome");
}
System.out.print ("#Enter word");
word = BIO.getString();
}
}
public static boolean isItPalindrome ( char letters[]){
boolean palindrome = true;
if (letters.length%2 == 0){
for (int index=0; index<letters.length/2-1; index++) //index will finish at letters/2
{
if (letters[index] != letters[letters.length-index-1]) //checks if index is the same as its opposite letter
{
return false;
}
else //if any pairs of letters are not in ascending order then it returns fasle and breaks out of the loop
{
palindrome = true;
}
}
}
else{
for (int index = 0; index < (letters.length-1)/2-1; index++)
{
if (letters[index] != letters[letters.length-index-1]){
return false;
}
else{
palindrome = true;
}
}
}
return palindrome;
}
}
There were some issues in the main-method, for example the char-array was never updated and the palindrome-method was far to complicated, here is the working version:
public static void main(String args[]) {
System.out.print("#Enter word: ");
String word = BIO.getString();
while (!word.equals("END")) {
char[] letters = word.toLowerCase().toCharArray();
if (isItPalindrome(letters) == true) {
System.out.println(word + " is a palindrome");
} else {
System.out.print(word + " is not a palindrome");
} // OR
// Use this one-liner instead of the if:
// System.out.println(word + isItPalindrome(letters) ?
// " is a palindrome" : " is not a palindrome");
System.out.print("#Enter word: ");
word = BIO.getString();
}
}
public static boolean isItPalindrome(char letters[]) {
for (int i = 0; i < letters.length / 2; i++) {
if (letters[i] != letters[letters.length - i - 1]) {
return false;
}
}
return true;
}
Hope this helps.
Besides the initial word, your character array letters never reflects the current word in your while loop inside your main method. I don't know what you mean when you say your method "doesn't seem to be run at all" but I assume that you meant it's being run with the wrong output. This is one reason why. Be sure to call
wordLowerCase = word.toLowerCase();
letters = wordLowerCase.toCharArray();
every iteration of the while loop.
Side note: In your isItPalindrome method, you do not even need any of the else statements or the boolean palindrome at all. Simply return false if you ever find a case when the word is not a palindrome like you currently are. Then, if you have gotten to the end of the word, it must be a palindrome and you can return true.
First, to answer the question that's in the title:
public boolean palindrome(char C)
Has a return type of boolean but requires that you pass it a Character.
Second:
You're over-complicating things in the way that you reverse the words to check them. You could simply take the word, as a String, and take it apart, putting it into an array of Characters. Then put each char variable into a Stack. Then as you take them out of the stack, piece by piece, copy them to another array of Characters.

Uppercase, lowercase and other counter

So I've been making a small piece of code in Java that takes input from the user counts the uppercase, lowercase and other parts (such as spaces, numbers, even brackets) and then returns how much there are of each to the user.
The problem I have is that say I put in "Hello There" it stops counting spots after the "o" in Hello. So after the first word.
Code
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = 0;
int lower = 0;
int other = -1;
int total = 0;
String input;
System.out.println("Enter the phrase: ");
input = scan.next();
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) upper++;
if (Character.isLowerCase(input.charAt(i))) lower++;
else other++;
total = upper + lower + other;
}
System.out.println("The total number of letters is " + total);
System.out.println("The number of upper case letters is " + upper);
System.out.println("The number of lower case letters is " + lower);
System.out.println("The number of other letters is " + other);
}
}
Scanner#next:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
The problem is that next doesn't see the word "There" since "Hello World" is not a complete token.
Change next to nextLine.
Advice: Use the debugger and you'll find the problem quickly, and when you have doubts refer to the docs, they're there for you.
Problem is that next() only returns the line before a space but nextLine() will read the whole line.
So Change
scan.next();
to
scan.nextLine();
You need to change next() to nextLine()- it will read all the line
As others have said. You should change from scn.next to scn.nextLine(). But why? This is because scn.next() only read until it encounters a space, and it stops reading. So whatever input after a space will not be read.
scn.nextLine() reads until a newline (i.e. enter) is encountered.
You can try with regular expressions:
public static void main(String[] args) {
String input = "Hello There";
int lowerCase = countMatches(Pattern.compile("[a-z]+"), input);
int upperCase = countMatches(Pattern.compile("[A-Z]+"), input);
int other = input.length() - lowerCase - upperCase;
System.out.printf("lowerCase:%s, upperCase:%s, other:%s%n", lowerCase, upperCase, other);
}
private static int countMatches(Pattern pattern, String input) {
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}

Categories

Resources