I am trying to print the array of characters by shuffling them. I saw other posts as well but wish to come up with my own naive algorithm. Here is the code :
public class Carbon{
public static void main(String args[]){
Char A = new Char[6] {'c','a','r','b','o','n'};
for (int i=0;i<6;i++) {
for (int j=0;j<6;j++) {
if(i<=j) {
for (int k=i;k<=j;k++)
System.out.print(A[k]);
}
else{
for (int k=i;k>=j;k--)
System.out.print(A[k]);
}
}
}
}
}
The following errors occurred :
Carbon.java:3: error: ';' expected
Char A = new Char[6] {'c','a','r','b','o','n'};
^
Carbon.java:3: error: not a statement
Char A = new Char[6] {'c','a','r','b','o','n'};
^
Carbon.java:3: error: ';' expected
Char A = new Char[6] {'c','a','r','b','o','n'};
^
3 errors
I brainstormed more than 1 hour to debug but failed. Please help.
Just change it to char[] a = new char[]{'c', 'a', 'r', 'b', 'o', 'n'};
It's a little clumsy to access individual characters if you use the String type.
You have severals issues here.
Char is used for a class named "Char", if you want to use the primitive type, the name as to be in lower case "char"
So in your case:
Char A = new Char[6] {'c','a','r','b','o','n'};
has to become
char A = new char[6] {'c','a','r','b','o','n'};
But still now it does not work because you are trying to bind a unique char to an array of char
So here again, code has to be fixed to:
char[] A = new char[6] {'c','a','r','b','o','n'};
Now there is the last problem, you have a new array and a static array at the same time. So either you set your variable "A" (for which the name should be lower case as per convention) either you assign the static array.
Let's stick with the second option and you code becomes:
char[] A = {'c','a','r','b','o','n'};
And now it works
Output will be :
ccacarcarbcarbocarbonacaararbarboarbonracrarrbrborbonbracbrabrbbobonobracobraobroboonnobracnobranobrnobnon
Related
The instructions >>
Implement the method named removeVowels which processes the array of strings named words by printing each string from words with only non-vowels on its own line.
For example, if words contains:
{"every", "nearing", "checking", "food", "stand", "value"}
The method should output:
vry
nrng
chckng
fd
stnd
vl
So far, I have:
public class U6_L3_Activity_Two {
public static void removeVowels(String[] hit_str) {
char vowels = {
'a',
'e',
'i',
'o',
'u',
'A',
'E',
'I',
'O',
'U'
};
for (int i = 0; i < hit_str.length; i++) {
if (find(vowels.begin(), vowels.end(),
hit_str[i]) != vowels.end()) {
hit_str = hit_str.replace(i, 1, "");
i -= 1;
}
}
return hit_str;
}
}
Runner:
import java.util.Scanner;
public class runner_U6_L3_Activity_Two
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter array length:");
int len = scan.nextInt();
scan.nextLine();
String[] wordList = new String[len];
System.out.println("Enter values:");
for(int i = 0; i < len; i++)
{
wordList[i] = scan.nextLine();
}
U6_L3_Activity_Two.removeVowels(wordList);
}
}
The error message i'm getting says:
U6_L3_Activity_Two.java:3: error: illegal initializer for char
char vowels = {
^
I've tried a bunch of different ways to make a list of vowels but none of them seem to work.
Try replacing vowels with this built-in method:
String[] hit_str = { "every", "nearing", "checking", "food", "stand", "value" };
for (String str : hit_str) {
System.out.println(str.replaceAll("[AaEeIiOoUu]", ""));
}
Here, the for loop iterates over your input string/s and uses Regex to check if char(s) is/are found from the provided Regex. [AaEeIiOoUu] tries to match all chars of Regex individually in the string chars. Using Regex is better than declaring a char[] as it improves code readability and saves us from writing complex logics.
There're many way to do this. I reccomen to split 2 tasks: remove vowels and print the results.
private static final Pattern VOWELS = Pattern.compile("(?i)[aeiou]");
public static String[] removeVowels(String[] words) {
return Arrays.stream(words)
.map(word -> VOWELS.matcher(word).replaceAll(""))
.toArray(String[]::new);
In case you are able to modife the original array, you can avoid creation of the new one.
public static String[] removeVowels(String[] words) {
for (int i = 0; i < words.length; i++)
words[i] = VOWELS.matcher(words[i]).replaceAll("");
return words;
}
Assumptions
This looks like a college class task. So, I'm going to answer assuming that you can't use more advanced data structures such as List, Set, etc. I'm also going to assume that you can't box and unbox your primitives (i.e. change int to Integer). If I recall from my college courses, the main point of these tasks is to learn to implement basic logic and loops. This means you don't need to use advanced Java features such as Pattern and Stream.
This means that we need to stick with primitives, basic arrays, basic loops, and basic java functionality. This also means that the code likely isn't going to be efficient, but it will meet the requirements of your course.
Error Message
Your Error message says
"illegal initializer for char"
You are trying to shove an array into a single character. You can't do that. Put some brackets after char, and your error message should go away.
char[] vowels = {
'a',
'e',
'i',
'o',
'u',
'A',
'E',
'I',
'O',
'U'
};
That being said, don't use this. It's clunky and error prone. There are better ways.
Remove Vowels Method
That's not the only problem with your code though. Your void method removeVowels has a return value. void methods don't return anything.
Working through the task
Since the instructions say you have to receive an array of Strings, we know that your method, at a minimum, should look something like
void removeVowels(String[] hit_str);
or
String[] removeVowels(String[] hit_str);
Since you can modify the String array without having to pass it around, the void method should work fine. So, now we can look at what the method should do. Here's some pseudo code:
void removeVowels(String[] hit_str){
for (int i = 0; i < hit_str.length; i++) {
// if hit_str[i] contains a vowel, then remove it <-- Pseudo Code
}
}
Fleshing out the Pseudo Code
At the point we hit the pseudo code, we know that hit_str[i] is a value within the array, and we know that it is a String. Since String extends Java's Object, we know that it can be null. We also know that "" is a valid empty String. We also know that "cdf" is also a valid String which doesn't contain any vowels.
So, we know that we should account for a null value in the array, as well as a value that has a length of 0, and a value that already matches our required criteria of no vowels.
So, our pseudo code now looks something like this
// this could also be if (hit_str[i] != null ...
if (Objects.nonNull(hit_str[i]) && !hit_str[i].isEmpty()) {
// remove vowels if they exist
}
Getting to work
Now that we finally have a String to work with, how do we remove the vowels from it. Since our object is a String, java has a lot of methods to help us. The best method would be replaceAll.
replaceAll uses a regex pattern to find any elements in the String that match the pattern, and replaces them with your designated replacement. Our Regex would look like this "(?i)[aeiou]". It can be a bit confusing at first, but the elements in parentheses are the modifiers. The ? says match everything after, and the i means case insensitive. The elements in the brackets are the elements to match. So, this regex says to match everything in the string, case insensitive, against the letters in the brackets.
Example:
String myString = "Look at all the vowels aeiou and AEIOU both upper and lower case";
System.out.println(myString.replaceAll("(?i)[aeiou]", ""));
This code produces Lk t ll th vwls nd bth ppr nd lwr cs.
Putting it together
So, our final code would look something like this.
void removeVowels(String[] hit_str){
for (int i = 0; i < hit_str.length; i++) {
if (Objects.nonNull(hit_str[i]) && !hit_str[i].isEmpty()) {
hit_str[i] = hit_str[i].replaceAll("(?i)[aeiou]", ""));
}
}
}
Using the method
Your main method should now look like this after the String[] array has been created.
removeVowels(wordList);
for (int i = 0; i < wordList.length; i++) {
System.out.println(wordList[i]);
}
I need to encode a given message using cipherTable and a given key. I'm pretty sure there's something wrong with the encode method but i'm not sure what. This code:
import java.util.ArrayList;
public class Prog3Cipher {
// INSTANCE VARIABLES
static char[] keyList; // VARIABLE DESCRIPTION COMMENT
static char[][] cipherTable; // VARIABLE DESCRIPTION COMMENT
String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String encode(String message) {
String result = "";
ArrayList<Character> w = new ArrayList<>();
String[] m = new String[]{message};
for (int p = 0; p < m.length; p++) {
int row = Character.getNumericValue(keyList[p]);
int column = Character.getNumericValue(Integer.parseInt(m[p]));
char q = cipherTable[row][column];
w.add(q);
}
result = String.join(" ", (CharSequence) w);
return result;
}
public Prog3Cipher(char code, String key) {
keyList = key.toCharArray();
int offset = code - 'A';
cipherTable = new char[26][26];
for (int x = 0; x < cipherTable.length; x++) {
for (int y = 0; y < cipherTable[0].length; y++) {
cipherTable[x][y] =
alpha.charAt((x + y + offset) % alpha.length());
}
}
}
public static void main(String[] args) {
// Testing only works if using VM argument -ea
Prog3Cipher self = new Prog3Cipher('H', "BABBAGE");
assert "PHXXF MQYBPKNJ".equals(self.encode("Happy Birthday"));
}
}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Happy Birthday"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Prog3Cipher.encode(Prog3Cipher.java:24)
at Prog3Cipher.main(Prog3Cipher.java:68)
Process finished with exit code 1
the encode method takes a cipher table, cipherTable, and finds the intersection point of the row and column, which are found with keyList and m, and the intersection is set to q and then added to an Arraylist w. Result is set to a String and returned.
i'm not sure what's wrong as there are no errors with the code so if anyone could look over it and give some guidance it would be much appreciated.
This line is the likely culprit.
int column = Character.getNumericValue(Integer.parseInt(m[p]));
The NumberFormatException is from the Integer.parseInt(). If you inspect m[p] you'll find that it is an array of length 1 with an where m[0]="Happy Birthday". The String "Happy Birthday" can't be parsed as a number, thus the exception.
If you want to break a String into its individual characters, you could use String.toCharArray() like this: char[] m = message.toCharArray();
There are some other issues in your code:
In the main() method an instance of Prog3Cipher is being created, but encode() is static, so the call to self.encode() likely isn't working as you might expect. Removing static from the method declaration of encode() should fix that problem.
Character.getNumericValue() returns the unicode value of the provided character. That method returns 10 for 'A' through 35 for 'Z', so the values don't match the bounds of your cipherTable array.
As written, the for loop in encode() will walk past the end of the keyList[] array. This is because keyList[] only has 7 characters compared to the 14 chars in message.
The encode() method doesn't have any special handling for spaces in message, so they'll most likely also cause an exception.
Trying to write a java method that will take a string, loop through it and where it finds a vowel (A,E,I,O,U,Y) replace it with the vowel plus "OB".
I've written the below but it isn't working as I'd expect and doesn't seem to be matching the current character in my string with the vowels from my list. (The program compiles and runs so it isn't an issue with not importing necessary bits at the beginning. The input string will always be uppercase and only contain alphas.) I'm struggling to figure out where I'm going wrong.
Can anyone help?
public static String obifyText(String text) {
String[] myList = new String[] {"A","E","I","O","U","Y"};
StringBuilder tempText = new StringBuilder(text);
String obify = "OB";
for (int i = 0; i < text.length() -1 ; i ++ ) {
if ( Arrays.asList(myList).contains(tempText.charAt(i)) ) {
System.out.println(tempText.charAt(i)+" found.");
tempText = tempText.insert((i+1),obify);
}
}
text = tempText.toString();
return text;
}
Don't play with indexes.
Managing with indexes could be difficult when you are dealing with changing the string.
Loop on the chars itself as follows:
public static void main(String[] args){
String[] myList = new String[] {"A","E","I","O","U","Y"};
String text = "AEE";
StringBuilder tempText = new StringBuilder("");
String obify = "OB";
for (char c : text.toCharArray()){
tempText = tempText.append(c);
if ( Arrays.asList(myList).contains(c+"") ) {
System.out.println(c+" found.");
tempText = tempText.append(obify);
}
}
text = tempText.toString();
System.out.println(text);
}
OUTPUT:
A found.
E found.
E found.
AOBEOBEOB
charAt returns a char, but myList stores String elements. An array of Strings can never contain values of char. Your if statement never runs.
You can convert the char value to a string:
Arrays.asList(myList).contains(Character.toString(tempText.charAt(i)))
There's just one more problem with your code.
When the code inserts OB after a vowel, there is a side effect: a new vowel O is created. Your code then tries to insert OB after the new O. This is undesired, right?
To make it not do this, you can loop from the end of the string to the start:
for (int i = text.length() - 1; i >= 0 ; i--) {
If this is not a homework question to practice using StringBuilder or for loops, here's a one liner solution using regex:
return text.replaceAll("([AEIOUY])", "$1OB");
You compare two different types in Arrays.asList(myList).contains(tempText.charAt(i)), Arrays.asList(myList) is a List<String> and tempText.charAt is a char. So the contains check will never result in true.
One possible fix, change myList to Character[]
Character[] myList = new Character[] {'A','E','I','O','U','Y'};
There is another problem with the actual insertion, see Pankaj Singhal answer for a solution to that.
I am trying to make a 2D array that stores character values and I keep running into errors. Here's the code I have so far.
public static void main(String[] args) {
char[][] text;
text = new char[20][45];
// Enter your message into the array
char text[][] = {{A, ,b,i,g, },{d,o,g, ,a,t,e},{ ,a, ,p,i,g}};
java.util.Scanner input = new Scanner(System.in);
for (char column = 0; column < text[0].length; column++) {
for (char row = 0; row < text.length; row++) {
System.out.println(text[row][column] + " " );
}
System.out.println();
}
}
}
I am also trying to print the values in column major order. How do I make this 2D array store letters? When I put letters into the array I get an error saying "A cannot be resolved to a variable, b cannot be resolved to a variable, etc." How do I set the array up so it can store these values and not result in errors?
A quick answer with thanks to #Kon in the comments:
Characters need to have quotes around them. If I execute
char[][] text;
text = new char[20][45];
char text[][] = {{h, i},{ ,b , o ,b}};
Firstly, I would already get the error Duplicate local variable text because you are defining text 2 times: One when you say char[][] text; and the other time when you say char text[][] =. Assuming you fixed that and put the right code, you still have a problem:
YOU DON'T HAVE THE CHARACTERS RIGHT Next time, do this
{{'h', 'i'}, {' ', 'b', 'o', 'b'}}
Instead of
{{h, i}, { , b, o, b}}
I am trying to convert character values to ASCII values in java.
Below is my code.
public class test {
public static void main(String[] args)
{
System.out.println("Enter the string to be converted");
Scanner input = new Scanner(System.in);
String str =input.nextLine();
char ch[]=str.toCharArray();//hello
for(int i =0;i<str.length();i++)
{
char ascii[i]=ch[i];
System.out.println((int)ascii[i]);
}
input.close();
}
}
I want to get the string from the user, and store it in an array(which I a m doing it in ch[]) and for each element in array, I want to print its corresponding ASCII value.
But at line char ascii[i]=ch[i]; the interpreter is telling Type mismatch: cannot convert from char to char[].
Where is the problem ? as both of my character initialization are arrays, then why is it telling that its type mismatch ?
Note: I want the ascii variable to be stored as an array only.
You can't assign a char to a char array.
Change
for(int i =0;i<str.length();i++)
{
char ascii[i]=ch[i];
System.out.println((int)ascii[i]);
}
to
for(int i =0;i<str.length();i++)
{
char ascii = ch[i];
System.out.println((int)ascii);
}
EDIT:
If you wish to store the output in an array, you should declare the array before the loop :
char[] ascii = new char[str.length()];
for(int i =0;i<str.length();i++)
{
ascii[i] = ch[i];
System.out.println((int)ascii[i]);
}
when you declare ascii[i], you are trying to initialize a character array, but you are assigning it ch[i], which is a single character. Hence you get the error:
Type mismatch: cannot convert from char to char[].
As Eran said above, changing ascii variable from char array to character will resolve the issue.