I'm doing a function in which I need to get user input and replace all of the vowels in the array with what the user put. This is my array: I honestly dont know what im doing .
char [] letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}
I'm thinking of doing a nested if inside the for loop but like I said I don't know if I'm headed in the right direction .
/********************************************************************************
This function will prompt the user to replace all vowels in the array
********************************************************************************/
public static void replace( char [] letters ){
for(int i =0; i < letters.length; i++){
if(i >= 'A')
if(i <='Z')
System.out.println(letters[i]);
else
break;
}
}
Your loop doesn't look like it will do much other than print out all the upper case letters. You need some code to display a prompt and obtain user input. You also need a way to test whether a character is a vowel. One way of doing the latter is:
if ("AEIOU".indexOf(letter) >= 0) {
// letter is a vowel
}
If you also need to handle lower case letters, you can use either "AEIOUaeiou".indexOf(letter) or "AEIOU".indexOf(Character.toUpperCase(letter)). This hides the nested loop inside a standard API function call, which makes your code more readable and easier to debug. (You can safely assume that indexOf is written correctly.)
For user interaction, you should look at wrapping System.in with a Scanner. Alternatively (and perhaps better), use a Console for managing all user I/O. Take a look at this tutoral, see if you can figure it out on your own and if you get stuck, post another question.
If I'm interpreting your question correctly, you want to replace a, e, and i with another character that the user has typed in.
You're comparing your index 'i' to characters, you will probably want to change that to
if(letters[i] >= 'A')
if(letters[i] <= 'Z')
System.out.println(letters[i]);
else
break;
Another thing, if you want to test to see if it is a vowel, you could OR all the comparisons together like this:
if(letters[i] == 'A' ||
letters[i] == 'E' ||
letters[i] == 'I' ||
letters[i] == 'O' ||
letters[i] == 'U')
letters[i] = users_input
Maybe something like this?
public static void replace( char [] letters )
{
Scanner s = new Scanner(System.in);
for(int i = 0; i < letters.length; i++)
{
if ("AEIOU".indexOf(letters[i]) >= 0)
{
System.out.println("\nVowel Found, What should it be replaced with?");
String line = s.read();
letter[i] = line.charAt(0);
}
}
}
Assume user input is b, you can achieve this:
public static char [] replace(char [] src) {
String s = new String(src);
s = s.replaceAll("[aeiouAEIOU]", "b");
return s.toCharArray();
}
Related
I am trying to create a program that loops through a string, and if it is a vowel that adds it to a variable and then displays. The idea is not to use regular expressions so I use a for. And the problem is that it does not show me the result well, can you help me?
import java.util.Scanner;
import java.lang.StringBuilder;
public class ReemplazarVocales {
public static void main(String[] args) {
Scanner InputText = new Scanner(System.in);
StringBuilder str = new StringBuilder();
System.out.println("Escribe una frase\n");
String Sentence = InputText.next();
Sentence = Sentence.toLowerCase();
char Vocal;
for (int i=0;i <= Sentence.length();i++){
Vocal = Sentence.charAt(i);
String Consonant = Character.toString(Vocal);
if (Consonant != "a" ||Consonant !="e" || Consonant !="i" || Consonant !="o" || Consonant!="u"){
str.append(Consonant);
}
}
System.out.println("\nTu frase sin vocales " + str);
}
}
There seem to be three problem in you code:
you are looping from index int i=0 till i=length, which will give you IndexOutOfBound.
Since string indexing start from 0 you can loop like
for (int i=0;i < Sentence.length();i++){
Vocal = Sentence.charAt(i);
String VocalP = Character.toString(Vocal);
if (!VocalP.equals("a") && !VocalP.equals("e") && !VocalP.equals("i") && !VocalP.equals("o") && !VocalP.equals("u")){
str.append(VocalP);
}
}
you need to have (&&) instead of Logical (||) because you wish to eliminate all the vowels.
It is adviceable to do string comparision using equals or equalsIgnoreCase to compare two strings
I am trying to create a program that loops through a string, and if it
is a vowel that adds it to a variable and then displays.
You are trying to get a character at the index = Sentence.length() which is not possible because java stores the characters in a string starting with index, 0 and therefore the last index is equal to the length-of-the-string minus one. Trying to access an index beyond the limits results in StringIndexOutOfBoundsException.
You do not need to convert a char into a String in order to add it to a StringBuilder; you can append a char value directly to the StringBuilder object.
You need to use == instead of !=.
You need to use Scanner#nextLine instead of Scanner#next which stops scanning the input as soon as it encounters whitespace.
A. Replace
String Sentence = InputText.next();
with
String Sentence = InputText.nextLine();
B. Replace
for (int i=0;i <= Sentence.length();i++)
with
for (int i = 0; i < Sentence.length(); i++)
C. Replace
Vocal = Sentence.charAt(i);
String Consonant = Character.toString(Vocal);
if (Consonant != "a" ||Consonant !="e" || Consonant !="i" || Consonant !="o" || Consonant!="u"){
str.append(Consonant);
}
with
Vocal = Sentence.charAt(i);
// String Consonant = Character.toString(Vocal);// It's not needed
if (Vocal == 'a' || Vocal == 'e' || Vocal == 'i' || Vocal == 'o' || Vocal == 'u') {
str.append(Vocal);
}
I also recommend you follow the Java naming conventions e.g. Vocal should be vocal and Sentence should be sentence as per the naming conventions.
You wrote:
if (VocalP!="a" || VocalP!="e" || VocalP!="i" || VocalP!="o" || VocalP!="u")
which if you look closely will always be true.
for example if you take the first two options only:
if (VocalP!="a" || VocalP!="e")
if the letter is not 'a' OR the letter is not 'b'
and the letter is 'a' it will still evaluate to true because it is not 'e'
from your question you should be using == instead of !=
so try:
if (VocalP=="a" || VocalP=="e" || VocalP=="i" || VocalP=="o" || VocalP=="u")
I am trying to have my code output the exact number of times a certain character is said in an inputted sentence (For example e).
I tried using a char and for statement so its able to count but it gives me the wrong value
int countChar;
char e = '\0';
String str;
int count = 0;
System.out.println("input your sentence:");
str = in.next();
for(i=0; i < str.length(); i++)
{ if(str.charAt(i) == e)
count++;
}
System.out.println(count);
You need to change if(str.charAt(i) == e) to if(str.charAt(i).equals("e")), you don't really require a variable for this. You just require the quotation marks, and since you are comparing a string, you should use the above String.equals() method.
If you are looking for uppercase letters as well, use the || (OR) operator and do the same but replace the lowercase e with an uppercase
You should use 'e' instead of '\0' when comparing the characters
When the first character of word starts with 'A' or 'a', let the program output the word 'America'. if the first character of the word starts with other characters, let the program prints "error"
public class Home1 {
public static void main(String[] args) {
String str=args[0];
char ch;
ch= (1) . (2) ;
if( (3) ) System.out.println("America");
(4) System.out.println("Error");
}
}
I have figured out that 4th one is 'else'
3rd one may be something like, 'first character = 'a','A'
but i do not fully get them.
could you help me?
(1) and (2): get somehow the char at position 0 of the string read. Documentation of the available methods on Strings is available here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
(3) Compare the character read with 'A' and 'a':
If char equals 'A' or char equals 'a'....
Documentation can be found here: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html
Ok this looks like a code fill in the blanks,
Your actual code should be something like this,
public static void main(String[] args) {
String str = args[0];
char ch;
ch = str.charAt(0);
if (ch == 'a' || ch == 'A')
System.out.println("America");
else
System.out.println("Error");
}
So,
(1) = str
(2) = charAt(0)
(3) = ch == 'a' || ch == 'A'
(4) = else
Hope this helps.
I'm a beginner at Java and I've been working on this puzzle for a while and just can't seem to get it right.
I want a user to enter a word, any word, and for a program to go through the characters in the String one by one, and if the first character is a vowel, the next 2 characters are to be erased in the String.
After the characters have been erased, the program will go to the next character and perform the same test. If a vowel, erase the next two, if not, just print the character and move on to the next one.
For example, a random word like 'liberty' would be:
'lirty'
'banana' would be changed into 'ban'.
'caramel' becomes 'came'.
Is there a basic and simple way to acheive this?
Thanks in advance for any help!
Kind Regards
///Magnus
Basic idea on how to solve this:
There are 2 cases. First letter a vowel or not a vowel.
This means we need the following structure
if(isVowel(firstLetter)){
//handle case with first letter a vowel
}else{
//handle other case
}
Since we want to print the first letter independent of the cases we can do that before the if, so that's done.
Then in both cases you can just call the function recursively.
So for the vowel case take the substring from 3 till the end.
str.subString(3, str.length()-1);
And finally don't forget about the edge cases: what would happen if you pass in an empty string?
Or if the first is a vowel but there's only 1 letter after?
This results in the following implementation:
public void printSpecial(String str){
if(str==null || str.isEmpty()){
return; //No letters to print
}
char firstLetter = str.charAt(0);
System.out.print(firstLetter); //print the current letter
if(isVowel(firstLetter)){
if(str.length()<4){
return; //Not enough letters to continue
}
printSpecial(str.substring(3, str.length()-1));
} else {
if(str.length()==1){
return; //Last letter done
}
printSpecial(str.substring(1, str.length()-1));
}
}
So the only thing left to do is implement the method
public boolean isVowel(char letter){
}
But I'll leave this up to you :)
public static void main(String[] args) {
String str = "caramel";
StringBuilder sb = new StringBuilder();
sb.append(str);
System.out.println("Before deletion=" + sb);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == 'a' || sb.charAt(i) == 'e' || sb.charAt(i) == 'i' || sb.charAt(i) == 'o' || sb.charAt(i) == 'u') {
if(i==sb.length()-2)
{//prevent index out of bounds
sb.deleteCharAt(i+1);
}
else if(i==sb.length()-1)
{
//prevent index out of bounds
}
else
{ //delete 2 charaters
sb.deleteCharAt(i+1);
sb.deleteCharAt(i+1);
}
}
}
System.out.println("After deletion=" + sb);
}
import java.util.Scanner;
import java.util.Stack;
public class Stack_1 {
public static void main(String[] args) {
String val;
Scanner input = new Scanner(System.in);
System.out.println("Enter Text: ");
val = input.nextLine();
push(val);
}
public static void push(String str) {
Stack<Character> stk = new Stack<Character>();
for (int i = 0; i < str.length(); i++) {
stk.push(str.charAt(i));
}
System.out.println(stk);
String reverseString = "";
String original = "";
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverseString = reverseString + original.toUpperCase().charAt(i);
if (original.toUpperCase().equals(stk))
System.out.println("The string is a palindrome.");
else if (reverseString.toUpperCase().equals(stk))
System.out.println("The string is not a palindrome.");
}
}
Can anyone help me out. I didn't know where I went wrong. The question was to create a stack (Character), and display the text where it is a palindrome or not. The user had to enter input.
P.S This was one of my lab test.
If I followed the code correctly, the problem appears to be that the OP is comparing a String object (either original or reverseString) to Stack<Character> object.
So, the probable failure is the incorrect attempted comparison of a String object to a Stack object.
I think there is a 2nd failure in the if/else if logic given that an example input of "cool" is not a palindrome, but no output is produced in such a case.
EDIT: while the OP code does attempt to adjust for the case of the entered data (not given in the question as to whether that is a requirement or not), it does not account for spaces or other punctuation. According to the entry on Wikipedia about Palindromes, punctuation is also usually ignored. Again, whether being concerned about spaces, periods, dashes, etc. was part of the exercise is not defined in the question. The question is a bit under specified in terms of full requirements.
I would think a solution using a stack would take a String, push it by character to a Stack (probably correcting for case and stripping out all punctuation at that time), and then do a comparison by popping from the Stack. I think the OP code is missing part of the requirement in using a Stack.
Example code to have only characters on the Stack. There are other approaches, of course:
// push by character onto the stack; use only
// characters, and convert to lower case
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ) {
stk.push(Character.toLowerCase(c));
}
}
Example to remove all non characters from a check String:
// convert out comparison String to lower case and remove
// all non letters
String chk = str.toLowerCase().replaceAll("[^a-z]", "");
Example loop to use the Stack to check against the String:
// assume we have a palindrome
boolean palindrome = true;
// counter across the String
int i = 0;
// loop while there is more on the stack and we haven't
// failed our test
while (! stk.isEmpty() && palindrome) {
Character c = stk.pop();
palindrome = (c == chk.charAt(i++));
}
Sample Test Data:
cool is a palindrome: false
mom is a palindrome: true
Never odd or even is a palindrome: true
A man, a plan, a canal - Panama! is a palindrome: true