I'm trying to write a code which gets as an input an array of strings, and creates a two-dimensoinal array of type char, the number of lines is as the number of words in the string and in each line there is a reversed array of the letters in the word.
for example if my input is: start at the end!
my output will be :
[t, r, a, t, s]
[t, a]
[e, h, t]
[!, d, n, e]
This is my code:
public static void main(String[] args) {
char thelist[][] = new char[args.length][];
for (int i = 0; i < args.length; i++) {
thelist[i] = new char[args[i].length()];
for (int k = 0; k < args[i].length(); k++) {
char letter = args[i].charAt(args[i].length() - k - 1);
thelist[i][k] = letter;
}
for (char[] word : thelist) {
String list = Arrays.toString(word);
System.out.println(list);
}
}
}
The code should be like this :
String str ="start at the end!";
String[] splitString = str.split(" ");
int length=0;
for(String string:splitString ){
if(string.length()>length){
length=string.length();
}
}
Character[][] charArray = new Character[splitString.length][length];
int index=0;
for(String string:splitString ){
length=string.length();
for(int i=0;i<string.length();i++){
charArray[index][--length]=string.charAt(i);
}
index++;
}
for (int i=0;i<charArray.length;i++){
for (int j=0;j<charArray[i].length && charArray[i][j]!=null;j++) {
System.out.print(charArray[i][j]);
}
System.out.println();
}
OUTPUT:
trats
ta
eht
!dne
You are getting extra lines because you are printing inside the outer for loops. try this. it should work.
public static void main(String[] args) {
char thelist[][] = new char[args.length][];
for (int i = 0; i < args.length; i++) {
thelist[i] = new char[args[i].length()];
for (int k = 0; k < args[i].length(); k++) {
char letter = args[i].charAt(args[i].length() - k - 1);
thelist[i][k] = letter;
}
}
for (char[] word : thelist) {
String list = Arrays.toString(word);
System.out.println(list);
}
}
While editing your question I fixed indentation of your code which showed your problem clearly: you placed code responsible for printing result array in same loop which fills this array. In other words you are printing array after you add new row to it.
That is why you see results in form
[row1]
null
null
null
[row1]
[row2]
null
null
[row1]
[row2]
[row3]
null
[row1]
[row2]
[row3]
[row4]
To solve this problem simply place loop responsible for printing outside of loop responsible in generating content of result array (remember that indentation is not responsible for scoping but placement of { and } brackets is, so move one } from end before printing loop). So change your code to
char thelist[][] = new char[args.length][];
for (int i = 0; i < args.length; i++) {
thelist[i] = new char[args[i].length()];
for (int k = 0; k < args[i].length(); k++) {
char letter = args[i].charAt(args[i].length() - k - 1);
thelist[i][k] = letter;
}
}
for (char[] word : thelist) {
String list = Arrays.toString(word);
System.out.println(list);
}
Related
Lets say I have an ArrayList called dictArray that holds 5 words. The five words are listed as so {"aaron", "abates", "dog", "mellon", "zoo"}. I need to loop through this string ArrayList one word at a time, and for each word create a ArrayList<Character> tempArray to store only the unique characters within that word. (I only need to go one word at a time because I will be performing calculations on the tempArray within the for loop). For example, each iteration would return the following:
{a,r,o,n}
{a,b,t,e,s}
{d,o,g}
{m,e,l,o,n}
{z,o}
This block of code will successfully store only the unique characters of the subject word:
if(tempArray.contains(word.charAt(i))){
} else {
tempArray.add(word.charAt(i));
}
}
My question: How do I set up the for loop structure to go one word at time, and then after identifying the word, go one letter at a time to call the above if statement? Here is my current code but I am receiving the error message type of expression must be an array type but resolved to ArrayList<String> underneath all of the j's.
ArrayList<String> dictArray = new ArrayList<String>();
ArrayList<Character> tempArray = new ArrayList<Character>();
for (int i = 0; i < dictArray.size(); i++) {
for (j = 0; j < dictArray[j]; j++) {
if(tempArray.contains(word.charAt(i))){
} else {
tempArray.add(word.charAt(i));
}
}
}
This is your code with a better format, and I will go down line by line.
ArrayList<String> dictArray = new ArrayList<String>();
ArrayList<Character> tempArray = new ArrayList<Character>();
for (int i = 0; i < dictArray.size(); i++) {
for (j = 0; j < dictArray[j]; j++) {
if(tempArray.contains(word.charAt(i))){
} else {
tempArray.add(word.charAt(i));
}
}
}
Line 4: for (j = 0; j < dictArray[j]; j++) {, if you want to access an element in the ArrayList, use get(int index). Also, you should use dictArray.get(i) instead of j (which you did not initialize). i is the index of String in the ArrayList, while j should be the index of characters in the String.
Line 5 - 8: can be combined together. You want to add the character if it is not in the tempArray so you don't need to use an if-else statement. Also, you never initialized word, which I think you meant dictArray.get(i)
Last I think you want to add the tempArray to a new ArrayList (call it answer) of Array of Strings which contains the unique characters for each word.
So here is the modified code
ArrayList<ArrayList<Character>> answer = new ArrayList<>();
for (int i = 0; i < dictArray.size(); i++) {
ArrayList<Character> tempArray = new ArrayList<Character>();
for (int j = 0; j < dictArray.get(i).length(); j++) {
if(!tempArray.contains(dictArray.get(i).charAt(j))){
tempArray.add(dictArray.get(i).charAt(j));
}
}
answer.add(tempArray);
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> dictArray = Arrays.asList("aaron", "abates", "dog", "mellon", "zoo");
List<List<Character>> result = new ArrayList<>();
dictArray.stream().
forEach(word -> {
List<Character> charArray = new ArrayList<>();
for (Character c : word.toCharArray()) {
if (!charArray.contains(c)) {
charArray.add(c);
}
}
result.add(charArray);
});
System.out.println(result);
}
}
output :
[[a, r, o, n], [a, b, t, e, s], [d, o, g], [m, e, l, o, n], [z, o]]
you can use a for each to loop through the list and break the individuals down to char arrays and then loop through those
for (String s : arr ) {
char[] cArray = s.toCharArray();
for (char cs : cArray) {
// Your Logic Here
}
}
ArrayLists need the get() method to extract a particular value. It might also be helpful to learn about the foreach lop, given here by for(char c: tempArray). Basically, it means for every character given a variable name c in the list tempArray
for(int i = 0; i < dictArray.size(); i++)
{
ArrayList<Character> tempArray = new ArrayList<Character>();
String val = dictArray.get(i);
for(int j = 0; j < val.length(); j++)
{
if(!tempArray.contains(val.charAt(j)))
{
tempArray.add(val.charAt(j));
}
}
String word = "";
for(char c: tempArray)
{
word += c;
}
dictArray.add(word);
}
This approach converts tempArray to a String word and stores it in dictArray
I have this array.
char [] cornStrand = {'G','G','A','G','T','T','C','C','C','A'};
I also have this array, for which the values are inputted by the user running the program.
char [] bacteriaStrand = new char [5];
String strBases = scan.nextLine();
for (int s=0; s <bacteriaStrand.length; s++)
{
char c = strBases.charAt(s);
bacteriaStrand[s]= c ;
}
The second block of code essentially inputs the values that the user entered into the bacteria strand array.
Now comes the tricky part. I need to "splice" and combine both arrays. By this I mean:
If the first character of
char [] bacteriaStrand
is A, then I have to insert
char [] bacteriaStrand
After the first G in
char [] cornStrand
Now, after I splice this, I have to put what I spliced into a new array, called
char [] combinedStrand
This is where I am becoming confused. If anyone can help, please do so! I would gladly appreciate it!
Maybe do something like this:
public char[] combine(char[] bacteriaStrand, char[] cornStrand) {
char[] result = new char[bacteriaStrand.length + cornStrand.length];
if (bacteriaStrand[0] == 'A') {
for (int i = 0; i < cornStrand.length; i++) {
boolean insertedBacteria = false;
if (cornStrand[i] == 'G') {
insertedBacteria = true;
for (int j = 0; j < bacteriaStrand.length; j++) {
result[i + 1 + j] = bacteriaStrand[j];
}
if (insertedBacteria)
i += bacteriaStrand.length;
result[i] = cornStrand[i];
}
}
}
return result;
}
If that is the only rule, it seems pretty simple to do.
if (bacteriaStrand[0] == 'A') {
int totalLength = cornStrand.length + bacteriaStrand.length;
char [] combinedStrand = new char [totalLength];
for(int i=0; i<cornStrand.length; i++){
combinedStrand[i] = cornStrand[i]; //fill in corn until you find the first G
if (cornStrand[i] == 'G') {
int j = 0;
for(; j<bacteriaStrand.length; j++){
combinedStrand[i+j+1] = bacteriaStrand[j]; //fill in bacteria
}
i++;
for(;i<cornStrand.length;i++){
combinedStrand[i+j+1] = cornStrand[i] //fill in the rest of corn
}
}
}//now this loop will break, since you increased i, so you won't get duplicates
}
I want to take two strings and alternate the characters into a new string using a for method.
Example: "two" and "one"
Result: "townoe"
This is what I have so far, and I really don't know how to finish it.
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < a.length(); i++) {
s += i;
System.out.println(s);
}
return null;
}
}
public class Alternator{
public static String alternate(String a, String b){
String s = "";
int i = 0;
while (i < a.length() && i < b.length()){
s += a.charAt(i) +""+ b.charAt(i);
i++;
}
while (i < a.length() ){
s += a.charAt(i);
i++;
}
while (i < b.length()){
s += b.charAt(i);
i++;
}
return s;
}
public static void main(String[] args){
String a = "two", b = "one";
String s = Alternator.alternate(a,b);
System.out.println(s);
}
}
To use for loop instead of while loop, simply remove all while lines with for lines like the following, then remove the i++ line from each while loop
for(; i < a.length() && i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < a.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
Here is some compact way of doing that:
String alternate(String a, String b) {
StringBuilder builder = new StringBuilder();
int smallerStringLength = Math.min(a.length(), b.length());
for (int i = 0; i < smallerStringLength; i++) {
builder.append(a.charAt(i));
builder.append(b.charAt(i));
}
return builder.toString();
}
Or even more optimized:
String alternate(String first, String second) {
char[] firstChars = first.toCharArray();
char[] secondChars = second.toCharArray();
int smallerCharsCount = Math.min(firstChars.length, secondChars.length);
StringBuilder builder = new StringBuilder(smallerCharsCount * 2);
for (int i = 0; i < smallerCharsCount; i++) {
builder.append(firstChars[i]);
builder.append(secondChars[i]);
}
return builder.toString();
}
This will work if string are of same length or of the different lengths.
static void mergeStrings(String a, String b) {
StringBuilder mergedBuilder = new StringBuilder();
char[] aCharArr = a.toCharArray();
char[] bCharArr = b.toCharArray();
int minLength = aCharArr.length >= bCharArr.length ? bCharArr.length : aCharArr.length;
for (int i=0; i<minLength; i++) {
mergedBuilder.append(aCharArr[i]).append(bCharArr[i]);
}
if(minLength < aCharArr.length) {
mergedBuilder.append(a.substring(minLength));
}
else{
mergedBuilder.append(b.substring(minLength));
}
Systemout.println(mergedBuilder.toString());
}
Assuming that the two strings are the exact same length, you can do the following. If they are different length, then currently your prompt doesn't say how you want the resultant string to be set up.
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < 2*a.length(); i++) {
if (i%2==0) // modular arithmetic to alternate
s += a.charAt(i/2); // Note the integer division
else
s += b.charAt(i/2);
}
System.out.println(s);
return s;
}
}
Alternatively, even easier, but the index i doesn't mark the length of your string s:
public class Alternator {
String alternate(String a, String b) {
String s = "";
for(int i = 0; i < a.length(); i++){
s += a.charAt(i);
s += b.charAt(i);
}
return s;
}
}
Use this:
String alternate(String a, String b){
StringBuilder builder = new StringBuilder();
final int greaterLength = a.length() > b.length() ? a.length() : b.length();
for(int i = 0; i < greaterLength; i++){
if (i < a.length()) {
builder.append(a.charAt(i));
}
if (i < b.length()) {
builder.append(b.charAt(i));
}
}
return builder.toString();
}
It uses the String.charAt method to obtain letters, and a StringBuilder to create the string.
(When given two strings of non-equal length, this returns an alternation of the first two chars, and then does just the remaining string. EG: Hello and Hi --> HHeillo)
According to the comments I've read, you are having trouble understanding for loops, and how to use them with strings.
For loops are most often used to iterate over arrays, or to perform a task a given number of times.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
This would give the output
0
1
2
3
4
For loops start at the value of the initializer, the first thing you put in int i = 0;
They then check the expression, the second part of the for loop, and if it returns true, it executes all of the code inside the braces. i < 5;
Once it has done that, it runs the incrementor, the last part of the for loop. i++
After that, it checks the expression again. I guess you can see where this is going. Until the expression returns false, everything inside the curly braces of the for loop gets executed over and over again.
Strings can be iterated over with a for loop, but you can't reference it like an array using array[index]. You have to either convert it into an array, using .toCharArray() on your String, and return the result to an empty char array char[], or use the .charAt(index) method on your string.
This code will go over a string, and output each character, one by one:
for (int i = 0; i < myString.length(); i++) {
System.out.println(myString.charAt(i));
}
If the string had a value of "Hello", the output would be:
H
e
l
l
o
Using this, instead of outputting the characters using System.out.println();, we can put them into an empty string, using +=:
myOtherString += myString.charAt(i);
That means, if we want to go over two Strings at a time, and alternate them, like you do, we can iterate over two strings at the same time, and add them to a new string:
myAlternatedString += myString.charAt(i);
myAlternatedString += myOtherString.charAt(i);
if MyString was still "Hello" and myOtherString was "World", the new string would be:
Hweolrllod
following code reads 2 different inputs and merges into a single string.
public class PrintAlternnateCharacterString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.next();
String b = in.next();
String mergedString = "";
int lenA = a.length();
int lenB = b.length();
if (lenA >= lenB) {
for (int i = 0; i < lenA; i++) {
if (i < lenB) {
mergedString += a.charAt(i) + "" + b.charAt(i);
} else {
mergedString += a.charAt(i);
}
}
}
if (lenB > lenA) {
for (int i = 0; i < lenB; i++) {
if (i < lenA) {
mergedString += a.charAt(i) + "" + b.charAt(i);
} else {
mergedString += b.charAt(i);
}
}
}
System.out.println("the merged string is-->" + mergedString);
}
}
public static String stringConcate(String str1,String str2){
String str3="";
if(str1!=null && str2!=null && !str1.isEmpty() && !str2.isEmpty()){
if(str1.length()==str2.length()){
for(int i=0;i<=str1.length()-1;i++){
str3+=str1.charAt(i);
str3+=str2.charAt(i);
}
}
if(str1.length()>str2.length()){
for(int i=0;i<=str1.length()-1;i++){
str3+=str1.charAt(i);
if(i<str2.length()){
str3+=str2.charAt(i);
}
}
}
if(str2.length()>str1.length()){
for(int i=0;i<=str2.length()-1;i++){
if(i<str1.length()){
str3+=str1.charAt(i);
}
str3+=str2.charAt(i);
}
}
}
return str3;
}
String str1 = "one"; String str2 = "two";
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < str1.length() && i < str2.length(); i++) {
sb.append(str1.charAt(i)).append(str2.charAt(i));
}
for(; i < str1.length(); i++) {
sb.append(str1.charAt(i));
}
for(; i < str2.length(); i++) {
sb.append(str2.charAt(i));
}
System.out.println("result = " + sb.toString());// otnweo
This will handle for different length too
This could be donw with very simple if...else.
public static void main(String... args) {
int[] one = { 1, 2, 3 };
int[] two = { 44, 55, 66, 77, 88 };
System.out.println(Arrays.toString(alternate(one, two)));
}
public static int[] alternate(int[] one, int[] two) {
int[] res = new int[one.length + two.length];
for (int i = 0, j = 0, k = 0; i < res.length; i++) {
if (i % 2 == 0)
res[i] = j < one.length ? one[j++] : two[k++];
else
res[i] = k < two.length ? two[k++] : one[j++];
}
return res;
}
Output:
[1, 44, 2, 55, 3, 66, 77, 88]
I have a string and I want to convert it to a 2D array of integers. This is what I am doing:
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
//Putting each element into an array of strings
String stringArray[]=string1.split("~");
//Determining the number of columns for the 2D array
int countints=0;
Scanner ins = new Scanner(stringArray[0]);
while (ins.hasNext()){
countints+=1;
ins.next();
}
//converting into an array of integers
int intArray[][]=new int[stringArray.length][countints];
Here I'm stuck as how to parse each integer into the 2D array.
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String string2 = string1.replace("[","").replace("]","");
for(int i = 0; i < stringArray.length; i++)
{
String s = stringArray[i].substring(1, stringArray[i].length()-1);
String[] elementArray = s.split(",");
for(int j = 0; j < elementArray.length; j++)
{
int val = Integer.parseInt(elementArray[j]);
intArray[i][j] = val;
}
}
For a totally dynamic array:
String string1 = "[1,2,3]~[4,5,6]~[7,8,9]~";
String[] lines = string1.split("(^|~)\\[");
int[][] array = new int[lines.length][0];
Pattern pat = Pattern.compile("\\d+");
int lineIndex = 0;
for (String line : lines) {
//if the row size is dynamic
Matcher m1 = pat.matcher(line);
int rowSize = 0;
while (m1.find())
rowSize++;
array[lineIndex] = new int[rowSize];
int colIndex = 0;
Matcher m2 = pat.matcher(line);
while (m2.find()) {
array[lineIndex][colIndex++] = Integer.parseInt(m2.group());
}
lineIndex++;
}
for(int i=0; i<array.length;i++){
for(int j=0; j<array[i].length;j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
It prints:
1 2 3
4 5 6
7 8 9
Once you have initialized the 2D array, you need to parse each element in stringArray by getting rid of trailing and leading '[', ']' bracket pairs and splitting it with "," and parse each element of the split string into Integer and put that int value to the given 2d array at correct postion.
EDIT: WORKING SOLUTION
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String stringArray[]=string1.split("~");
int countints = stringArray[0].substring(1, stringArray[0].length()-1).split(",").length;
int intArray[][]=new int[stringArray.length][countints];
for(int i = 0; i < stringArray.length; i++)
{
String s = stringArray[i].substring(1, stringArray[i].length()-1);
String[] elementArray = s.split(",");
for(int j = 0; j < elementArray.length; j++)
{
int val = Integer.parseInt(elementArray[j]);
intArray[i][j] = val;
}
}
Here is a clean solution that works. I started working on it before I got through all of the other answers, so my apologies if it doesn't meaningfully add to what is already here:
public class SO {
public static int[][] parse(String input) {
String[] rows = input.split("~");
int[][] ints = new int[rows.length][];
int j = 0;
for(String row : rows) {
String[] cols = row.substring(1, row.length()-1).split(",");
int k = 0;
ints[j] = new int[cols.length];
for(String col : cols) {
ints[j][k++] = Integer.parseInt(col);
}
j++;
}
return ints;
}
public static void main(String[] args) {
for(int[] row : parse("[1,2,3]~[4,5,6]~[7,8,9]~")) {
for(int col : row) {
System.out.print(","+col);
}
System.out.println();
}
}
}
This produces the output:
,1,2,3
,4,5,6
,7,8,9
As for error checking you should decide upfront how you want to handle error checking, As this is written a single invalid int will throw an exception, which I think is the correct behavior. Malformed rows on the other hand might give unpredictable output (which I would say is wrong if the input has even the slightest potential to be malformed).
I'm working on a study problem from class and essentially it reads a string, and a character. The character is the delimiter. It will then search the string for the delimiter and create an array in equal length to the number of times the delimiter is found. It then assigns each character or string to its own spot in the array and returns it.
Maybe I am over thinking things, but the just of it is to not rely on the various string methods and to sort of create your own. How can I get this method to only assign the string/char found in the one that is read to one position in the array and not all as well as stop it from adding unnecessary output? Help/Suggestions greatly appreciated
public static String[] explode(String s, char d){
String []c;
int count = 1;
//checks to see how many times the delimter appears in the string and creates an array of corresponding size
for(int i = 0; i < s.length(); i++){
if(d == s.charAt(i))
count ++;
}
c = new String [count];
//used for checking to make sure the correct number of elements are found
System.out.println(c.length);
//goes through the the input string "s" and checks to see if the delimiter is found
//when it is found it makes c[j] equal to what is found
//once it has cycled through the length of "s" and filled each element for c, it returns the array
for(int i = 0; i < s.length(); i++){
for(int j = 0; j < c.length; j++){
if(d == s.charAt(i))
c[j] += s.substring(i-1);
}
}
//provides output for the array [c] just to verify what was found
for(int y = 0; y < c.length; y++)
System.out.println(c[y]);
return c;
}
public static void main(String [] args){
String test = "a,b,c,d";
char key = ',';
explode(test,key);
}
^The following will output:
4
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
nulla,b,c,db,c,dc,d
I'm aiming for:
4
a
b
c
d
Thank you
Perhaps you could try something like this:
public static void main(String[] args){
explode("a,b,c,d", ',');
}
public static void explode(final String string, final char delimiter){
int length = 1;
for(final char c : string.toCharArray())
if(delimiter == c)
length++;
if(length == 1)
return;
final String[] array = new String[length];
int index, prev = 0, i = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
array[i++] = string.substring(prev, index);
prev = index+1;
}
array[i] = string.substring(prev);
System.out.println(length);
for(final String s : array)
System.out.println(s);
}
Output of the program above is:
4
a
b
c
d
Or if you want to utilize a List<String> instead (and Java 8), you could remove a couple of lines by doing something like this:
public static void explode(final String string, final char delimiter){
final List<String> list = new LinkedList<>();
int index, prev = 0;
while((index = string.indexOf(delimiter, prev)) > -1){
list.add(string.substring(prev, index));
prev = index+1;
}
list.add(string.substring(prev));
System.out.println(list.size());
list.forEach(System.out::println);
}