Invalid Identifier when using ArrayList<Character> - java

I am trying to finish this program for a homework assignment and This is the only thing not working. I get an expected error on this line:
System.out.println(myChars.equals(complement));
Here is my code
public class WCpalindrome {
private static char[] dna = {'A', 'C', 'T', 'G'};
private static ArrayList<Character> myChars = new ArrayList<Character>();
private static ArrayList<Character> reverse = new ArrayList<Character>();
private static ArrayList<Character> complement = new ArrayList<Character>();
public static char toUpperCase(char c) {
if (c == 'A' || c == 'a') {
return 'A';
} else if (c == 'T' || c == 't') {
return 'T';
} else if (c == 'C' || c == 'c') {
return 'C';
}
return 'G';
}
public static char getComplement(char c) {
if (c == 'A' || c == 'a') {
return 'T';
} else if (c == 'T' || c == 't') {
return 'A';
} else if (c == 'C' || c == 'c') {
return 'G';
}
return 'C';
}
public static void main(String[] args) {
char current;
int i = 0;
//Get the input sequence
while (StdIn.hasNextChar()) {
current = StdIn.readChar();
current = toUpperCase(current);
myChars.add(current);
StdOut.println(myChars.get(i));
i++;
}
System.out.println();
//Reverse the sequence
int k = 0;
int size = myChars.size() - 1;
for (int j = size-1; j >= 0; j--) {
current = myChars.get(j);
StdOut.println(current);
reverse.add(k, current);
k++;
}
System.out.println();
//Complement the reversed sequence
int n = 0;
size = myChars.size() - 1;
for (n = 0; n < size; n++) {
current = reverse.get(n);
complement.add(getComplement(current));
StdOut.println(complement.get(n));
}
}
//Prints true if the original equals the complement of the reversal
//else it prints false
System.out.println(myChars.equals(complement));
}

The line you are talking about is not inside any method. I think you want to move it inside your main method.

You have place the statement System.out.println(...); outside main(). Shift it up 3 lines. It is now at the level where method and field declarations are expected.
Also the equals will always return false as array instances do not compare there inside elements.
One might useArrays.equals` but you might simply use:
System.out.println(new String(myChars).equals(new String(complement)));

System.out.println(myChars.equals(complement));
outside of main method.
this should be in end
}
//Prints true if the original equals the complement of the reversal
//else it prints false
System.out.println(myChars.equals(complement));
}
}

Related

How to insert a syllable before a single vowel

I try to insert a syllable before each vowel with the following restrictions:
- Before each following vowel (a, e, i, o, u), insert the stray syllable "av".
- Unless the vowel is preceded by another vowel
Actually I've done this
public static String translate(String text) {
char [] charArray = text.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : charArray) {
if (charArray.length < 255){
if (isVowel(c)) {
sb.append(String.format("av%s" , c));
}
else {
sb.append(c);
}
}
}
return sb.toString();
}
static boolean isVowel(char c) {
return (c == 'a') || (c == 'e') ||
(c == 'i') || (c == 'o') ||
(c == 'u');
}
With words without double vowels it works perfectly:
Cat becomes
Cavat
But with double vowel it doesn't work
Meet becomes
Maveavet // Should return Meet
How to check if 2 successive letters are vowels in order not to add the syllable if it's the case ?
Thanks in advance
Here is a version that uses an ordinary for loop:
public static String translate(String text) {
char [] charArray = text.toCharArray();
StringBuilder sb = new StringBuilder();
Set<Character> vowels = new HashSet<>(Arrays.asList('a','e','i','o','u'));
char cFirst = charArray[0];
if (vowels.contains(cFirst) && !(vowels.contains(charArray[1]))) {
sb.append(String.format("av%s" , cFirst));
}
else sb.append(cFirst);
for (int i = 1; i < charArray.length-1; i++){
char c = charArray[i];
char cNext = charArray[i+1];
char cPrev = charArray[i-1];
if (vowels.contains(c) && !(vowels.contains(cNext) || vowels.contains(cPrev))) {
sb.append(String.format("av%s" , c));
}
else sb.append(c);
}
char cLast = charArray[charArray.length-1];
if (vowels.contains(cLast) && !(vowels.contains(charArray[charArray.length-2]))) {
sb.append(String.format("av%s" , cLast));
}
else sb.append(cLast);
return sb.toString();
}
Works for all the cases I could think of, but probably not the optimal way of doing this.
One approach is to manage the indexes yourself instead of using an enhanced for loop. This allows you to 'skip' over two vowel chunks by checking the next character if it exists. Something like this should work:
int i = 0;
while (i < charArray.length) {
char c = charArray[i];
if (isVowel(c)) {
if (i + i == charArray.length || isVowel(charArray[i+1])) {
sb.append("av");
} else {
i++;
}
}
sb.append(c);
i++;
}
Note that this does not solve for when there are three sequential vowels.

Trouble with Java vowel counter

I am having trouble getting my vowel counter to run in the for loop I created for this cap. Here is my code:
//java app that counts vowels using a forloop
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner ent=new Scanner(System.in);
String string1;
System.out.println("Entered a letter:");
string1 = ent.nextLine();}
public static int numberVowels(String string1){
int count=0;
int vowels=0;
int consonants=0;
for(int i=0; i<string1.length(); i++){
char ch=string1.charAt(i);
if(ch=='a' || ch=='e' ||ch=='i' ||ch=='o'||ch=='u' ){
vowels++;
return ch=ch+vowel;
}else{
consonants++;
}
}
}
}
It says that there is no return type but I do have a return type. What am I doing wrong
You have a return statement in your if (and it looks specious to me), you need one that is guaranteed to be reachable; since your method is for counting vowels you should stick to that. Finally, since you only test lower case vowels, I would recommend calling toLowerCase before your test. Something like,
public static int numberVowels(String string1) {
int vowels = 0;
for (int i = 0; i < string1.length(); i++) {
char ch = Character.toLowerCase(string1.charAt(i));
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
}
return vowels;
}
or using a for-each loop like
public static int numberVowels(String string1) {
int vowels = 0;
for (char ch : string1.toLowerCase().toCharArray()) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
}
return vowels;
}
Yes the message is regarding Java syntax try to fix using this:
always Java check that have returned a variable if your method has a return type.
´
//java app that counts vowels using a forloop
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner ent=new Scanner(System.in);
String string1;
System.out.println("Entered a letter:");
string1 = ent.nextLine();}
public static int numberVowels(String string1){
int count=0;
int vowels=0;
int consonants=0;
char tmp='';
for(int i=0; i<string1.length(); i++){
char ch=string1.charAt(i);
if(ch=='a' || ch=='e' ||ch=='i' ||ch=='o'||ch=='u' ){
vowels++;
tmp= ch=ch+vowel;
}else{
consonants++;
}
}
return tmp;
}
`

Java-How to translate a String to piglatin?

I am writing a pig latin code and I am tripped up by how to get my program to identify where the next vowel in the word is if the first letter in the word is a consonant. Then it moves the first part of the word, up to the first vowel, to the end of the word and prints ay along with it. (ex. trees = eestray)
This is the code I have now
// word is bringing in the string entered from the user
public static void translate(String word) {
String wordCap, pigLatin = "";
char vowels;
int lowest = 0, tempOne, tempTwo, tempThree, tempFour, tempFive;
wordCap = word.toUpperCase();
vowels = wordCap.charAt(0);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
word = word + "way";
System.out.println(word);
}
else {
tempOne = wordCap.indexOf('A', 1);
if (lowest > tempOne && tempOne != -1) {
lowest = tempOne;
}
tempTwo = wordCap.indexOf('E', 1);
if (lowest > tempTwo && tempTwo != -1) {
lowest = tempTwo;
}
tempThree = wordCap.indexOf('I', 1);
if (lowest > tempThree && tempThree != -1) {
lowest = tempThree;
}
tempFour = wordCap.indexOf('O', 1);
if (lowest > tempFour && tempFour != -1) {
lowest = tempFour;
}
tempFive = wordCap.indexOf('U', 1);
if (lowest > tempFive && tempFive != -1) {
lowest = tempFive;
}
public static char vowel(String word) {
int start= 0, end= 0;
char vowels;
for (int i = 0; i < word.length(); i++) {
vowels = word.charAt(i);
if (vowels == 'A' || vowels == 'E' || vowels == 'I' || vowels == 'O' || vowels == 'U') {
end = i;
break;
}
}
return (char) end;
}
(in translate method)
for (int i = 0; i<wordCap.length(); i++) {
if (vowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
}
}
The problem now is that the vowel method is not an applicable method type. It says it must be a char?
Let me try to shorten that method for you ;)
Try something like this:
private static final char[] vowels = {'a', 'e', 'i', 'o', 'u'};
public static String translate(String word) {
int start = 0; // start index of word
int firstVowel = 0;
int end = word.length(); // end index of word
for(int i = 0; i < end; i++) { // loop over length of word
char c = Character.toLowerCase(word.charAt(i)); // char of word at i, lower cased
if(Arrays.asList(vowels).contains(c)) { // convert vowels to a list so we can use List.contains() convenience method.
firstVowel = i;
break; // stop looping
}
}
if(start != firstVowel) { // if start is not equal to firstVowel, we caught a vowel.
String startString = word.substring(firstVowel, end);
String endString = word.substring(start, firstVowel) + "ay";
return startString+endString;
}
return word; //couldn't find a vowel, return original
}
What this snippet does, is iterate over every character in the word, storing the index of the first vowel in the firstVowel variable. Then, we get every character from firstVowel to end; and store it in startString. Then, we get every character from start to firstVowel; add "ay", and store it in endString. Finally, we concatenate these strings together and return them, resulting in the desired output.
We can test this with System.out.println(translate("trees"));
EDIT: Without array, as requested:
public static String translate(String word) {
char a = 'a';
char e = 'e';
char i = 'i';
char o = 'o';
char u = 'u';
int start = 0;
int firstVowel = 0;
int end = word.length();
for(int i = 0; i < end; i++) {
char c = Character.toLowerCase(word.charAt(i));
if(c == a || c == e || c == i || c == o || c == u) {
firstVowel = i;
break;
}
}
if(start != firstVowel) {
String startString = word.subString(firstVowel, end);
String endString = word.subString(start, firstVowel) + "ay";
return startString+endString;
}
return word;
}
As you can see, arrays shorten things up quite a bit!
If you're feeling pedantic about the Arrays.asList().contains() call, we could define our own:
public static boolean containsChar(char[] lookIn, char lookFor) {
boolean doesContainChar = false;
for(char c : lookIn) {
if(doesContainChar = c == lookFor)
break;
}
return doesContainChar;
}
You might want to use a for loop to iterate through the letters of each word until it finds a vowel. Example:
String wordCap = word.toUpperCase();
char vowels;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
break;
}
}
Of course, I only used isVowel() for the sake of keeping the example concise. You'll have to identify it as a vowel the same way you did in your first if statement (or write an isVowel() method yourself).
For modifying the word, you'll also want to declare a variable to hold the index of the vowel. The previous section of code could be added to for this, like so:
String wordCap = word.toUpperCase();
char vowels;
int vowelIndex;
String newWord;
for (int i=0; i<wordCap.length(); i++) {
if (isVowel(wordCap.charAt(i))) {
vowels = wordCap.charAt(i);
vowelIndex = i;
break;
}
}
Then you could reference vowelIndex when modifying the word.
if (vowelIndex == 0) {
newWord = word + "way";
} else {
newWord = word.substring(vowelIndex) + word.substring(0, vowelIndex) + "ay";
}
return word;

Count y and z at end of a word

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;
}

Java - Converting the characters in a string array depending on whether or not it's a vowel

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.

Categories

Resources