here is a logical error how can i find the most vowel sentence has the user entered .
import java.util.Scanner;
public class ZanoreShqip {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String fjalia;
int count_zanore = 0;
int maxVowelCount = 0;
String wordWithMostVowels = "";
final String SENTINEL = "FUND";
System.out.print("Sheno fjali dhe fund per te perfunduar : ");
fjalia=input.nextLine();
while(!fjalia.equalsIgnoreCase(SENTINEL)) {
fjalia = fjalia.toLowerCase();
for(int i = 0; i <fjalia.length(); ++i) {
char ch = fjalia.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u') {
count_zanore++;
} if ( count_zanore > maxVowelCount) {
wordWithMostVowels = fjalia;
maxVowelCount = count_zanore;
}
}
System.out.print("\nSheno fjali dhe fund per te perfunduar : ");
fjalia = input.nextLine();
}
System.out.println(wordWithMostVowels);
System.out.println(maxVowelCount);
}
}
You forgot this part count_zanore = 0;
Try this
while(!fjalia.equalsIgnoreCase(SENTINEL)){
fjalia = fjalia.toLowerCase();
for(int i = 0; i <fjalia.length(); ++i)
{
char ch = fjalia.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u'){
count_zanore++;
}
if ( count_zanore > maxVowelCount){
wordWithMostVowels = fjalia;
maxVowelCount = count_zanore;
}
}
count_zanore = 0;
System.out.print("\nSheno fjali dhe fund per te perfunduar : ");
fjalia = input.nextLine();
}
Related
I have created a password checker program. All it does is ask for a password and then outputs if the password doesn't follow the rules I have made. I would like to get help to figure out to loop this right so you can check multiple passwords without restarting.
import java.util.Scanner;
public class password {
public static void main(String[] args) {
String end = "endofinput";
Scanner word = new Scanner(System.in);
System.out.print("Password:");
String password = word.nextLine();
// password
if(password.contains("password")){
System.out.println("Password may not contain the word password");
}
// lenght
if( password.length() < 8){
System.out.println("Needs to be longer");
}
//space/special check
if((password.contains(" ")||password.contains("#")|| password.contains("#")|| password.contains("!") || password.contains("~")|| password.contains("$") || password.contains("%") || password.contains("^")|| password.contains("*") || password.contains("(")|| password.contains(")") || password.contains("-")|| password.contains("+") || password.contains("/")|| password.contains(":") || password.contains("&")|| password.contains(".")|| password.contains(", ") || password.contains("<")|| password.contains(">")|| password.contains("?")|| password.contains("|"))){
System.out.println("No spaces or special Characters");
}
// Number
if(!(password.contains("1")|| password.contains("2")||password.contains("3")||password.contains("4")||password.contains("5")||password.contains("6")||
password.contains("7")||password.contains("8")||password.contains("9")||password.contains("0"))){
System.out.println("Need a Number");
}
// upper case
if (true) {
int count = 0;
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String e = Character.toString(c);
if (password.contains(e)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs an uppercase letter");
}
}
//lower case
if (true) {
int count = 0;
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs Lower case");
}
}
}
}
Just add a while with a "True" of condition, and put an if with a condition you want, to quit the loop, for example ìf(password == "Exit"). like this.
while(true)
{
System.out.print("Password:");
String password = word.nextLine();
if(password == "exit")
{
System.out.println("Ending the program");
break; //this break will stop the loop
}
// password
if(password.contains("password")){
System.out.println("Password may not contain the word password");
}
// lenght
if( password.length() < 8){
System.out.println("Needs to be longer");
}
//space/special check
if((password.contains(" ")||password.contains("#")|| password.contains("#")|| password.contains("!") || password.contains("~")|| password.contains("$") || password.contains("%") || password.contains("^")|| password.contains("*") || password.contains("(")|| password.contains(")") || password.contains("-")|| password.contains("+") || password.contains("/")|| password.contains(":") || password.contains("&")|| password.contains(".")|| password.contains(", ") || password.contains("<")|| password.contains(">")|| password.contains("?")|| password.contains("|"))){
System.out.println("No spaces or special Characters");
}
if(!(password.contains("1")|| password.contains("2")||password.contains("3")||password.contains("4")||password.contains("5")||password.contains("6")||
password.contains("7")||password.contains("8")||password.contains("9")||password.contains("0"))){
System.out.println("Need a Number");
}
// upper case
if (true) {
int count = 0;
for (int i = 65; i <= 90; i++) {
// type casting
char c = (char)i;
String e = Character.toString(c);
if (password.contains(e)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs an uppercase letter");
}
}
//lower case
if (true) {
int count = 0;
for (int i = 90; i <= 122; i++) {
// type casting
char c = (char)i;
String str1 = Character.toString(c);
if (password.contains(str1)) {
count = 1;
}
}
if (count == 0) {
System.out.println("Needs Lower case");
}
}
}
I've got the code to put a seven letter phrase into a phone number. The hyphen is not returning in the correct spot. I really don't know how to fix this problem. It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Code:
import java.util.*;
import java.lang.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if (letter== 'A' || letter=='a' || letter== 'B' || letter=='b' || letter=='C' || letter=='c') {
return '2';
}
else if (letter== 'D' || letter=='d' || letter== 'E' || letter=='e' || letter=='F' || letter=='f') {
return '3';
}
else if (letter== 'G' || letter=='g' || letter== 'H' || letter=='h' || letter=='I' || letter=='i') {
return '4';
}
else if (letter== 'J' || letter=='j' || letter== 'K' || letter=='k' || letter=='L' || letter=='l') {
return '5';
}
else if (letter== 'M' || letter=='m' || letter== 'N' || letter=='n' || letter=='O' || letter=='o') {
return '6';
}
else if (letter== 'P' || letter=='p' || letter== 'Q' || letter=='q' || letter=='R' || letter=='r'|| letter=='S' || letter=='s') {
return '7';
}
else if (letter== 'T' || letter=='t' || letter== 'U' || letter=='u' || letter=='V' || letter=='v') {
return '8';
}
else if (letter== 'W' || letter=='w' || letter== 'X' || letter=='x' || letter=='Y' || letter=='y' || letter=='Z' || letter=='z') {
return '9';
}
if (letter == ' ')
return '-';
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a 7 letter phrase: ");
String number = input.nextLine();
for (int i = 0; i < 8; i++) {
System.out.print(getNumber(number.toUpperCase().charAt(i)));
}
}
}
It should return xxx-xxxx and if the phrase is xxxx xxx it returns xxxx-xxx. Please someone help me with this problem!
Here you go! A bit of regex is always good for the soul:
{
String number = input.nextLine();
final StringBuilder builder = new StringBuilder(); // Buffer the sequence.
for (int i = 0; i < 8; i++) {
builder.append(getNumber(number.toUpperCase().charAt(i)));
if (builder.toString().getCharAt(2) != '-') // If the format isn't correct, fix it
System.out.println(builder.toString().replaceFirst("(...)(.).(...)", "$1-$2$3"))
}
}
As seen from CSᵠ's comment, you can use the following universal regex instead, such that the section becomes:
builder.toString().replaceFirst("^\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*(\\d)\\D*$", "$1$2$3-$4$5$6$7");
Edit: Updated regex as \N backreferences does not work in Java.
Here's a quick and dirty solution to your problem.
import java.util.*;
public class Project1 {
public static char getNumber(char letter) {
char ret = 0;
if( letter < 'A' )
{
ret = '0';
}
else if( letter < 'D' )
{
ret = '2';
}
else if( letter < 'G' )
{
ret = '3';
}
else if( letter < 'J' )
{
ret = '4';
}
else if( letter < 'M' )
{
ret = '5';
}
else if( letter < 'P' )
{
ret = '6';
}
else if( letter < 'T' )
{
ret = '7';
}
else if( letter < 'W' )
{
ret = '8';
}
else if( letter <= 'Z' )
{
ret = '9';
}
else
{
ret = '0';
}
return ret;
}
public static void main (String[] arg) {
Scanner input = new Scanner(System.in);
System.out.println( "Please enter a 7 letter phrase: " );
String number = input.nextLine().toUpperCase();
StringBuffer buff = new StringBuffer();
for( int i = 0, j = 0; j < number.length() && i < 7; j++ )
{
char c = number.charAt(j);
if( c != ' ' )
{
if( i == 3 )
{
buff.append( '-' );
}
buff.append( getNumber( c ) );
i++;
}
}
System.out.println( buff );
}
}
Key points:
There is no need to check for lower case if the alpha characters are guaranteed to be uppercase.
There is no need to uppercase the input string on each iteration of the loop. Do it once at the beginning.
I'm ignoring spaces, and always adding a hyphen before I print position 3 (ie the fourth character).
chars can be compared just like numbers, using ranges. This simplifies the amount of code quite a bit (ie. each letter within a range doesn't need to be written down).
This is the problem: Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)
countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2
This is my code:
public int countYZ(String str) {
int count = 0;
for (int i=0; i<str.length(); i++){
if (Character.isLetter(i) && (Character.isLetter(i+1)==false || i+1==str.length()) && (Character.toLowerCase(str.charAt(i))=='y' || Character.toLowerCase(str.charAt(i))=='z')){
count++;
}
}
return count;
}
I know it's messy, but I'm just trying to figure out why it's not working right now. It returns "0" each run through. In the if statement, I'm checking for: is i a letter? is i+1 a letter or the end of the string? and finally if i is 'y' or 'z'. Appreciate the help!
You could use a regex:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public int countYZ(String str) {
int count = 0;
Pattern regex = Pattern.compile("[yz](?!\\p{L})", Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = regex.matcher(str);
while (regexMatcher.find()) {
count++;
}
return count;
}
Explanation:
[yz] # Match the letter y or z
(?!\p{L}) # Assert that no letter follows after that
Use split() and endsWith()
public static int countYZ(String str) {
int count = 0;
String temp[] = str.split(" ");
for (int i = 0; i < temp.length; i++) {
if (temp[i].trim().endsWith("y") || temp[i].trim().endsWith("z"))
count++;
}
return count;
}
Output: for all your cases as required
countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2
try this fix
for (int i = 0; i < str.length(); i++) {
if ((Character.toLowerCase(str.charAt(i)) == 'y' || Character
.toLowerCase(str.charAt(i)) == 'z')
&& i == str.length() - 1
|| !Character.isLetter(str.charAt(i + 1))) {
count++;
}
}
Try This
public class CountXY {
/**
* #param args
*/
public static int countXY(String str){
int count = 0;
String strSplit[] = str.split(" ");
for(String i:strSplit){
if(i.endsWith("y")||i.endsWith("z")||i.endsWith("Y")||i.endsWith("Z")){
count++;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "Abcy Asdz z z z y y y yyu ZZ Y ";
System.out.println("Count::"+countXY(str));
}
}
public static int countYZ(String str) {
String[] array = str.split("[^a-zA-Z]");
int count = 0;
for (String s : array) {
if (s.toLowerCase().trim().endsWith("y") || s.toLowerCase().trim().endsWith("z"))
count++;
}
return count;
}
Your code is not working because following two conditions
Character.isLetter(i) --> here you are checking isLetter for the i which is int
(Character.isLetter(i+1)==false -> it will cause indexout of error
Please check following I have check its working fine, its just modified version of your code
public class FirstClass {
public static void main(String args[]) {
String string="fez day";
int count = 0;
String[] strcheck = string.split(" ");
for (String str : strcheck) {
if (Character.isLetter(str.charAt(str.length()-1)) &&(Character.toLowerCase(str.charAt(str.length()-1))=='y' || Character.toLowerCase(str.charAt(str.length()-1))=='z')){
count++;
}
}
System.out.println(count);
}
}
Hope this will help, Good Luck
You can try this too
public static void main(String[] args){
System.out.println(countYZ("abcxzy"));
}
public static int countYZ(String str) {
int countYandZ=0;
String[] arr=str.split(" ");
for (String i:arr){
if(("Y".equalsIgnoreCase(String.valueOf(i.charAt(i.length()-1))))||("Z".equalsIgnoreCase(String.valueOf(i.charAt(i.length()-1))))){
countYandZ++;
}
}
return countYandZ;
}
Here's what I've done:
public int countYZ(String str) {
//Initialize a return integer
int ret = 0;
//If it has at least 2 characters, we check both ends to see how many matching instances we have.
if (str.length() >= 2)
{
if (!Character.isLetter(str.charAt(1)) && (str.charAt(0) == 'y' || str.charAt(0) == 'Y' || str.charAt(0) == 'z' || str.charAt(0) == 'Z'))
{
ret++;
}
if (Character.isLetter(str.charAt(str.length() - 2)) && (str.charAt(str.length()-1) == 'y' || str.charAt(str.length()-1) == 'Y' || str.charAt(str.length()-1) == 'z' || str.charAt(str.length()-1) == 'Z'))
{
ret++;
}
}
//If it has more than 3 characters, we check the middle using a for loop.
if (str.length() >= 3)
{
for (int i = 2; i < str.length(); i++)
{
char testOne = str.charAt(i-2);
char testTwo = str.charAt(i-1);
char testThree = str.charAt(i);
//if the first char is a letter, second is a "YZyz" char, and the third is not a letter, we increment ret by 1.
if (Character.isLetter(testOne) && (testTwo == 'y' || testTwo == 'Y' || testTwo == 'z' || testTwo == 'Z') && (!Character.isLetter(testThree)))
{
ret++;
}
}
}
return ret;
}
public int countYZ(String str) {
int count=0;
if ( str.charAt(str.length() - 1) == 'z'||
str.charAt(str.length() - 1) == 'y'||
str.charAt(str.length() - 1) == 'Z'||
str.charAt(str.length() - 1) == 'Y' ) {
count += 1;
}
for (int i = 0; i < str.length(); i++) {
if ( i > 0 ) {
if ( !( Character.isLetter(str.charAt(i)) ) ) {
if ( str.charAt(i - 1) == 'y' ||
str.charAt(i - 1) == 'z' ||
str.charAt(i - 1) == 'Y' ||
str.charAt(i - 1) == 'Z' ) {
count += 1;
}
}
}
}
return count;
}
This allows the words to be separated by anything other than a letter. whitespace, numbers, etc.
public int countYZ(String str) {
int count = 0;
String newStr = str.toLowerCase();
for (int i =0; i < newStr.length(); i++){
if (!Character.isLetter(newStr.charAt(i))){
if (i > 0 && (newStr.charAt(i-1) == 'y' || newStr.charAt(i-1) == 'z'))
count++;
}
}
if (newStr.charAt(str.length()-1) == 'z' || newStr.charAt(str.length()-1) == 'y')
count++;
return count;
}
I am making a Pig Latin translator and I don't really knwo where to go from here. I have the basic code, but I need to revise it in order for it to translate a whole sentence. If anyone can tell me how to use my String[] words I would really appreciate it. Thanks a lot!
import java.io.*;
import java.util.*;
import java.util.Arrays;
public class Main
{
public static void main (String[] args)
{
System.out.print("Please enter a phrase to translate: ");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
String[] words = str.split("\\s+");
String answer = "";
if (str.startsWith("a") || str.startsWith("e") || str.startsWith("i") || str.startsWith("o") || str.startsWith("u"))
{
System.out.print(str + "way");
}
else
{
answer = str.substring(2,str.length());
String answer2 = str.substring(1,str.length());
String answer3 = str.substring(3,str.length());
String answer4 = str.substring(4,str.length());
String d = str.substring(0,4);
if (!(d.contains("a") || d.contains("e") || d.contains("i") || d.contains("o") || d.contains("u")))
{
System.out.print(answer4 + d + "ay");
}
else
{
String c = str.substring(0,3);
if (!(c.contains("a") || c.contains("e") || c.contains("i") || c.contains("o") || c.contains("u")))
{
System.out.print(answer3 + c + "ay");
}
else
{
String b = str.substring(0,2);
if (!(b.contains("a") || b.contains("e") || b.contains("i") || b.contains("o") || b.contains("u")))
{
System.out.print(answer + b + "ay");
}
else
{
String a = str.substring(0,1);
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
System.out.print(answer2 + a + "ay");
}
}
}
}
}
}
}
This should translate each word in that array, just use a for loop around your whole if block
for(String word: words) {
//put your whole if block here
//word is the variable to translate (i.e. word.startsWith("a"))
}
alternatively for beginners:
for(int i = 0; i < words.length(); i++) {
//put if statements here
//words[i] is the variable to translate (i.e. words[i].startsWith("a"))
}
You will also need to change all str references inside the loop to word[i], since that is the variable you want to use.
You can have a for loop that goes through each word, and apply your logic to each word:
for(String str : words ) {
if (str.startsWith("a") || str.startsWith("e") || str.startsWith("i") || str.startsWith("o") || str.startsWith("u"))
{
System.out.print(str + "way");
}
else
{
answer = str.substring(2,str.length());
String answer2 = str.substring(1,str.length());
String answer3 = str.substring(3,str.length());
String answer4 = str.substring(4,str.length());
String d = str.substring(0,4);
if (!(d.contains("a") || d.contains("e") || d.contains("i") || d.contains("o") || d.contains("u")))
{
System.out.print(answer4 + d + "ay");
}
else
{
String c = str.substring(0,3);
if (!(c.contains("a") || c.contains("e") || c.contains("i") || c.contains("o") || c.contains("u")))
{
System.out.print(answer3 + c + "ay");
}
else
{
String b = str.substring(0,2);
if (!(b.contains("a") || b.contains("e") || b.contains("i") || b.contains("o") || b.contains("u")))
{
System.out.print(answer + b + "ay");
}
else
{
String a = str.substring(0,1);
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
System.out.print(answer2 + a + "ay");
}
}
}
}
}
}
You can use an enhanced for loop around your if block to translate the entire array:
for(String word: words) {
/*
*if block goes here
*...
*/
}
Though creating a translator like this is rather unsafe (e.g. code injections), unless the input is put in from a trusted source.
If you are familiar with lexer/parsers you should look into using a generator such as ANTLR to create safer (albeight more complex) language translators.
#include stdio.h>
#include conio.h>
#include stdlib.h>
#include string.h>
void main()
{
char * sUserInput ;
char * check ;
char * firstletter;
char ch = NULL;
int i = 0 ;
int j = 0 ;
int k = 0 ;
int spacecount = 0 ;
int count = 0 ;
int count1 = 0 ;
int var = 0 ;
int gold = 1 ;
sUserInput = (char *) malloc(sizeof(char));
check = (char *) malloc(sizeof(char));
firstletter = (char *) malloc(4*sizeof(char));
printf("Enter the sentence \n");
while(ch != '\n')
{
scanf("%c",&ch);
sUserInput[i]=ch;
sUserInput = (char *) realloc(sUserInput,((i+2))*sizeof(char));
i++;
if( ch == ' ')
{
spacecount++;
}
}
while(sUserInput[j] != '\n')
{
count1++;
if(gold==1)
{
firstletter[var]=sUserInput[j];
firstletter[var+1]='a';
firstletter[var+2]='y';
gold=0;
j++;
}
if(sUserInput[j] !=' ')
{
check[k] = sUserInput[j];
check = (char *) realloc(check,((k+2))*sizeof(char));
printf("%c",check[k]);
k++;
}
if(sUserInput[j] ==' ' || (count1 == (i-(spacecount+2))))
{
for(count=0;count<3;count++)
{
printf("%c",firstletter[count]);
}
var=0;
gold=1;
printf(" ");
}
j++;
}
free(sUserInput);
free(check);
free(firstletter);
getch();
}
The method takes in any name and tests whether a character is a vowel or consonant. If it's a vowel, it makes the character uppercase, if it's a consonant, it makes the character lowercase. Any thoughts? I don't know how to add .toUpperCase and .toLowerCase in the if else statements.
public static void parsing(String name[])
{
String temp = name[0];
int i = 0;
for(i = 0; i < temp.length(); i++)
{
if(temp.charAt(i) == 'a' || temp.charAt(i) == 'A' ||
temp.charAt(i) == 'e' || temp.charAt(i) == 'E' ||
temp.charAt(i) == 'i' || temp.charAt(i) == 'I' ||
temp.charAt(i) == 'o' || temp.charAt(i) == 'O' ||
temp.charAt(i) == 'u' || temp.charAt(i) == 'U')
{
System.out.print(temp.charAt(i).toUpperCase);
}//Obviously wrong but I don't know what to do.
else
{
System.out.print(temp.charAt(i).toLowerCase);
}//Obviously wrong but I don't know what to do.
}
To convert a single character use the methods from the Character class:
System.out.print(Character.toUpperCase(temp.charAt(i)));
System.out.print(Character.toLowerCase(temp.charAt(i)));
Create two final arrays - one with the vowels, the second one with the consonants. Then check, whether the current char in the loop is a vowel or consonant and make the appropriate changes.
Your are hitting your head as String is immutable. Rebuild the resulting string.
A (bit suboptimal) solution is:
public static void parsing(String[] names)
{
for (int i = 0; i < names.length; ++i) {
names[i] = chAngEd(names[i]);
}
}
private static String chAngEd(String s) {
String result = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (ch == 'a' || ...) {
ch = Character.toUpperCase(ch);
} else {
ch = ...
}
result += ch;
}
return result;
}
public static void parsing(String names[]){
for (int i=0; i<names.length; ++i){
names[i] = capitaliseConsts(names[i]);
}
}
private static String capitaliseConsts(String name){
StringBuilder sb = new StringBuilder();
Character c;
for (int i=0; i<name.length(); ++i){
c = name.charAt(i);
if (c.equalsIgnoreCase('a') ||
c.equalsIgnoreCase('e') ||
c.equalsIgnoreCase('i') ||
c.equalsIgnoreCase('o') ||
c.equalsIgnoreCase('u')){
sb.append(Character.toUpperCase(c));
}
else{
sb.append(Character.toLowerCase(c));
}
}
return sb.toString();
}
String vowelsArray = "aeiuo";
String constantsArray = "uppercase constants";
int stringLength = name.length();
String givenNameCopy = name.ToString();
for(int i = 0; i < stringLength; i++){
if(vowelsArray.contains(givenNameCopy[i]))
then uppercase
else if(constantsArray.contains(givenNameCopy[i]))
then lowercase
else
continue;
hope this helps.