How to store characters in a 2D character array - java

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

Related

removing vowels from array

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

Java method not doing what expected. Trying to understand why

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.

Type mismatch in java

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.

To shuffle six characters and print the permutation of an array

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

How is this program coming along?

Instructions:
Write a program that will read a line of text that ends
with a period, which serves as a sentinel value. Display all the
letters that occur in the text, one per line and in alphabetical
order, along with the number of times each letter occurs in the text.
Use an array of base type int of length 26 so that the element at
index 0 contains the number of as. and index 1 contain number of bs etc.
package alphabetize;
import java.util.*;
public class Alphabetize
{
private static void number(String s)
{
int[] array = new int[26];
s = s.toUpperCase();
System.out.println(s);
for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
++array[s.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println("|" + (char) ('A' + i) + "|" + array[i] + "|");
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String aString = ".";
while (true)
{
System.out.println("Please enter sentence with a period to end");
aString = keyboard.nextLine();
if (".".equals(aString))
{
System.exit(0);
}
number(aString);
}
}
}
Still having problem with the period thing.. it does not seem to work the way i did it.
Considering this is a homework and instructions are very specific, you should read the text character by character instead of using built-in functions
If your text file was something like
abcabca.
The output should be something a appears three times, b appears two times etc etc.
So your algo should be something like
Read next character
If char is period goto 5
If char is space goto 1.
If char is between a <-> z. update the counter in arr[0..25] and goto 1
output arr[0..25] one per line
Was it mandated that this assignment is done in Java? The whole idea of a "sentinal character" rather than just using a line terminator is pretty bizarre.
Anyway, you can achieve the behaviour you want by setting the delimiter of Scanner:
keyboard.useDelimiter("\\.");
As for the looping, a big hint is this:
int[] counts;
counts[chars[0] - 'a'] = counts[chars[0] - 'a'] + 1;
or simply
counts[chars[0] - 'a']++;
I'll leave it up to you to include that in a loop.
Edit
If you are looking for character-at-a-time input, I would suggest you use an InputStreamReader instead of Scanner for your input. Here's a basic skeleton of what that looks like:
Reader reader = new InputStreamReader(System.in);
while (true) {
int nextInput = reader.read();
if (nextInput == -1) {
System.out.println("End of input reached without sentinal character");
break;
}
char nextChar = (char) nextInput;
//deal with next character
}
Still, read() will typically block until either the end of input is reached (CTRL-D or CTRL-Z from most consoles) or a new line is sent. Thus the sentinal character is of limited use since you still have to do something after typing ".".
You have to check whether period is there at the end or not. So the last character should be '.'.
Then take the length of string before last '.'.
For the counting part create an array like u are doing :
int [] name = new int[26]
where each index starting from 0, 25 corresponds to 'a' till 'z'.
Now you put the string characters in a loop and have to check what that character is like :
if its a 'a' : increase the value at index 0 by 1.
if its a 'd' : increase the value at index 3 by 1.
like wise.
later you display the whole array with a, z along with indexes from 0 till 25.
Suggestion: If its not required to use an array, and you can use any other data-structure you can implement the same in a HashMap very easily. by keeping 'a', 'z' as the keys and count as the corresponding values. and then retrieving and showing the values will also be easier.
You need an int array (e.g., int[] counts = new int[26];) After you read the input line, examine it character by character in a loop. If the character is a not period, then increment the appropriate element of the counts array. (If the character is a, then increment counts[0]; if it is b, increment counts[1]; etc. Hint: you can subtract a from the character to get the appropriate index.) When you find a period, exit the loop and print the results (probably using a second loop).

Categories

Resources