Here is the question: Write a Java program that asks the user to provide a single character from the alphabet. Print Vowel or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an appropriate, descriptive error message.
I have made a switch statement that successfully tells if you have a vowel or a consonant but I can't figure out how to give an error message if the length of what the user types in is more than one character.
import java.util.Scanner;
public class VowelKL{
public static void main(String[] args){
int i=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter a single letter from the alphabet: ");
char letter=input.next().charAt(0);
switch(letter)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : i++;
}
if(i==1)
System.out.println("You entered the letter " + letter + " and it is a Vowel!");
else
if((letter>='a' && letter<='z')||(letter>='A' && letter<='Z'))
System.out.println("You entered the letter " + letter + " and it is a Consonant!");
else
System.out.println("You did not enter a single character from the alphabet, please try again.");
}
}
You could use something like this
public int length() {
return i.length;
}
There are a few ways of doing this and the above is only an example but the .length() property will get you an int value of the length of the string. In the above case we are then returning the int as a value.
In your case you could make a new int variable and then assign it with the length.
int x = letter.length()
This will get the length of the string to an int value. You can then take that and write an if statement for when it is above or below the value of 1.
EDIT:
I quickly wrote this in java and it seems to work as intended. Hope that helps point you in the correct direction. Note that you would need to change your variable letter from a char to a String
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
System.out.println("Enter a single letter from the alphabet: ");
String letter= input.nextLine();
if (letter.length() == 1)
System.out.println("Only one letter was entered");
else
System.out.println("Either no letter or more than one letter was entered");
}
As you are already specifying in the user input command that user input is allowed only at index 0 i.e. charAt(0). So there is no other way to extract the index position of that character value. Unless you have to cast that particular character in the string type and then you can access String's
str.lastIndexOf(char) method to provide the restriction .
which is not the best practice to do.
Related
I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.
I created a method called showCharacter. The method takes a string and shows what character is at a given location in that string. Here is the code for that method:
public static void showCharacter(String userStr1, byte charLoc)
{
System.out.println(userStr1.charAt(charLoc));
}
In main, I want to ask the user to enter a string and then ask the user to enter a number that designates a position in that string (first letter, second letter, fifth letter, etc).
The part I'm having trouble with is, after all that I want to print to the screen "The letter at position USER_ENTRY is: CHARACTER_FROM_THE_METHOD_I_CREATED_EARLIER."
Here is the code currently in my main method:
public static void main(String[] args) {
// TODO code application logic here
Scanner k = new Scanner(System.in);
System.out.println("Please enter a String");
String str = k.nextLine();
int strLen = str.length();
System.out.println("Please enter the character's position");
byte i = k.nextByte();
while (i <0 || i > (strLen -1))
{
System.out.println("Invalid Position. Enter a valid position");
i = k.nextByte();
}
showCharacter(str, i);
}
I tried writing:
System.out.println("The letter at position " + i + " is " + showCharacter(str, i));
Any ideas?
Thanks!
Keep your showCharacter method almost as originally written.
public static void showCharacter(String userStr1, byte charLoc)
{
System.out.print(userStr1.charAt(charLoc));
}
The difference is I used print rather than println because I don't want to wire in the assumption that the character must be the last thing on the line. Just output the character.
In main after you have a valid position, do your output:
System.out.print("The letter at position " + i + " is ");
showCharacter(str, i);
System.out.println();
That is, there are 3 parts:
Stuff before the character
The character
Stuff after the character (here nothing except end of line)
What can I do to modify this, is there any java function for that?
What needs to be done so that it only accepts characters and returns an error message for other data types?
import java.util.*;
public class problem5
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a letter from the alphabet: ");
char letter = in.next(".").charAt(0);
char vowels[] = {'A','E','I','O','U','a','e','i','o','u'};
int vowelcount = 0;
for (int i = 0; i < 10; i++)
{
if (vowels[i] == letter)
{
vowelcount++;
}
}
if (vowelcount > 0)
{
System.out.println("You entered a vowel.");
}
else
{
System.out.println("You entered a consonant.");
}
}
}
I need to reject input that has more than 1 char – Nico Dela Cruz
You just need to check the length of your input
String input = in.next(".");
if(input.length == 1){
char letter = input.charAt(0);
...
}
Add an else if you want to add an error message of some sort.
To check the input to only accept letter, you have Character.isLetter(char) to check every "letter" in UNICODE for you.
If you want to only accept a range of a-z and/or A-Z, you can do it yourself with an if condition or using regex.
Wrap your loop in a statement such as:
if (Character.isLetter(letter)){
and put and else clause at the end for your error
Edit:
OP has changed their question slightly, so you can either:
-Accept only the first character entered:
char letter = in.next().trim().charAt(0);
-Or as AxelH said above, only proceed if user enters one char:
if(input.length == 1){
char letter = input.charAt(0);
trying to write a simple Java program that accepts a string and validates against two criteria.
If the word is shorter than 4 letter it asks the user to re enter a word till it is four letters..
Once that criteria is true it evaluates it against the letters. If the first letter of the four letter word is a D then it prints a silly message "The D was found" if not "No D found"
So far what i have working is validation for the four letters. It checks that it is four letters and if its not it keeps asking till it gets a four letter word.
After that when i enter the four letter word i cant get it to validate on the next if which checks if it is greater than 4 letters and then checks if it starts with a D or not.
import java.util.Scanner;
public class POD1
{
private static Scanner scan = new Scanner(System.in);
private static String word;
public static void main(String [] args)
{
System.out.println("Please enter a 4 Letter word");
word = scan.next();
if(word.length() <4)
{
System.out.println("Word is to short ");
System.out.println("Plese re-enter");
word = scan.next();
}
if(word.length() > 4)
{
if(word.charAt(1) == 'd')
{
System.out.println("Big d");
} else
if( word.charAt(1) !='d')
{
System.out.println("No big d");
}
}
}
}
UPDATE
The code now does go past 4 letter words but even if the word starts with a d it prints out no big d even though it starts with a d
You should be having the following to include 4 lettered words as well
if(word.length() >= 4)
You are scanning and taking the input until word.length() <4. So the loop breaks when the length is 4.
So, it doesn't enter the next if statement.
A better implementation would be to use the else clause
if(word.length() <4) {
System.out.println("Word is to short ");
System.out.println("Plese re-enter");
word = scan.next();
} else {
if(word.charAt(0) == 'D')
{
System.out.println("Big D");
} else
if( word.charAt(0) !='D')
{
System.out.println("No big D");
}
}
}
Also, you should be checking for 'D' and not 'd', if you are looking for "Big D".
Also, the index of the first character in a String is 0. So, you should be using word.charAt(0) == 'D', and not index 1 as you are using in your code right now. Index 1 will return the second character.
You check wether the word is shorter than 4 letters AND wether the word is longer than 4 letters.
There is absolutely nothing in your code that includes 4 letter words.
if(word.length() >= 4)
should be used.
Recently, I've been trying to build a program that does 4 things:
1) Enter a word from the keyboard.
2) Check the context of this word with the context of a string that contains the letters of the alphabet.
3) Compare the letters of the given word with the letters of the alphabet string and whenever there is match, it will return the position of that letter in the alphabet string +1. (ex. word='a' position=1 since 'a' is the first letter)
4) Get the total of all of these positions.(ex. word='abc' total=6)
Now let me show you what I've written in terms of code.
//Part 1 Entering word from keyboard
package IntroductionJava;
import java.util.Scanner;
public class Numerology
{
public static void main(String[] args)
{
int m=0,n=0,sum=0;
int j,k;
Scanner user_input=new Scanner(System.in);
String word;
System.out.print("Give a word: ");
word=user_input.next();
String word1 = "\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03bf\u03c0\u03c1\u03c3\u03c2\u03c4\u03c5\u03c6\u03c7\u03c8\u03c9";
//Part 2 check word
for(int i=0; i<word.length(); i++)
{
if(word.charAt(i)>=word1.charAt(0) && word.charAt(i)<=word1.charAt(word1.length()-1))
{
System.out.println("Your word '"+word+"' is valid.");
break;
}
else
{
System.out.println("Your word '"+word+"' is invalid.");
}
break;
//show System.out.print(word.charAt(i));
}
//Part 3 Compare letters
for(j=0; j<word.length(); j++)
{
for(k=0; k<word1.length(); k++)
{
if(word.charAt(j)==word1.charAt(k))//???
{
m=k+1;
}
}
}
}
Now, Part 1 and 2 are working fine.
My problem lies when I try to compare the letters of the word that I'm entering with the String of letters in unicode format(the letters in unicode format are from the Greek alphabet). I've tried many variations, I've also consulted some of the articles here but I couldn't find a solution.
To make things a bit more clear let's say that I'm entering the word: "hello". I want to check whether 'h' is inside the alphabet string, and if it is I want to get it's position as an integer which in our case it's the number '8' (position in the string +1) and so on.
And the last part of my program is to get all those numbers from the given word and get it's total ('hello'=8+5+12+12+20=57).
Thank you very much in advance.
How about this:
String alphabet = "abcdefgh";
String input = "abc";
int value = input.chars()
.map(alphabet::indexOf)
.map(i -> i + 1)
.sum()
System.out.println(value);