I'm confusing how to transform values in 2D char array into number (integer).
Let's assume the array is: [[a, b],[c, d],[e, f]] or {{'a','b'},{'c','d'},{'e','f'}}
All values in that array will be converted to number, a=0, b=1, c=2, d=3, e=4, f=5.
I expect result like: [[0, 1], [2, 3], [4, 5]] or {{0, 1},{2, 3},{4, 5}}
If it's just a string of "abcdef", I can use charAt(), but I can' use it in an array, especially in char array. So, I use .replace.
package array_learning;
public class test {
public static void main(String[] args){
char [][] word= {{'a','b'},{'c','d'},{'e','f'}};
int strLength = word.length;
for(int i = 0; i<strLength; i++){
for(int j=0; j<2; j++){
String strWord = Character.toString(word[i][j]);
strWord = strWord.replace("a","0");
strWord = strWord.replace("b","1");
strWord = strWord.replace("c","2");
strWord = strWord.replace("d","3");
strWord = strWord.replace("e","4");
strWord = strWord.replace("f","5");
System.out.print(strWord+" ");
}
System.out.println();
}
}
}
But, the result is not what I've expected.
Result:
0 1
2 3
4 5
How to solve this in the right way?
Consider:
import java.util.Arrays;
public class Ctest {
public static void main(String[] args) {
char[][] word= { {'a', 'b'}, {'c', 'd'}, {'e', 'f'} };
println(word); // format with brackets e.g., [[a, b], [c, d]]
System.out.println(Arrays.deepToString(word)); // same format
for (int i = 0; i < word.length; i++) {
for (int j = 0; j < word[i].length; j++) {
if (word[i][j] >= 'a' && word[i][j] <= 'f') {
word[i][j] = (char) ((word[i][j] - 'a') + '0');
}
}
}
println(word); // formatted with brackets
printPlain(word); // formatted without brackets
}
public static void println(char[][] word) {
System.out.print("[");
for (int i = 0; i < word.length; i++) {
if (i > 0) System.out.print(", ");
System.out.print("[");
for (int j = 0; j < word[i].length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(word[i][j]);
}
System.out.print("]");
}
System.out.println("]");
}
public static void printPlain(char[][] word) {
for (int i = 0; i < word.length; i++) {
if (i > 0) System.out.print(", ");
for (int j = 0; j < word[i].length; j++) {
if (j > 0) System.out.print(", ");
System.out.print(word[i][j]);
}
}
System.out.println();
}
}
The main changes I have made are that the values in the array are actually converted (I'm not sure if you want this; you weren't storing any new values back into the array before), the data is handled as char without being converted to String, the conversion is done with a calculation instead of a special case for each value, and converting the data and printing it have been separated from one another.
There are also a few minor changes. The data is now printed in the format you demonstrated, with brackets, there is no assumption that the inner arrays always have exactly two elements, and the class name has been changed to start with a capital letter.
One other minor note. On the line that converts the values from lower case letters to digits, the expression is in parentheses and is cast back to a char. This is because when you add and subtract chars Java performs a widening conversion to int, so to store the value back into the char[][] it is necessary to cast it to char again.
I had forgotten that there is already a method in Java in the java.util.Arrays class to format a multidimensional array with brackets: Arrays.deepToString(word) will give you the same format as the println method above. I had also shown a printPlain method which is similar, but lacks the brackets, if you prefer a cleaner output format. You could also easily modify this method so that it appends to a StringBuilder and returns a String, instead of printing the array directly.
Everything is matching up correctly. This is a 2d array so your arrays are printing one by one.
If you don't want them to go on seperate lines then get rid of the System.out.println(); statement at the end of the for loop.
Use Arrays.toString() to convert your array into string first. Then do the replacement. For example:
char [][] word= {{'a','b'},{'c','d'},{'e','f'}};
String strWord = "";
for(char []w : word){
// convert array int [x, y] format
strWord += Arrays.toString(w)+",";
}
// removing comma(,) from end.
strWord = strWord.replaceAll(",$", "");
// do your replacement.
strWord = strWord.replace("a","0");
// ... more
// output
System.out.println("["+strWord+"]");
Related
I'm new to Java and I'm still learning. As a part of my learning I took a challenge to write a program that will take a string, and check if there are any words, that are 5 or more in length and if so, it will flip the chars in the 5+ long words. The challenge was to do it without using Collections.reverse(list) or StringBuilder.
My idea was, I'd say simple to write 2 methods.
Main will split the string, and iterate by each string array index looking for 5+ long words, and method called 'reverse' would be triggered inside 'if' condition. Look like this one works okay.
For the reverse method idea was to split the word to an array, and then with help of 2 nested 'for' loops iterate by indexes of 'ori' and auxiliary 'rev' arrays to assign value of index ori[i] to index rev[j].
So beginning with i=0 and j=arr.length-1 will result with assigning value "s" out of sentence word in ori[0] to rev[7], then "e" from ori[1] to rev[6], and so on, so the result would be [e, c, n, e, t, n, e, s]
Instead I get output like this:
[This, [e, e, e, e, e, e, e, e], will, [n, n, n, n, n, n, n], [s, s, s, s, s], with, more, than, five, [., ., ., ., ., ., ., .]]
I tried to fix that many ways, but so far my logic fails. Could someone explain me please, what am I doing wrong, how did I screw that apparently simple logic?
I'll figure out how to display this as a regular sentence without square brackets and commas later so this is no issue so far.
The code:
import java.util.Arrays;
public class Main {
public static void main (String[] args) {
String original = "This sentence will contain words with more than five letters.";
String[] splitter = original.split(" ");
for (int i = 0; i < splitter.length; i++){
if (splitter[i].length() >= 5){
splitter[i] = reverse(splitter[i]);
}
}
System.out.println(Arrays.toString(splitter));
}
public static String reverse (String s){
String [] ori = s.split("");
String [] rev = new String[ori.length];
for (int i = 0; i < rev.length; i++) {
for (int j = rev.length-1; j >=0; j--) {
rev[j] = ori[i];
}
}
s = Arrays.toString(rev);
return s;
}
}
Please be understading for a newbie :)
I tried to modify this part:
public static String reverse (String s){
String [] ori = s.split("");
String [] rev = new String[ori.length];
for (int i = 0; i < rev.length; i++) {
for (int j = rev.length-1; j >=0; j--) {
rev[j] = ori[i];
by swapping i/j, rev[i] = ori[j], --j, j > 0 and many others, mostly blind shots looking for some inspiration where my logic fails.
Hy Pawel Niewolak, the issue is with your reverse function.
Depending on your requirements use that:
public static String reverse(String s) {
String[] ori = s.split("");
String[] rev = new String[ori.length];
for (int i = 0; i < rev.length; i++) {
rev[i] = ori[rev.length - i - 1];
}
s = "";
for (String str : rev) {
s += str;
}
return s;
}
}
Here is another possibility that uses the existing array of characters.
create the array using String.toCharArray()
iterate half-way thru the array, simply swapping the end characters moving inward.
then since the String constructor takes an array of characters as an argument, return new String(array)
public static String reverse(String s) {
char[] array = s.toCharArray();
for (int i = 0; i <array.length/2; i++) {
char ch = array[i];
array[i] = array[array.length-i-1];
array[array.length-i-1] = ch;
}
return new String(array);
}
Note that for even length strings, the middle two characters are swapped. For odd length strings, the middle character is untouched.
Given a non-empty string str like "Code" print a string like "CCoCodCode". Where at each index in the string you have to reprint the string up to that index.
I know there is DEFINITELY something wrong with this code that I wrote because the answer should be CCoCodCode, but instead it's giving me the alphabet! I don't know how I should change it.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String str = scan.next();
int x = str.length();
for(char i = str.charAt(0); i <= str.charAt(x-1); i++)
{
System.out.print(i);
}
}
The char datatype can be treated as a number; you can increment it and manipulate it as a number.
What you really want is successive substrings of str to be printed. Loop over an int that will represent the ending position of the substring to be printed.
for (int i = 0; i < str.length(); i++)
{
System.out.print(str.substring(0, i + 1));
}
The end index argument to substring is exclusive, which is why I added 1.
Let's say that str is "Code". We can perform some mental substitutions to see what happens to your loop.
str is "Code"
x is 4
str.charAt(0) is 'C'
str.charAt(x-1) is 'e'
Making these substitutions, your loop is:
for(char i = 'C'; i <= 'e'; i++)
{
System.out.print(i);
}
Does this help you see the problem? I would think you'd have a loop from 0 to 3, not from 'C' to 'e'...
Many ways to get it done, suppose we have the input from user stored in a string named "c"... then...
String c = "Code";
for (int i = 0; i < c.length(); i++) {
System.out.print(c.substring(0, i));
}
System.out.print(c);
And this will print the sequence you are looking for.
It is outputting the alphabet because you are printing the counter instead of the characters in the string!
As it is, the first iteration of the for loop will set i to the first character, print that, then the operation i++ will increment i by one. Wait, so if the first character is "C", so i = 'C', what is i++?
Well it turns out characters can be represented by numbers. For example, 'C' has a value of 67. So incrementing it makes it 68, which represents 'D'. So if you run the loop on "Code", it will increment your counter 4 times, giving "CDEF". If you run on "Codecodecode", that will make the loop run 12 times, giving "CDEFGHIJKLMN".
What you really want is to loop through the string by its index instead:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.next();
int length = str.length();
for (int i = 0; i < length; i++) {
System.out.print(str.substring(0, i + 1));
}
}
When I run the method below keep in mind ADFGVX will be printed to the left and over the top of the array when its displayed, just like a classic ADFGVX cypher.
static char [][] poly = new char[][]{
{'p','h','0','q','g','6'},
{'4','m','e','a','1','y'},
{'l','2','n','o','f','d'},
{'x','k','r','3','c','v'},
{'s','5','z','w','7','b'},
{'j','9','u','t','i','8'}};
I have written a method that displays a polybius square using a 2d array(array can be seen above) and what I want to do is pair what ever the user enters with the square, so if the user types OBJECT I want it to return FG VX XA DF GV XG.
Scanner console = new Scanner (System.in);
String phrase;
displayGrid();
System.out.println("");
System.out.print("Please enter a phrase you want to use\n");
phrase = console.nextLine();
console.close();
Does anyone here know how I would go about this? I was going to make a switch statement or something but I don't think that would work and even if it did it would be very long and inefficient.
You could just iterate over your array to get the position of the character you are looking for and than decode this position to the letter.
public static String[] cypherADFGVX(String phrase){
String[] output=new String[phrase.length()];
for (int i = 0; i < phrase.length(); i++) {
//optional for breaking
//squareIteration:
for (int j = 0; j < 6; j++) {
for (int k = 0; k < 6; k++) {
if(poly[j][k]==phrase.charAt(i)){
output[i]=new String(new char[]{switchChar(j),switchChar(k)});
//To stop the iteration over poly and take care of the next char
//break squareIteration;
}
}
}
}
return output;
}
public static char switchChar(int integer){
switch (integer) {
case 0:
return 'A';
case 1:
return 'D';
//and so on
}
}
If I left any questions just ask.
To answer your questions
Oh. I see. I made it a bit too complicated for java beginners.
An easier solution with just one String would be:
public static String cypherADFGVX(String phrase){
String output=new String[phrase.length()];
for (int i = 0; i < phrase.length(); i++) {
//optional for breaking
//squareIteration:
for (int j = 0; j < 6; j++) {
for (int k = 0; k < 6; k++) {
if(poly[j][k]==phrase.charAt(i)){
output=output+switchChar(j)+switchChar(k)+" ";
//To stop the iteration over poly and take care of the next char
//break squareIteration;
}
}
}
}
return output;
}
Now let me explain what my lines do.
String[] output=new String[phrase.length()];
creates a new array of string where each string are the two capital letters.
It would look like ["FG","VX",...]. It is easier for futher processing in my opinion.
if(poly[j][k]==phrase.charAt(i))
Compares the character at position jk in your square with the i-th character of the input String.
output[i]=new String(new char[]{switchChar(j),switchChar(k)});
I use the String constructor that takes a char-array as argument.
new char[]{'a','b'}
creates the array and fills it with the elements listed in the brackets.
Sure you can use the switch to set the value of a variable and than return that variable.
I'm having trouble with this, maybe you could help me:
I have 3 strings like: word1, word2, word3 and I have to build a matrix with them, like this:
on the first row : word1("ABC"), second row: word2("DEF") and third row: word3("GHI").
A|B|C
D|E|F
G|H|I
I need this because after that I have to check if the formed words ("ADG","BEH","CFI") are in an array of words. And I don't know how to put those strings in the matrix so I can check. Any help is useful.
Thanks
Based on this comment:
the words have the same size, because the matrix is actually like a puzzle. I choose randomly 3 words from an array, put them in a matrix and check after that if the words resulted are from the same array.
I'll assume some things in order to make this work (since we don't have enough info):
You have an array of Strings where you have all the words
private String[] words;
You have a method to randomly pick up 3 Strings from this array.
private String s1, s2, s3;
public void pickThreeRandomWords() {
s1 = aRandomWord(words);
s2 = aRandomWord(words);
s3 = aRandomWord(words);
//or maybe another fancy algorithm to get this...
}
So you would need an array of array of chars based on these 3 Strings. This code could do the work for you:
public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[3][]; //yes, hardcoded
theMatrix[0] = s1.toCharArray();
theMatrix[1] = s2.toCharArray();
theMatrix[2] = s3.toCharArray();
return theMatrix;
}
Of course, if you would want to make this method to support more than 3 Strings you can make the method to receive a random quantity of Strings:
public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
You can build the result words without a matrix:
List<String> verticalWords = new ArrayList<String>();
for (int i = 0; i < horizontalLen; i++){
String currentWord = "";
for (int j = 0; j < wordCount; j++)
currentWord += words.get(j).get(i);
verticalWords.add(currentWord);
}
P.S. For the currentWord you can use a StringBuilder to make it more efficient, but I doubt it is highly needed here.
Java doesn't have matrix.It has array of array
So,you can try this
List<char[]> lst=new ArrayList();//stores a list of char[]
lst.add(("ADC".toCharArray()));//adds array of characters i.e 'A','D','C'
lst.add(("DEF".toCharArray()));
lst.get(0)[0];//A
lst.get(1)[0];//D
Now you can iterate vertically
for(int i=0;i<lst.size();i++)temp+=lst.get(i)[0];
temp would have AD which you can now cross check with equals method
The main thrust of this goal is that you're taking a one-dimensional value, and converting it into a two-dimensional value. There are many ways you can do this, but here are the two that come off the top of my head:
Set up a nested while loop to iterate over the first dimension, and when it reaches the length, reset and cause the outer loop to increment, much like a clock
You can create a new subarray using ArrayUtils.toSubArray(), and with some finagling, get that to work:
Create a new row of the array each time, based on the dimension slices you want to hit up. I'll leave figuring this one out as an exercise for the reader. But here's a hint:
for(int i = 0; i < theDimension; i++, j += 3) {
ret[i] = ArrayUtils.subarray(word, i*theDimension, j);
}
Lastly, I assume that there's a restraint on the type of input you can receive. The matrix must be square, so I enforce that restriction before we build the array.
I strongly encourage you to poke and prod this answer, and not just blindly copy it into your schoolwork. Understand what it's doing so you can reproduce it when you're asked to again in the future.
public char[][] toMatrix(int theDimension, String theEntireWord) {
if(theEntireWord.length() != theDimension * theDimension) {
throw new IllegalArgumentException("impossible to add string to matrix of uneven dimension");
}
char[][] ret = new char[theDimension][theDimension];
int i = 0;
int j = 0;
while(i < theDimension) {
if(j == theDimension) {
j = 0;
++i;
} else {
ret[i][j] = theEntireWord.charAt((i * theDimension) + j);
j++;
}
}
return ret;
}
I think this will sort your problem.
package printing;
public class Matrix {
public static void main(String[] args) {
//Length can define as you wish
String[] max = new String[10];
String[] out = null;
//Your Inputs
max[0]="ADG";
max[1]="BEH";
max[2]="CFI";
//following for loop iterate your inputs
for (int i = 0; i < max.length; i++) {
if(out==null){out= new String[max.length];}
String string = max[i];
if(string==null){ break;}
//Here breaking input(words) one by one into letters for later contcatnating.
String[] row = string.split("");
for (int j = 0; j < row.length; j++) {
String string1 = row[j];
// System.out.println(string1);
//create the values for rows
if(out[j]!=null){ out[j]=out[j]+string1;}
else{
out[j]=string1;
}
}
}
//following for loop will out put your matrix.
for (int i = 0; i < out.length; i++) {
String string = out[i];
if(out[i]==null){break;}
System.out.println(out[i]);
}
}
}
I am trying to store a string into an integer array with the following code:
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Integer.parseInt( s.charAt(i));
}
}
eclipse is giving me an error saying: the method parseInt(string) is not applicable for the arguments (char)
What am I doing wrong?
You need to parse the char, or convert it to a String.
If you're trying to get one digit at a time, and you know your input is a digit, then the easiest way to convert a single digit to an int is just
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
If you want to keep using Integer.parseInt, then just do
intArray[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
// or
intArray[i] = Integer.parseInt(s.substring(i, i+1));
That's because Integer.parseInt() expects a String as parameter, while you are passing a char (s.charAt() returns a char).
Since you are creating the array one digit at a time, a better way to get the decimal representation would be:
intArray[i] = s.charAt(i) - '0';
char is not a String so use a substring function s.substring(i, i+1) or better intArray[i] = s.charAt(i)
s.charAt returns a char.
+ parseInt take a String
= Eclipse gives you the compilation error
You may create a String from the char if really needed:
s.charAt(i)+""
String[] split = s.split("");
int[] nums = new int[split.length];
for(int i = 0; i < split.length; i++){
nums[i] = Integer.parseInt(split[i]);
}
public class Storing_String_to_IntegerArray
{
public static void main(String[] args)
{
System.out.println(" Q.37 Can you store string in array of integers. Try it.");
String str="I am Akash";
int arr[]=new int[str.length()];
char chArr[]=str.toCharArray();
char ch;
for(int i=0;i<str.length();i++)
{
arr[i]=chArr[i];
}
System.out.println("\nI have stored it in array by using ASCII value");
for(int i=0;i<arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println("\nI have stored it in array by using ASCII value to original content");
for(int i=0;i<arr.length;i++)
{
ch=(char)arr[i];
System.out.print(" "+ch);
}
}
}