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.
Related
Being fairly new to Java, I have an exercise where the user will be asked to enter a word. Next, they will be asked to enter a number. Then the program will modify the word by taking the number and implementing it to change the string. For example, if the word "Hello" was entered, and the integer entered was the number "3", it will take each character in the string (Hello) and move them each 3 letters down in the alphabet, which would then make the output word "Khoor". I recently learned about method replacing (.replace) in the same chapter as this question but it seems like having to clarify every single letter with a replace would be too lengthy. This is what I have so far.
public class Lab03Exercise7 {
public static void main(String [] args)
{
// Prompt user to enter a string
System.out.print("Enter a word");
// Import Java scanner
Scanner input = new Scanner( System.in );
int numberinput;
String wordinput = input.nextLine();
// Prompt user to enter an integer
System.out.print( "Enter a number");
numberinput = input.nextInt();
}
}
You can do it as follows:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a word: ");
String wordInput = input.nextLine();
System.out.print("Enter a number: ");
int numberInput = input.nextInt();
StringBuilder updatedStr = new StringBuilder();
for (char c : wordInput.toCharArray()) {
updatedStr.append((char) (c + numberInput));
}
System.out.println("Updated string: " + updatedStr);
}
}
Explanation: Break the word into an array of characters and iterate through the array. During iteration, add the number to the character and append the updated character to a StringBuilder object. Note that you can add an integer to a char value but you need to cast it before appending to the StringBuilder object.
You can use something like this:
final StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < wordinput.length(); i++) {
final char currentChar = wordinput.charAt(i);
sb.append((char)(currentChar + numberinput));
}
System.out.println(sb.toString());
So basically, we're going character by character and adding the shift that you've got from the user. here I don't handle the edge cases - where we need to rotate after z / Z
In general, this algorithm called Caesar Cipher and you can get some more info about it here: https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/
As highlighted by #maio290' comment you have to use the ascii table to solve your problem, differentiating between lowercase characters and uppercase characters. Starting from the assumption we have a 26 chars alphabet (a-z and A-Z) in the example we are translating the chars of three positions so we will have for example:
"Hello" will be translated to "Khoor"
"zed" will be translated to "chg"
In the case of z char it will be translated to c, I'm posting an example explaining the situation:
public class Caesar {
public static String encode(String original, int k) {
char[] arr = original.toCharArray();
StringBuilder encoded = new StringBuilder();
for (char ch : arr) {
char initialCharacter = Character.isLowerCase(ch) ? 'a' : 'A';
int dec = ((int)(ch - initialCharacter) + k) % 26;
encoded.append((char)(dec + initialCharacter));
}
return encoded.toString();
}
public static void main(String[] args) {
System.out.println(encode("Hello", 3)); //<-- will print Khoor
System.out.println(encode("zed", 3)); //<-- will print chg
}
}
You have to transform your char to int and after retransform it to char , differentiating between lowercase chars and uppercase chars and assuming an alphabet of 26 chars , for further details see the ascii table.
I believe this is gonna help to solve your problem. Just do not forget to handle it after 122(letter z). You can check the ASCII table here (https://theasciicode.com.ar/)
public static void main(String[] args) throws Exception {
String word = "word";
char[] arr = word.toCharArray();
int count=0;
for (char c : arr) {
//!!Handle if the sum is bigger than 122 (letter z), you need to do some easy math.
arr[count] = (char) (((int)c) + 3);
count++;
}
String newWord = new String(arr);
}
I am supposed to write code that replaces a letter in an input. For example, if the word is "hello" and the letter to replace is "l" and put "y" it would make "heyyo". I just don't know what to do after the user inputs.
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static int replaceLetter(String word, String letterToReplace, String replacement)
{
int count = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
count++;
}
}
return count;
}
}
Try doing the next, replacing the char at the position if it is the same as the letter to replace.
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == letterToReplace)
{
word = word.substring(0, i)
+ replacement
+ word.substring(i + 1);
count++;
}
}
Or you could just do the next:
word = word.replace(letterToReplace, replacement);
YCF_L is correct, the best way would be with replace. If you need to do things programatically for some reason, this will work:
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
System.out.println(replaceLetter(word, letter, replace));
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static String replaceLetter(String word, String letterToReplace, String replacement)
{
//Short way:
String wayOne = word.replace(letterToReplace, replacement);
//Long way:
String wayTwo = "";
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == letterToReplace.charAt(0)){
wayTwo += replacement;
} else {
wayTwo += Character.toString(word.charAt(i));
}
}
return wayOne + " VS " + wayTwo;
}
Output should be printing only once, but can't figure it out to get it out of loop once i find the VOWEL.
Go on by giving input 'a' once then 'aft'. You will know what i actually want...
package com.java;
import java.util.Scanner;
public class three {
#SuppressWarnings("resource")
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter String");
String a = s.next();
char b[] = a.toCharArray();
///char c[] = {"a","e","i","o","u"};
String str = "aeiouAEIOU";
char[] c = str.toCharArray();
//char[] charArray = str.toCharArray();
if(a.matches(".*\\d+.*"))
{
System.out.println("WARNING!!!");
System.out.println("please input only string");
}
else
{
for(int i=0;i<b.length;i++)
{
for(int j=0;j<c.length;j++)
{
if(b[i]==c[j])
{
System.out.print(" VOWEL ");
}
else if(b[i]!=c[i])
{
System.out.print(" consonant ");
}
}
}
}
}
}
The issue
The problem is in your second for loop, you should not be printing vowel or consonant from within it. This inner loop is just there to decide if the character is a vowel or not, so you should update a boolean inside this loop and print out in the outer loop depending on the value of the boolean.
code corrected
Here is your code corrected (I changed variables names so it is easier to understand):
public static void main(String args[]) {
String vowels = "aeiouAEIOU";
char[] vowelsArray = vowels.toCharArray();
Scanner s = new Scanner(System.in);
System.out.println("Enter String");
String inputString = s.next();
char inputStringArray[] = inputString.toCharArray();
if(inputString.matches(".*\\d+.*")) {
System.out.println("WARNING!!!");
System.out.println("please input only string");
} else {
for(int i=0;i<inputStringArray.length;i++) {
// Declare a boolean to say if the character is a Vowel or not
boolean isVowel = false;
// Check the character and set the boolean value
for(int j=0;j<vowelsArray.length;j++) {
if(inputStringArray[i]==vowelsArray[j]) {
isVowel = true;
break;
}
}
// Then do the printing here, in the input characters loop
if(isVowel) {
System.out.print(" VOWEL ");
} else if(inputStringArray[i]!=vowelsArray[i]) {
System.out.print(" consonant ");
}
}
}
Note regarding the regular expression
You might prefer this regex if you only want accept letters.
if(!inputString.matches("[a-zA-Z]+"))
Your current regex, would accept hey!
An other way to code it
Here is an other way to do it:
Using the contains method of the List object.
Modified the regular expression test to only accept letters
Lower casing the input string so our vowels array can be lower case only
See inline comments for explanations:
public static void main(String args[]) {
// declare your vowels
List<Character> vowelsList = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');
// get the input string
Scanner s = new Scanner(System.in);
System.out.println("Enter String");
String inputString = s.next();
if(!inputString.matches("[a-zA-Z]+")) {
System.out.println("WARNING!!!");
System.out.println("please input only string");
} else {
// Transform your inputString to lower case
// (because we only have lower case in our vowels list)
String lowerCaseInputString = inputString.toLowerCase();
// Then for each character of the input string,
// check if it is in the vowels list or not
for(char c : lowerCaseInputString.toCharArray()) {
if(vowelsList.contains(c)) {
System.out.print(" VOWEL ");
} else {
System.out.print(" consonant ");
}
}
}
}
And finally, a lambda version
If you are using Java 8 and are willing to use a lambda, you can replace the whole else block with a lambda
...
} else {
inputString.toLowerCase().chars()
.mapToObj(c -> vowelsList.contains((char) c) ? " VOWEL " : " consonant ")
.forEach(System.out::print);
}
...
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());
I need help on writing a program about counting how many times a letter in a given word is repeated in alphabetical order. Lower and upper case letters are equals and it has to work for numbers as well. For example:
we have to use array and loops. also, it must not count the space if there is more than 1 word /number given and it should also prompt the user if they want to continue or not. If not then they should enter a dot '.' or when there's a dot '.' after the word, it should close the program after counting the letters.
University
e:1 i:2 n:1 r:1 s:1 t:1 u:1 y:1
import java.util.Scanner;
import java.lang.Character;
public class Array {
public static void main(String[] args) {
Scanner input=new Scanner (System.in);
int[] letters =new int [26];
String str= input.nextLine();
str=str.toLowerCase();
for (int i=0; i<str.length(); i++)
{
letters[i]=0;
}
System.out.println(str.length());
System.out.println(char2int('a'));
System.out.println(char2int ('D'));
}
public static int char2int (char c) {
return Character.toLowerCase(c)-(int)'a';
}
}
This comes out to, for example
me
2
0
3
I'm going to give you a big hint, what you need to do is call a method (say countLetters) that takes a word and a letter - so that would be,
// Count the "letter"(s) in the word.
public static int countLetters(String word, char letter) {
int count = 0;
if (word != null) {
char lc = Character.toLowerCase(letter);
for (char c : word.toCharArray()) {
if (lc == Character.toLowerCase(c)) {
count++;
}
}
}
System.out.printf("%s: %d\n",
String.valueOf(letter), count);
return count;
}
public static void main(String[] args) {
String test = "Universe";
countLetters(test, 'e');
countLetters(test, 'u');
}
Output is
e: 2
u: 1