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.
Related
I'm trying to make a program where it asks for a letter from the alphabet. Lets say I choose the letter "b". The "b" should be shown in quotation marks in the program. I'm trying to learn Java, I know HTML and CSS, but Java is new to me, so go easy.
So in practice:
Choose a letter:
d
abc"d"efghijklmnopqrstuvwxyz
I've figured out how to print the alphabet
import java.util.Scanner;
public class Characters {
public static void main(String[] args) {
char c;
for(c = 'a'; c <= 'z'; ++c)
System.out.print(c + " ");
}
}
(I have added scanner, because I'll ask the user for the letter)
A very concise example:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
char c = s.next().charAt(0);
for(char i = 'a'; i < 'z'; i++){
System.out.print(i == c ? "\""+c+"\"" : i);
}
}
}
Use java.util.Scanner's .next() to read the next word, then get the first character of the word.
Sample Run:
a
"a"bcdefghijklmnopqrstuvwxy
Since Java recognises quotation marks for text, you need to add a \ before each caracter to indicate to java that you wish for it to be part of the text. For example, if you want to show "b" with quotation mark, your final string is going to be a\"b\"cdefghijklmnopqrstuvwxyz
First, we would have to read the input char:
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); // Get char
Then, I would make sure that our char is in the alphabet:
if(!('a' <= c && c <='z')) {
return; // NOT IN ALPHABET
}
If we got this far, we successfully read a character, which is in the alphabet.
Now, we can print out the modified alphabet.
for(char letter = 'a'; letter <= 'z'; letter++) {
if(letter == c) {
System.out.print("\"" + c + "\"");
}else {
System.out.print(letter);
}
}
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
In my program, I get a user input (String):
ex:
String input = in.nextline();
I want to check (with an if-function) if the user/string has the following:
contains a letter (a-z / A-Z)
only contains one letter (A is valid, AA/AB/LWA is invalid)
so what goes on x/x2?
if(input.equals(x) && input.equals(x2){
//...
}
You can use a simple regex for that:
String input = in.nextline():
if (input.matches("[A-Za-z]{1}")) {
//valid input
}
else {
//invalid input
}
A solution that doesn't involve regular expressions (and, as such, can be easier understood) is simply:
check that the length of the String is 1, using String.length().
check that the first character is between 'a' and 'z' or between 'A' and 'Z', using String.charAt(index) and doing integer comparison on the ASCII value of the characters. This can be also simplified by lowercasing the character and checking that it is between 'a' and 'z' only.
A sample code would be:
private static boolean isValid(String str) {
if (str.length() != 1) return false;
char c = Character.toLowerCase(str.charAt(0));
return c >= 'a' && c <= 'z';
}
And you would use it like
String input = in.nextline();
if (isValid(input)) {
// do something wonderful
}
Using a regex should do the work:
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.matches("[A-z]")) {
System.out.println("Valid input");
}
else {
System.out.println("Wrong input");
}
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();
}