Java Doesnt realize if and else - java

it doesn't realize that there is an if statement when i type a consonant.
and also when i type e, it realizes that its a consonant.
Also when i enter "a" it produces the if statment for string vowel and the else statement.
same with captial letter "A" but this time it produces the else twice.
import javax.swing.JOptionPane;
public class R
{
public static void main(String args[])
{
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
for (int x=0;x<vowels.length;x++)
{
if(InputVowel.equals (vowels[x]))
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
if(InputVowel.equals(vowel[x]))
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
else
x = 5;
JOptionPane.showMessageDialog(null,InputVowel+" is a consaunant");
}
}
}

The reason it can't recognize your if-statements is braces are required if you have more than one if-statement check. If you have an if-else, braces are required.
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
for (int x=0;x<vowels.length;x++) {
if(InputVowel.equals (vowels[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
} else if(InputVowel.equals(vowel[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
} else {
x = 5;
JOptionPane.showMessageDialog(null,InputVowel+" is an consaunant");
}
}
The above code should work.

You can only assume it is not a vowel after checking all candidates (all vowels)
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
boolean isVowel = false;
for (int x=0;x<vowels.length;x++)
{
if(InputVowel.equals (vowels[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
isVowel = true;
break;
}
if(InputVowel.equals(vowel[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
isVowel = true;
break;
}
}
if (!isVowel)
JOptionPane.showMessageDialog(null,InputVowel+" is an consaunant");

Although the OP has already accepted an answer. This is an enhanced version of the program utilizing various features of the program.
import javax.swing.JOptionPane;
public class R
{
public static void main(String args[]){
String[] vowels = {"a","e","i","o","u"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ").trim();
String x = Integer.toHexString(InputVowel.charAt(0));
for(int i=0;i<vowels.length;i++)
{
if(vowels[i].equalsIgnoreCase(InputVowel))
{
if(!(InputVowel.equals(vowels[i].toUpperCase())))
JOptionPane.showMessageDialog(null,InputVowel+" is a vowel and lowercase character");
else
JOptionPane.showMessageDialog(null,InputVowel+" is a vowel and uppercase character");
break;
}
else if(InputVowel.length()>1||(Integer.valueOf(x)>=0 && Integer.valueOf(x)<=40))
{JOptionPane.showMessageDialog(null,InputVowel+" is not a valid character");break;}
else
{
if(!InputVowel.equals(vowels[i].toUpperCase()))
JOptionPane.showMessageDialog(null,InputVowel+" is a consonant and lowercase character");
else
JOptionPane.showMessageDialog(null,InputVowel+" is a consonant and uppercase character");
break;
}
}
}
}
Note
The input other than letters are handled (numbers and special characters) and for simplicity are labelled as non valid characters.

Related

password validation using boolean

I have to write a code that check if a password is valid.
The problem is when the password pass every condition I don't get any answer if it's.
Right here you can see my code; I think I need to add something in my main function but I don't know what.
Is the else if statement not necessary?
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a password : ");
String passwordhere = in.nextLine();
List<String> errorList = new ArrayList<String>();
while (!isValid(passwordhere, errorList)) {
System.out.println("The password entered here is invalid");
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
passwordhere = in.nextLine();
}
}
public static boolean isValid(String passwordhere, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!specailCharPatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one specail character !");
flag=false;
}
if (!UpperCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one uppercase character !");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one lowercase character !");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one digit character !");
flag=false;
}
else if(digitCasePatten.matcher(passwordhere).find()&&passwordhere.length() < 8&&
specailCharPatten.matcher(passwordhere).find()&&lowerCasePatten.matcher(passwordhere).find()&&
UpperCasePatten.matcher(passwordhere).find()){
System.out.println("the pass is right");
flag=true;
}
return flag;
}
}
while (true) {
if (!isValid(passwordhere, errorList)) {
System.out.println("The password entered here is invalid");
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
passwordhere = in.nextLine();
}
else {
System.out.println("Password is valid!");
break;
}
}
or change just your method isValid like this :
public static boolean isValid(String passwordhere, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!specailCharPatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one specail character !");
flag=false;
}
if (!UpperCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one uppercase character !");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one lowercase character !");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one digit character !");
flag=false;
}
if(flag) System.out.println("the pass is right");
return flag;
}
else if( ... &&passwordhere.length() < 8 ...) <-- sth wrong here.
But I think u don't need else if. After checking all, it's true or false.
So just
if (flag){
System.out.println("the pass is right");
}

How to get correct output for Pig Latin translator using JAVA

I am coding a JAVA application that translates english to pig latin. My application runs with no actual errors but the output is automatic and incorrect. This application will continue to run if the user selects "y".
Can you all see where my error lies?
Thank you.
CODE:
import java.util.Scanner;
public class PigLatin2 {
public static void main(String[] args) {
// create a Scanner object
Scanner sc = new Scanner(System.in);
// Run through the loop of calculations while user choice is equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("Enter a line to be translated");
System.out.println();
//Get String entered
String userInput = sc.toString();
//Line break
System.out.println();
String[] words = userInput.split(" ");
String output = "";
for(int i = 0; i < words.length; i++) {
String pigLatin = translated(words[i]);
output += pigLatin + " ";
}
System.out.println(output);
//Scan next line
sc.nextLine();
//line break
System.out.println();
// Ask use they want to continue
System.out.print("Continue? (y/n): ");
//Users choice
choice = sc.nextLine();
System.out.println();
}//END WHILE LOOP
//Close scanner object
sc.close();
}//END MAIN METHOD
private static String translated(String words) {
String lowerCase = words.toLowerCase();
int firstVowel = -1;
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCase.length(); i++) {
ch = lowerCase.charAt(i);
if (startsWithVowel(ch)) {
firstVowel = i;
break;
}
}
if (firstVowel == 0) {
return lowerCase + "way";
}else {
String one = lowerCase.substring(firstVowel);
String two = lowerCase.substring(0, firstVowel);
return one + two + "ay";
}
}
public static Boolean startsWithVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
This is the output I get automatically:
ava.util.scanner[delimiters=\p{javawhitespace}+][position=0][matchjay alid=false][needvay input=false][sourceway osed=false][skipped=false][groupclay eparator=\,][decimalsay eparator=.][positivesay efix=][negativepray efix=\q-\e][positivepray uffix=][negativesay uffix=][nansay ing=\qnan\e][infinitystray ing=\q?\e]stray

check is String vowel or consonant using java?

How do I check whether a String begins with a vowel or a consonant sound? For instance, University begins with a consonant sound; Hour begins with a vowel sound.
public static void main(String args[])
{
char ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word : ");
ch = scan.next().charAt(0);
if(ch=='a' || ch=='A' || ch=='e' || ch=='E' ||
ch=='i' || ch=='I' || ch=='o' || ch=='O' ||
ch=='u' || ch=='U')
{
System.out.print("This is a Vowel");
}
else
{
System.out.print("This is not a Vowel");
}
}
You cannot do this reasonably simply by examining the first letter. Rather, you need to refer to an on-line dictionary and use the first phoneme of the pronunciation. You've already coded the simple implementation: check the first letter. However, as your counterexamples show, this is not enough.
If this is a homework assignment, please contact your instructor for access to the pronunciation file.
public static int vovelsCount(String str) {
return str.replaceAll("[^aeiou]","").length();
}
import java.util.Scanner;
/**
* Java Program to count vowels in a String. It accept a String
from command promptand count how many vowels it contains. To revise,
5 letters a, e, i, o and u are known as
vowels in English.
*/
public class VowelCounter {
public static void main(String args[]) {
System.out.println("Please enter some text");
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
char[] letters = input.toCharArray();
int count = 0;
for (char c : letters) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
default:
// no count increment
}
}
System.out.println("Number of vowels in String [" + input + "] is : " + count);
}
}

Vowels are not being detected?

How to find a vowel in a given word?
import java.util.Scanner;
public class Test {
public static void main(String args[])
{
Scanner a =new Scanner(System.in) ;
String x=a.nextLine();
for(int i = 0;i<x.length();i++)
{
if(x.charAt(i)=='o');
System.out.println("the word has a vowel o");
break;
}
}
}
The reason for getting this output is "when i give input lets say jdbc it shows thisjdbc the word has a vowel o the word has a vowel o the word has a vowel o the word has a vowel o –" , your if statement is wrong.
When you give semi colon after the if statement, it means you are executing a empty statement.You can either remove the semicolon after your if statement
( if(x.charAt(i)=='o'){-----}) or try the below solution
I have slightly modified your code to capture and print all the vowels present in the given String.
Hope below code helps -:
public class Test {
public static void main(String args[])
{
Scanner a =new Scanner(System.in) ;
String x=a.nextLine();
for(int i = 0;i<x.length();i++)
{
if((x.charAt(i) == 'a') || (x.charAt(i) == 'e') ||(x.charAt(i) == 'i') || (x.charAt(i) == 'o') || (x.charAt(i) == 'u')) {
System.out.println("the word has a vowel -: "+x.charAt(i));
}
}
}
}
Change your if statement so it covers the print and break:
if(x.charAt(i)=='o') {
System.out.println("the word has a vowel o");
break;
}
Note that as soon as it detects the first letter 'o' it breaks.

Java phrase guessing game

Wondering how to exit if total phrase is guessed and why my vowels, spaces and consonants are not counting? Most of progam runs great just cant figure out how to exit without saying "n" to question. I am returning values for counters, don't understand?
import java.util.Scanner;
public class Prog09
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
// Initializes all string variables
String sPhrase;
String answer;
// Initializes all int variables
int vowels = 0;
int consonants = 0;
int spaces = 0;
// Initializes all char variables
char cGuess = 0;
char vGuess = 0;
boolean valid = false;
// Asks user to enter if they want to play
System.out.print("Do you want to play a game? [y/n] ");
answer = stdIn.nextLine();
// Asks user to enter the phrase
System.out.print("Please enter the phrase to guess at : ");
sPhrase = stdIn.nextLine();
// Checks if user wants to play
while (answer.equalsIgnoreCase("y"))
{
char[] phrase = new char[sPhrase.length()];
char[] tmpArr = new char[sPhrase.length()];
for(int i = 0; i < sPhrase.length();i++)
{
tmpArr[i] = sPhrase.charAt(i);
phrase[i] = sPhrase.charAt(i);
}
// Runs methods and main body of program
initTemplateArray(sPhrase, tmpArr, spaces);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
while (answer.equalsIgnoreCase("y"))
{
//getConsonant(stdIn, cGuess);
cGuess = getConsonant(stdIn, cGuess);
vGuess = getVowel(stdIn, vGuess);
isVowel(vGuess, valid);
updateTemplateArray(tmpArr, sPhrase, cGuess, vGuess, consonants, vowels);
printHeader();
printTemplateArray(tmpArr);
System.out.println("");
System.out.println("");
stdIn.nextLine();
System.out.print("Do you want to try again? [y/n]: ");
answer = stdIn.next();
vGuess = 0;
cGuess = 0;
}
}
// Prints results
System.out.println("The common phrase contained: Spaces: " + spaces + " Consonants: " + consonants + " Vowels: " + vowels);
stdIn.close();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for program
public static int initTemplateArray(String sPhrase, char [] tmpArr, int spaces)
{
for (int i = 0; i < sPhrase.length(); i++)
{
if (sPhrase.charAt(i) == ' ')
{
spaces++;
tmpArr[i] = ' ';
}
if (!(sPhrase.charAt(i) == ' '))
{
tmpArr[i] = '?';
}
}
return spaces;
}
public static void printTemplateArray(char [] tmpArr)
{
for (int i = 0; i < tmpArr.length; i++)
{
System.out.print(tmpArr[i]);
}
System.out.println();
}
public static boolean isVowel(char c, boolean valid)
{
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
{
return valid = true;
}
else
{
return valid = false;
}
}
public static char getConsonant(Scanner stdIn, char cGuess)
{
while(cGuess == 'a' || cGuess == 'e' || cGuess == 'i' || cGuess == 'o' || cGuess == 'u'|| cGuess == 0)
{
System.out.print("Enter a lowercase consonant guess : ");
String myGuess = stdIn.next();
cGuess = myGuess.charAt(0);
}
return cGuess;
}
public static char getVowel(Scanner stdIn, char vGuess)
{
while(!(vGuess == 'a' || vGuess == 'e' || vGuess == 'i' || vGuess == 'o' || vGuess == 'u'))
{
System.out.print("Enter a lowercase vowel guess : ");
String newGuess = stdIn.next();
vGuess = newGuess.charAt(0);
}
return vGuess;
}
public static int updateTemplateArray(char [] tmpArr, String sPhrase, char cGuess, char vGuess, int consonants, int vowels)
{
vowels = 0;
consonants = 0;
for (int i = 0; i < tmpArr.length; i++)
{
if (cGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
consonants++;
}
if (vGuess == sPhrase.charAt(i))
{
tmpArr[i] = sPhrase.charAt(i);
vowels++;
}
}
return consonants & vowels;
}
public static void printHeader()
{
System.out.println("");
System.out.println(" Common Phrase");
System.out.println("---------------");
}
}
Java passes Ints by value instead of by reference, this means that updateTemplateArray doesn't modify the values of main's vowels, consonants or spaces. To fix this you could:
Make these variables global by definining them outside the scope of the main method. You would have to change the name of the parameters in the updateTemplateArray method to prevent shadowing.
Break updateTemplateArray into separate functions to count each of the vowels, consonants or spaces, and have them return the count of each. You would then call something like: vowels = countVowels(sPhrase); to populate the variables.
With the current setup, it will exit whenever answer stops being equal to 'y' Changing the value of answer at any time will exit the loop.

Categories

Resources