I am trying to recreate the Thue Morse sequence in Java console and need to bring the contents of a 1 dimensional array into a 2 dimensional one. I tried using 2 for loops, with one nested, but receive the Ljava.lang.String;#42d3bd8b as a result
int x = Integer.parseInt(args[0]);
String[][] array = new String [x][x];
String thue = "0";
String morse = "1";
//
for (int i = 1; i <= array.length; i++) {
String t = thue; // save away values
String m = morse;
thue += m;
morse += t;
}
String[] split = (thue.split("(?!^)"));
for (var y = 0; y<split.length; y++){
if (split[y] == "0"){
split[y] = "+";
}
else split[y] = "-";
}
int index = 0;
for (var i = 0; i < array.length; i++){
for (var j = 0; j < array[i].length;j++){
array[i][j] = (split[index]);
index++;
}
}
System.out.println(Arrays.toString(array));
}
}
There are 2 corrections to be made
1)in this code
if (split[y] == "0"){
split[y] = "+";
}
Strings cannot be compared as primitives. Replace equals operator with equals method as such
if (split[y].equals("0")){
split[y] = "+";
}
2)Arrays toString method can be used to convert only 1D arrays to string format.
You have to use the deepToString for your purpose
System.out.println(Arrays.deepToString(array));
I found out how to fix it, I converted array into a integer array and then later on when setting split[index] equal to the indicies of array, I just added and Intger.parseInt around the split[index]
Related
I have one text file in which each String holds one line of numbers say 203 and I have one 2d array int puzzle[][].
The lines of file are in the array list Arraylist<String> lines .The first String from the array list goes into puzzle[0].The second String goes into puzzle[1], etc.
The problem I'm having is that after splitting the lines I cannot convert those numbers into integers because it gives me number format exception for -1 what if I will split that - and 1 as well.
I tried the following and also making deep copy of the string array and then transforming each string into an integer
public void parseFile(ArrayList<String> lines)
{
ArrayList<String> l = lines;
for(int i =0; i<puzzle.length; i++)
puzzle[i][0] = Integer.parseInt(l.get(i).split(""));
}
it should give me 2d array with integers
Here is a method that will take a list of strings made up of single digit numbers and convert the list to a 2d array of int. This code makes no use of Java 8 streams.
public static int[][] parseFile(List<String> lines) {
int[][] result = new int[lines.size()][];
int multiplier = 1;
int counter = 0;
for (String line : lines) {
List<Integer> row = new ArrayList<>();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '-') {
multiplier = -1;
continue;
}
int n = (int)c - 48;
row.add(n * multiplier);
multiplier = 1;
}
int[] rowArray = new int[row.size()];
for (int j = 0; j < row.size(); j++) {
rowArray[j] = row.get(j);
}
result[counter] = rowArray;
counter++;
}
return result;
}
Below is my test code, execute from main
List<String> list = new ArrayList<>();
list.add("-111");
list.add("2-13");
int[][] result = parseFile(list);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.printf("%d ", result[i][j]);
}
System.out.print("\n");
}
Output
-1 1 1
2 -1 3
I want to sort on a calculation result, where there is a String and value, sorting process succeeds, but there is a problem with the string. string does not follow the values that have been in the previous sorting. how to handle it ? getNamaDosen () as String, nilaiDosen as value and getJumlahBakcal() as the amount of data.
Code program :
Object[][] data2 = new Object[getJumlahBakcal()][2];
Double [] nilaiDosen = new Double[getJumlahBakcal()];
for(int a=0; a<nilaiDosen.length; a++){
for(int b=0; b<nilaiDosen.length-1; b++){
if(nilaiDosen[b]<nilaiDosen[b+1]){
double temp = nilaiDosen[b];
nilaiDosen[b] =nilaiDosen[b+1];
nilaiDosen[b+1] = temp;
}
for (int i = 0; i < getJumlahBakcal(); i++) {
for (int j = 0; j < 3; j++) {
if (j == 0) {
data2[i][j] = getNamaDosen()[i];
} else if (j == 1) {
data2[i][j] = (nilaiDosen[i]);
}
}
}
}
}
String[] header = {"Nama Dosen", "Prefensi"};
DefaultTableModel dtm = new DefaultTableModel(data2, header);
analisaVW.getRank().setModel(dtm);
Picture illustration :
string does not follow the values that have been in the previous sorting
Because, you are only swapping values. So, you want to follow String value as well. Then, you are supposed to swap String at the same time.
I assume, this is where you are swapping values
if(nilaiDosen[b]<nilaiDosen[b+1]){
double temp = nilaiDosen[b];
nilaiDosen[b] =nilaiDosen[b+1];
nilaiDosen[b+1] = temp;
// include code here to swap Sting value using same index
}
Now, while swapping value, you should also swap the String value.
I am completely new to programming. Can you give me some tips on how to improve my code?
The problem was:
Given an array of strings, return a new array without the strings that are equal to the target string. One approach is to count the occurrences of the target string, make a new array of the correct length, and then copy over the correct strings.
And my code:
public String[] wordsWithout(String[] words, String target) {
int numberOfTargets = 0;
for (int i = 0; i < words.length; i++){
if ( words[i].equals(target) ) numberOfTargets++;
}
String[] result = new String[words.length - numberOfTargets];
for (int i = 0; i < words.length - numberOfTargets; i++){ // 1
result[i] = "0"; // 1
} // 1
for (int i = 0; i < words.length; i++){
if ( !words[i].equals(target) ){
int j = 0; // 2
while ( !result[j].equals("0") ){ // 2
j++; // 2
} // 2
result[j] = words[i];
}
}
return result;
}
Example of how code works:
wordsWithout(["aa", "ab", "ac", "aa"], "aa") → ["ab", "ac"]
I know that new array of ints is filled by zeros dy default. What about new array of Strings? I had to artificially fill it by zeros in part marked as //1, so that I could "scroll" to the right element, when I have to add elements to my new array in part marked as //2.
My code seems to be kind of awkward. Are there any standard methods or general ways to improve my code?
You don't need to set each element to "0".
Just do this:
public static String[] wordsWithout(String[] words, String target) {
int numberOfTargets = 0;
for (int i = 0; i < words.length; i++){
if ( words[i].equals(target) ) numberOfTargets++;
}
String[] result = new String[words.length - numberOfTargets];
int j =0; // for indices of result
for (int i = 0; i < words.length; i++){
if (!words[i].equals(target) ){
result[j++] = words[i];
}
}
return result;
}
Looks like your code could be simplified a lot by just using an ArrayList.
public String[] wordsWithout(String[] words, String target)
{
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < words.length; ++i)
{
if(!words[i].equals(target))
{
list.add(words[i]);
}
}
return list.toArray(new String[0]);
}
Basically instead of calculating the size of the target array and initialising it, you use a list (which is variable in size), put in all the elements you need, and then create a new array from it.
Unrelated to that, please don't invent your own values ("0") to describe a null value - there's a dedicated keyword, null, for that.
Use
for (String s : words) {
if (s.equals(target))
numberOfTargets++;
}
This might be a bit simpler. Using the split string method allows you to create an array with each value separated by white space.
public String[] wordsWithout(String[] words, String target) {
String newStr = "";
for (int i = 0; i < words.length; i++){
if (words[i].equals(target))
continue;
newStr = newStr + words[i] +" ";
}
return newStr.split(" ");
}
My output should look like:
1 star(*)
3 stars(***)
4 stars(****)
For example i have code:
char array[] = new char[3];
char x = '*';
For (int i= 0; i < array.length; i++)
{
array[i]='*'
x = x+2;
system.out.println(array[i]);
}
No it's not possible in char[] array, you should do it like,
String array[] = new String[3];
String x = "*";
for (int i= 0; i < array.length; i++)
{
array[i] = "";
array[i] = array[i] + x;
system.out.println(array[i]);
x = x + "*";
}
This will print the output as,
*
**
***
Your array is a char array, so each element contains a single char. Therefore your output will be :
*
*
*
To get the output you want, you'll need a String array (or no array at all - you can used a nested loop instead).
In addition, x = x+2; doesn't do what you think it does. It assigns a new character to x. If the initial value of x is '*', it will change it to the char whose numeric value is higher by two compared to the numeric value of '*'.
Just to provide an alternative to the already existing answers, it is also possible to just work with char. The trick then is to use System.out.print() rather than System.out.println(). An example:
int n = 3; //the number of lines you want to print
char x = '*';
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(x);
}
System.out.print("\n");
}
Note: this is just an alternative to the already proposed solutions
For that you need to change array to String type and concat * on it in each level.
Code
String array[] = new String[3];
char x = '*';
array[0]=""+x;
for (int i= 0; i < array.length; i++)
{
System.out.println(array[i]);
if(i!=array.length-1)
array[i+1]='*'+array[i];
}
And you also have so much compilation error in your code like For,Array,system.
Also check DEMO
Considering your out put it can be derived from following
String s="*";
StringBuffer sb =new StringBuffer();
for(int i=1;i<=4;i++)
{
System.out.println(sb.append(s));
}
Output will be
*
**
Tc
I have to write a method in java, where having in input an array "a" of numbers and a number "x" returns an array of elements which follows the last occorence of "x " in "a". For example
with input {0,1,2,3,4,5,6,7,8,9} and x=6 the method must return {7,8,9} meanwhile with {4,1,4,2} and x =4 the method must return {2} and if the x is not in "a" then it must return empty array {} (or array with 0 length)
so far we haven't study classes or objects .here an example of another program we made so far
boolean arrayIncluso( int[] s,int[] t ) {
boolean flag=true;
for(int i=0;i< s.length;i++){
int c1 = 0 ;
int c2 = 0 ;
for(int j=0;j< s.length;j++){
if(s[i] == s[j]){
c1 ++;
}
}
for(int j=0;j< t.length;j++){
if(s[i] == t[j]){
c2 ++;
}
}
if(c1 > c2)
flag= false;
}
return flag;
}
can someone explain to me
why this
t[i-idx-1 ] = s[i];
instead of this
for(int j=0;j<t.length;j++){
t[j]=a[i];
}
return t;
You can split the problem into two parts:
Find last index of the character x. This can be done using an easy for loop.
int idx = -1;
for (int i = 0; i < s.length; i++) {
if (s[i] == x) idx = i;
}
After you found this index, create a new array starting from this element. It can be done with a second (not nested) for loop, or you can use Arrays.copyOfRange()
//make sure idx != -1
int[] t = new int[s.length - idx - 1];
for (int i = idx+1; i < s.length; i++)
t[i-idx-1 ] = s[i];
System.out.println(Arrays.toString(t)); //print to make sure it's all fine
OR
t = Arrays.copyOfRange(s, idx+1, s.length);
System.out.println(Arrays.toString(t));
Here's a general algorithm: (you have to code it yourself)
Run through the array a keeping track of the current index of the number x. Call this index e.g.lastOccurance.
Return the array from lastOccurance + 1 and onwards.
Don't forget checks for no occurances and if the last occurance is end of array.
Using lists:
int pos = a.lastIndexOf(x);
List<Integer> result = null;
if(pos > -1)
result = a.subList(pos+1, a.size());
You can build your the list from an arra y using Arrays:
Integer [] array = new Integer[3];
...
...
List<Integer> a = Arrays.asList(array);
Alltogether would result in a code like:
List<Integer> a = Arrays.asList(array);
int pos = a.lastIndexOf(x);
int [] result = null;
if(pos > -1) {
List<Integer> sl = a.subList(pos+1, a.size());
result = new int[sl.size()];
for(int i = 0; i < sl.size(); i++)
result[i] = sl.get(i);
}
You can use commons lang library in order to determine the last index of an array element with method ArrayUtils.lastIndexOf, that way it turns to be a one-liner:
int[] t = Arrays.copyOfRange(s, ArrayUtils.lastIndexOf(s, x) + 1, s.length);