java,arrays,for-loop,random , How to fill array with random values 1-110


How to fill array with random values 1-110

Question:

Tag: java,arrays,for-loop,random

I want to fill tab[110] array with random bits (so 1 and 0). Don't know how to fill with values 1-110, but not 0-109. My for-loop:

for (int i = 0; i<tab.length; i++)
            {

                Random r = new Random();
                tab[i] = r.nextInt(2);
                if (i%25==0)
                {
                    System.out.println("");
                }
                System.out.print(tab[i]+"("+i+")"+", ");

            }

I know that usually it's simple, just tab[i]=i+1;, but when i put a random number into array it doesn't work for me. I tried to add "+1" everywhere in this loop and only effect i got is when i added it to System.out.println - but then i got fake output that it's 1-110, when in array it's still 0-109.

whole code:

package teleinformatykalab2;

import java.util.Random;

public class TeleinformatykaLab2 {

    public static void losujBity(int tab[])  // Funkcja losuje ciag 110 bitow i umieszcza je w utworzonej tabeli
    {
        System.out.println("Ciag 110 bitow: ");

        for (int i = 0; i<tab.length; i++)
        {

            Random r = new Random();
            tab[i] = r.nextInt(2);
            if (i%25==0)
            {
                System.out.println("");
            }
            System.out.print(tab[i]+"("+i+")"+", ");

        }
        System.out.println("\n");
    }

    private static boolean isPowerOfTwo(int x)  // Funkcja zwraca liczby, ktore sa kolejna potega liczby 2
    {
        //return (x & (x-1)) ==0;                
        return (x!=0) && ((x&(x-1)) ==0);
    }

    public static void wyswietlBityPowerOfTwo(int tab[])
    {
        boolean [] bityPotegiDwa = new boolean[7];
        System.out.println("Bity, ktorych indeks w tablicy jest kolejna potega liczby 2: ");
        for (int i=0; i<tab.length; i++)
        {

            if (isPowerOfTwo(i))
                {
                 int j = 0;
                 bityPotegiDwa[j+1] = isPowerOfTwo(i);
                 j++;
                 System.out.print(tab[i]+"("+i+")"+", ");

                }
        }
        System.out.println("\n");
    }

    public static void podzielCiagNaParzysteGrupy(int tab[]) // Funkcja dzieli ciag bitow na 7 grup wg indeksow potegi 2
    {
        int [] gr1 = new int [56];


    }

    public static void main(String[] args) {

        int [] tab = new int [110]; // Utworzenie tablicy jako globalnej zmiennej
        losujBity(tab);

        wyswietlBityPowerOfTwo(tab);
        podzielCiagNaParzysteGrupy(tab);


    }

}

[edit] Is this proper method? Make tab[111] and then fill it from i=1 to i<=110?

for (int i = 1; i<=110; i++)
        {

            Random r = new Random();

            tab[i] = r.nextInt(2);
            if (i%25==0)
            {
                System.out.println("");
            }
            System.out.print(tab[i]+"("+i+")"+", ");

        }

But then what about tab[0]? Is there null?

[edit2] My previous version of trying to implement a Hamming code was:

package teleinformatykalab2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


public class TeleinformatykaLab2 {

    //Funkcja wypelniajaca tablice ciagiem losowych bitów 0 lub 1 //

    static boolean[] bity;

    public static void Losowanie(int tab[]){

        ////int [] tab = new int[110];

        for (int i = 0; i<110; i++)
        {
            Random r = new Random();
            tab[i] = r.nextInt(2);
            if (i%25==0)
            {
                System.out.println("");
            }
            System.out.print(tab[i]+"("+i+")"+", ");

        }
        System.out.println("");

}
    /////////////////


    //Funkcja wywietla bity, których indeks w tablicy jest wartoci¹ kolejnej potêgi liczby dwa//
    public static void zamienBity(int tab[], int tabBit[])
    {
        ////System.out.println("\n"+tab[0]+tab[109]+"\n");
        //int [] power = new int [7];
        bity = new boolean[7];
        for (int i=0; i<110; i++)
        {

            if (isPowerOfTwo(i))
                {
                 int j = 0;
                 bity[j] = isPowerOfTwo(i);
                 j++;
                 System.out.print(tab[i]+"("+i+")"+", ");

                }
            if (i%50==0)
            {
                System.out.println("");
            }

        }

        System.out.println("\n");

    }

    //Sprawdzenie ci¹gu kodem Hamminga//
    public static void sprawdzHamming(int tab[], int tabBit[])
    {
        // przypisanie do tabBit bitow o indeksie potêgi dwa
        int [] power = new int [7];
        for(int i=0;i<tabBit.length;i++)
        {
            tabBit[i] = tab[(int)Math.pow(2,i)];
            System.out.print(tabBit[i]+", ");
        }
        System.out.println("////\n");

        //sprawdzenie pierwszej pary bitów
        System.out.println("\nPierwsza para");

        int [] skip = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,36,39,41,43,45,47,49,
                        51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,
                        101,103,105,107,109};    
        for (int i : skip)
        {
             System.out.print(tab[i] + "("+i+")"+",");

                if (i%25==0)
                {
                    System.out.println("");
                }
        }
        System.out.println("");

        //sprawdzenie drugiej pary bitów
        System.out.println("\nDruga para");

         int skip2 []= {3,6,7,10,11,14,15,18,19,22,23,26,27,30,31,34,35,38,39,42,43,46,47,
                        50,51,54,55,58,59,62,63,66,67,70,71,74,75,78,79,82,83,86,87,90,91,94,95,98,99,102,103,106,107};
          for (int j : skip2)
          {
          System.out.print(tab[j] + "("+j+")"+",");
          if (j%25==0)
                {
                    System.out.println("");
                }
          }
        System.out.println();

        //sprawdzenie trzeciej pary bitów
        System.out.println("\nTrzecia para");

         int skip3 []= {5,6,7, 12,13,14,15, 20,21,22,23, 28,29,30,31, 36,37,38,39, 44,45,46,47,
                        52,53,54,55, 60,61,62,63, 68,69,70,71, 76,77,78,79, 84,85,86,87, 92,93,94,95, 100,101,102,103, 108,109};
          for (int k : skip3)
          {
          System.out.print(tab[k] + "("+k+")"+",");
          if (k%18==0)
                {
                    System.out.println("");
                }
          }
        System.out.println();

         //sprawdzenie czwartej pary bitów
        System.out.println("\nCzwarta para");

         int skip4 []= {9,10,11,12,13,14,15,16, 25,26,27,28,29,30,31,32, 41,42,43,44,45,46,47,48,
                       57,58,59,60,61,62,63,64, 73,74,75,76,77,78,79,80, 89,90,91,92,93,94,95,96,
                       105,106,107,108,109};
          for (int l : skip4)
          {
          System.out.print(tab[l] + "("+l+")"+",");
          if (l%8==0)
                {
                    System.out.println("");
                }
          }
        System.out.println();

        //sprawdzenie pi¹tej pary bitów
        System.out.println("\nPi¹ta para");

        for (int m=17; m<110; m++)
        {
            if ((m>=32 && m<=47) && (m>=64 && m<=79) && (m>=96 && m<=111)) continue;
            System.out.print(tab[m] + "("+m+")"+",");
            if (m%16==0)
                {
                    System.out.println("");
                }
        }
        System.out.println();

        //sprawdzenie szótej pary bitów
        System.out.println("\nSzóta para");

        for (int m=33; m<110; m++)
        {
            if (m>=65 && m<=96)/* && (m>=64 && m<=79) && (m>=96 && m<=111))*/ continue;
            System.out.print(tab[m] + "("+m+")"+",");
            if (m%16==0)
                {
                    System.out.println("");
                }
        }
        System.out.println();

        //sprawdzenie siódmej pary bitów
        System.out.println("\nSiódma para");

        int [] sixtyfour = new int [120];

        for (int m=65; m<110; m++)
        {
            //if (m>=65 && m<=96)/* && (m>=64 && m<=79) && (m>=96 && m<=111))*/ continue;
            System.out.print(tab[m] + "("+m+")"+",");
            if (m%16==0)
                {
                    System.out.println("");
                }
        }
        System.out.println("\n");




    ////Tablica liczników par bitów//
        int [] counter = new int [7];

    ////Tablica wywietlanych b³êdów//
        Boolean [] error = new Boolean [7];

        Boolean [] errors = new Boolean [7];
  //////////Liczniki bitów jedynkowych////        
        int licznik1=0;
        for (int a=1; a<110;a++)
        {
            if (tab[a]==1)
                licznik1++;
        }
        int l1;
        String spr;
        if (licznik1%2==1) l1=1; else l1=0;
        if (l1==tabBit[0]) {
            error [0] = true;
            errors[0] = true;
        }//spr="ok";
        else {
            error [0]=false;
            errors[0] = false;
        }
        counter [0] = l1;

        System.out.println("W grupie 1: "+licznik1+"("+tabBit[0]+")" + " >"+counter[0]+" "+error[0]);



        int licznik2=0;
        for (int b=3; b<108;b++)
        {
            if (tab[b]==1)
                licznik2++;
        }
        int l2;
        if (licznik2%2==1) l2=1; else l2=0;
        if (l2==tabBit[1]) {
            error [1]=true;
            errors [1]=true;
        }
        else {
            error [1]=false;
            errors [1] = false;
        }
        counter [1] = l2;
        System.out.println("W grupie 2: "+licznik2 +"("+tabBit[1]+")"+" >"+counter [1]+" "+error[1]);


        int licznik3=0;
        for (int c=5; c<109;c++)
        {
            if (tab[c]==1)
                licznik3++;
        }
        int l3;

        if (licznik3%2==1) l3=1; else l3=0;
        if (l3==tabBit[2]) {
            error[2]=true;
            errors [2] = true;
        }
        else {
            error[2]=false;
            errors [2] = false;
        }
        counter [2] = l3;
        System.out.println("W grupie 3: "+licznik3 +"("+tabBit[2]+")"+ " >"+counter[2]+" "+error[2]);


        int licznik4=0;
        for (int d=9; d<109;d++)
        {
            if (tab[d]==1)
                licznik4++;
        }
        int l4;

        if (licznik4%2==1) l4=1; else l4=0;
        if (l4==tabBit[3]) {
            error[3]=true;
            errors [3]=true;
        }
        else {
            error[3]=false;
            errors[3]=false;
        }
        counter[3]=l4;
        System.out.println("W grupie 4: "+licznik4 +"("+tabBit[3]+")"+ " >"+counter[3]+" "+error[3]);
        //if (l4==tabBit[3]) System.out.print(" ok");

        int licznik5=0;
        for (int e=17; e<110;e++)
        {
            if (tab[e]==1)
                licznik5++;
        }
        int l5;

        if (licznik5%2==1) l5=1; else l5=0;
        if (l5==tabBit[4]) {
            error[4]=true;
            errors [4]=true;
        }
        else {
            error[4]=false;
            errors [4]=false;
        }
        counter[4] = l5;
        System.out.println("W grupie 5: "+licznik5 + "("+tabBit[4]+")"+" >"+counter[4]+" "+error[4]);


        int licznik6=0;
        for (int f=33; f<110;f++)
        {
            if (tab[f]==1)
                licznik6++;
        }
        int l6;

        if (licznik6%2==1) l6=1; else l6=0;
        if (l6==tabBit[5]) {
            error[5]=true;
            errors[5]=true;
        }
        else {
            error[5]=false;
            errors[5]=false;
        }
        counter [5] = l6;
        System.out.println("W grupie 6: "+licznik6+"("+tabBit[5]+")"+" >"+counter[5]+" "+error[5]);


        int licznik7=0;
        for (int g=65;g<110; g++)
        {
            if (tab[g]==1)
                licznik7++;
        }
        int l7;

        if (licznik7%2==1) l7=1; else l7=0;
        if (l7==tabBit[6]) {
            error[6]=true;
            errors[6]=true;
        }
        else {
            error[6]=false;
            errors[6]=false;
        }
        counter [6] = l7;
        System.out.println("W grupie 7: "+licznik7+"("+tabBit[6]+")"+" >"+counter [6]+" "+error[6]);

        //Tablica boolean ok lub b³¹d//
        ArrayList<Boolean> true_or_false = new ArrayList<>();
        for (Boolean tof : true_or_false)
        {
            int i=0;
            i++;
            true_or_false.add(error[i]);
            System.out.print(tof+",");

        }

        /*//Dwuwymiarowa tablica bitów i poprawnoci
        int [][] bit_check = new int [7][7];
        int [] myInt = new int [7];
        for (int i=0,j=0; i<7; i++, j++)
        {
            if (i==0) System.out.println("dwuwymiarowa tablica");
            if (errors[i]==false)
            {
                myInt[i]= (errors[i]) ? 1 : 0;
                bit_check[i]=counter;
                bit_check[j]=myInt;
                  System.out.print(bit_check[i][j]+",");
            }
        }*/

        ////sumowanie par, które sa blêdne////
        ArrayList<Integer> error_sum = new ArrayList<>();
        System.out.println("\n"); 


        for (int i=0, j=0; i<7; i++)
        {
            if (error[i]==false)

            {
                //System.out.println(counter[i]+" "+error[i]);

                error_sum.add(counter[i]);
                    System.out.println(counter[i]+", ");

            }

                //System.out.print("//"+power[j]+", ");
                //System.out.println("Bity zacne: " + bity[i]);
        }
        System.out.println("\n");
        for (Integer num : error_sum)
        {
            System.out.print(num+", ");
        }
               //System.out.println("\n"+error_sum[0]+","+error_sum[1]+","+error_sum[2]+","+error_sum[3]+","+error_sum[4]+","+error_sum[5]+","+error_sum[6]);
         System.out.println("\n");

       ////Sumowanie indeksów b³êdnych bitów//
         ArrayList<Integer> error_sum_pair = new ArrayList<>();

         /*for (Integer num : error_sum_pair)
         {
             do{
                 System.out.print();
             }
             if (true_or_false==false)
         }*/
     ////Wskazanie blednego bitu, przez sumowanie blednych par bitow//
         int suma=0;
         int [] grupa = new int [7];
         grupa[0] = 1;
         grupa[1] = 2;
         grupa[2] = 4;
         grupa[3] = 8;
         grupa[4] = 16;
         grupa[5] = 32;
         grupa[6] = 64;

    for (int i=0; i<7; i++)
    {        
        if (i==0) System.out.print("Numery blednych bitow w grupach: ");
        if (error[i]==false) 
        {
            System.out.print(grupa[i]+", ");
            suma+=grupa[i];
        }

            if (i==6) System.out.println("\nIndeks blednego bitu w ciagu: "+suma);
    }     

    int wskOfIndex;
    for (int i=0, j=0; i<110; i++)
    {
        if (j>6) break;
        if (i==grupa[j]) System.out.println("Bledny bit we wskazanym "+suma+" indeksie: "+tab[i]);
        /*wskOfIndex=Arrays.asList(tab).indexOf(grupa[i]);
        if (i==109) System.out.println(wskOfIndex);*/
    }

    /*////Podmiana blednego bity na prawidlowy//
    for (int i=0; i<110; i++)
    {
        if (i==suma)
            {
             if (tab[i]==0) tab[i]=1;
             else tab[i]=0;
            };
    }

    ////Ponowne wygenerowanie, teraz juz prawidlowego ciagu bitow//
    for (int i=0; i<110; i++)
    {
        if (i%25==0)
            {
                System.out.println("");
            }
            System.out.print(tab[i]+"("+i+")"+", ");
    }

        System.out.println("\n");        
    System.out.println("W grupie 1: "+licznik1+"("+tabBit[0]+")" + " >"+counter[0]+" "+error[0]);
    System.out.println("W grupie 2: "+licznik2 +"("+tabBit[1]+")"+" >"+counter [1]+" "+error[1]);
    System.out.println("W grupie 3: "+licznik2 +"("+tabBit[2]+")"+" >"+counter [2]+" "+error[2]);
    System.out.println("W grupie 4: "+licznik2 +"("+tabBit[3]+")"+" >"+counter [3]+" "+error[3]);
    System.out.println("W grupie 5: "+licznik2 +"("+tabBit[4]+")"+" >"+counter [4]+" "+error[4]);
    System.out.println("W grupie 6: "+licznik2 +"("+tabBit[5]+")"+" >"+counter [5]+" "+error[5]);
    System.out.println("W grupie 7: "+licznik2 +"("+tabBit[6]+")"+" >"+counter [6]+" "+error[6]);*/


}





////Funkcja wypisujaca bity o indeksie w tablicy kolejnej potegi 2// 
    private static boolean isPowerOfTwo(int x)
    {
        //return (x & (x-1)) ==0;                
        return (x!=0) && ((x&(x-1)) ==0);
    }


    public static void main(String[] args) {

        int [] tab = new int[110];


    // wywo³anie metody wype³niaj¹cej tablicê ci¹giem losowych bitów 0 lub 1
        Losowanie(tab);
        System.out.println("\n Bity potegi dwa: ");
        int [] tabBit = new int [7];


        zamienBity(tab,tabBit);

        System.out.println("////Bity potegi 2");
        sprawdzHamming(tab,tabBit);
        //powerOfTwo();

        /*int liczby [] = new int[120];
        System.out.println("\n");
        for (int z=1; z<120;z++)
        {
            liczby[z]=z;
            System.out.print(liczby[z]+", ");
            if (z%32==0)
                {
                    System.out.println("");
                }
        }*/

    }
}

But i noticed that some arrays are wrong built (i forgot that arrays are numbered from 0) and i wanted to rebuild this code, so that i ask how to put random 110 bits into array, but with first bit on 1 index (not standard 0).


Answer:

In Java arrays are indexed starting from 0. So the index of the 1st element will be 0 and index of the Nth element will be N-1. So since you need to keep 110 bits in an array the arrays will be indexed from 0 - 109.

As an work aground for your requirement of referring to the elements in index that starts from 1, you may write some methods to access the array via 1 based index.

e.g.

int getArrayValue(int[] array, int index){
  return array[index-1]
}

void setArrayValue(int[] array, int index, int value){
   array[index -1] = value;
}

So that your for loop will logs as follows

for (int i = 1; i<=110; i++)
{

   Random r = new Random();

   setArrayValue(tab, i,r.nextInt(2));
   if (i%25==0)
   {
       System.out.println("");
   }
   System.out.print(getArrayValue(tab, i)+"("+i+")"+", ");

 } 

You can use these methods across your code when you want to access the arrays in a 1 based index.


Related:


Javascript sort array of objects in reverse chronological order


javascript,arrays,sorting
I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is...

How can implement long running process in spring hibernate?


java,spring,hibernate
as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

error: cannot find symbol class AsyncCallWS Android


java,android,web-services
I'm trying to rewrite the application in this, in Android Studio link, which is written in Eclipse. There are two problems, first problem is there is this line in the project : import com.example.webserviceactivity.R; I couldn't write this one on Android Studio. The second problem is, in this part of...

Get elements containing text from array


javascript,jquery,html,arrays,contains
I want to search all the elements containing any string in the array. For example I have following list of items <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li> <li>hockey stick</li> </ul> and this array var arr = ['bat', 'ball']; It should select all the elements having text bat and ball....

type conversion if flex


java,actionscript-3,flex
I am using Flerry as Java-Flex bridge for my Flex Desktop Application. How to convert List in Java to ArrayCollection in Flex Flex Code:- [Bindable]public var screenList:ArrayCollection; <flerry:NativeObject id="windowControllerObj" source="ls.window.EnumAllWindowNames" singleton="true" fault="windowControllerObj_faultHandler(event)"> <flerry:NativeMethod id="getWindowNames" name="getAllWindowNames" result="windowControllerObj_resultHandler(event)" fault="getWindowNames_faultHandler(event)"/>...

Join files using Apache Spark / Spark SQL


java,apache-spark,apache-spark-sql
I am trying to use Apache Spark for comparing two different files based on some common field, and get the values from both files and write it as output file. I am using Spark SQL for joining both files (after storing the RDD as table). Is this the correct approach?...

Merge and sum values and put them in an array


javascript,arrays,angularjs,foreach
I'm retrieving values from an external source and apply a foreach loop to the results, with the code below. angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { console.log(value.firstname + ' - ' + value.distance); } else { //do nothing } }); The result is console...

custom arraylist get distinct


java,android
is there any way to get the distinct values of a custom arraylist? public class mystatistic extends BaseActivity { public String objectid; public String playerid; public String playername; public String enemyid; public String enemyname; public String question; public mystatistik(String objectid, String playerid, String playername, String enemyid, String enemyname, String question)...

Logging operations in lightadmin


java,spring,logging,lightadmin
I have a Java web application which use Spring and Hibernate and I plan to use lightadmin to provide an administration interface. However, I found very little information about the logging part of lightadmin : if I have such an adminsitration interface, I would like that any operation made to...

How to call MySQL view in Struts2 or Hibernate


java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

Get element starting with letter from List


java,android,list,indexof
I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

Android set clickable text to go one fragment to another fragment


java,android,android-fragments,spannablestring
I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

Java Scanner not reading newLine after wrong input in datatype verification while loop


java,while-loop,java.util.scanner
I've looked at similar questions and tried to follow the answers that solved the issues that others have had but putting the sc.next() or sc.nextLine() after the while loop causes it to go into an infinite loop. The problem is if a user enters incorrect input (nothing or a number)...

Can I install 2 or more Android SDK when using Eclipse


java,android,eclipse,sdk,versions
I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]


java,android,eclipse,adt
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat http://i.stack.imgur.com/VZhuL.png package...

Get network interfaces on remote machine


java,network-programming
I know in java we can do NetworkInterface.getNetworkInterfaces() to get all available network interfaces on local machine. Can we do similar thing where I can pass host name to get the NICs(with IPs) which are up and running?

Getting particular view from expandable listview


java,android,listview,android-fragments,expandablelistview
In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....

Selenium catch popup on close browser


java,selenium,browser
I'm trying to test that when I close my window a popup shows with a warning message. I've tried both driver.close() and driver.quit() after making sure I'm on the proper window but this just terminates the process since my popup doesn't show. I could test it by using the awt...

Mysterious claim of a missing { in eclipse


java,eclipse
I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

pointer to pointer dynamic array in C++


c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

How to block writes to standard output in java (System.out.println())


java,logging,stdout
In Java, how to block code from writing to system out? My app calls a 3rd party library that spams logs by issuing numerous System.out.println() calls. I don't have legal rights to decompile and patch the library. I'm running Websphere 8.5.x Considered using System.setOut(PrintStream out), but that will effect the...

Reading and modifying the text from the text file in Java


java
I am have a project that need to modify some text in the text file. Like BB,BO,BR,BZ,CL,VE-BR I need make it become BB,BO,BZ,CL,VE. and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR. I have tried to type some code, however the code fail to loop and also,in this...

Translating a character array into a integer string in C++


c++,arrays,string
I was trying to achieve translating a character array into a integer string and corresponding character to their alphabetical order. For instance: A(a) = 0 , Z(z) = 25. string key_char = argv[1]; string key_num; for (int i = 0; i < key_char.length(); i++){ if (isalpha(key_char[i])){ if (islower(key_char[i])){ key_num[i] =...

PropertyNotFoundException in jsp


java,jsp
Am getting this error in my application javax.el.PropertyNotFoundException: Property 'survey_id' not found on type com.moh.forms.MOH731 javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:229) javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:206) javax.el.BeanELResolver.property(BeanELResolver.java:317) javax.el.BeanELResolver.getValue(BeanELResolver.java:85) This is my MOH731.java @Id @GeneratedValue(strategy = GenerationType.AUTO) private int survey_id; public MOH731 (int survey_id, String uname)...

Blank screen on GridView


android,arrays,gridview
I'm trying to create a GridView with an array of strings. These are XML, and MainActivity and Adapter, but what I get is a blank screen. I'm change the background, but the result is the same, but clicking on a point on the screen appears to me the toast stating...

Get document on some condition in elastic search java API


java,elasticsearch,elasticsearch-plugin
As I know we can parse document in elastic search, And when we search for a keyword, It will return the document using this code of java API:- org.elasticsearch.action.search.SearchResponse searchHits = node.client() .prepareSearch() .setIndices("indices") .setQuery(qb) .setFrom(0).setSize(1000) .addHighlightedField("file.filename") .addHighlightedField("content") .addHighlightedField("meta.title") .setHighlighterPreTags("<span class='badge badge-info'>") .setHighlighterPostTags("</span>") .addFields("*", "_source")...

why java API prevents us to call add and remove together?


java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

Substring of a file


javascript,arrays,substring
I have a file that is structure like this : var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; Now I would extract all letters "c" and "d" of this file and put those letter in array, structure like this: var array = [ [a,b,1], [a,b,2], [a,b,3], [a,b,4], [a,b,5] ]; How...

Ruby: How to copy the multidimensional array in new array?


ruby-on-rails,arrays,ruby,multidimensional-array
seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

Get the value of the last inserted record


java,jdbc
I am trying to get the stop_name of the last inserted row in the table with preparedStatement. How can I get the last inserted one? I appreciate any help. behavoiur table: CREATE TABLE IF NOT EXISTS behaviour( behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, mac VARCHAR(30) NOT NULL, stop_name VARCHAR(30)...

Android String if-statement


java,android,string
I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

SOAP Client, Following an example


java,soap,saaj
I need to consume a SOAP Server named "Mouser" for my company. However I have a problem when I try to send a message. The documentation of my request is : POST /service/searchapi.asmx HTTP/1.1 Host: www.mouser.fr Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Header> <MouserHeader...

Interpreting hex dump of java class file


java,class,hex
I understand the structure of a java .class file, but when I want to interpret the raw hex data I get a bit lost. This is a hex dump of a class file, excluding the header and constant pool. I understand the header to be the magic number, minor_version and...

Using world coordinates


java,libgdx
I am currently using pixels as units for placing objects within my world, however this can get tedious because I only ever place objects every 16 pixels. For example, I would like to be able to place an object at position 2 and have the object rendered at the pixel...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring


java,spring,jsp,spring-mvc
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- avoid '???' --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp"/> </bean> if i create other subfolders under jsp , for instance /WEB-INF/jsp/reports , /WEB-INF/jsp/insertions how should i configure now the viewResolver to can resolve these new sub folders??...

Form submit portlet with Spring MVC


java,jsp,spring-mvc,liferay,portlet
I'm trying to achieve a Liferay portlet of submit form using spring MVC. The model: package com.model; public class Person { String firstName; String middleName; public String getFirstName() { return this.firstName; } public String getMiddleName() { return this.middleName; } public void setFirstName(String firstName) { this.firstName=firstName; } public void setMiddleName(String middleName)...

How to pivot array into another array in Ruby


arrays,ruby,csv
I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

how to call Java method which returns any List from R Language? [on hold]


java,r,rjava
How to call java method which returns list from R Language.

Android Implicit Intent for Viewing a Video File


java,android,android-intent,uri,avd
In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(R.id.button); button.setOnClickListener ( new Button.OnClickListener()...

App Not Downloading Newest Version Of File [Java]


java,caching,download
Okay, I've been trying to figure this out for a few hours and it's starting to kill me. I wrote a primitive version checker for an app I work on every once and awhile. It's just a simple for fun project. The version checker has been a pain though. It...

Javascript function to validate contents of an array


javascript,arrays
Here's what is asked: validItems(items) – this function receives a string array of items which are to be for a customer. The function returns an empty string indicating all item codes in the array are valid; otherwise the function returns the first invalid item code in the array. All item...

Infinite loop with fread


c,arrays,loops,malloc,fread
I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

Java dice roll with unexpected random number


java,if-statement
I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below: 3 1 [email protected] 1 5 4 1 [email protected] 1 [email protected] [email protected] 1 6 [email protected] 1 [email protected] [email protected] 1 2 3 3 When I ran it for...

Get current latitude and longitude android


java,android,gps,geolocation,location
Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

Javadoc: Do parameter and return need an explicit type description


java,types,javadoc
When Javadoc'ing, I don't know whether you should explicitly say whether the parameters are of type String or int. For example /** * This method does something * @param foo an object of type Foo * @param abc the number of doors, of type int * @return the number of...

array and function php


php,arrays
I'm just a beginner in PHP coding. I've been reading through a tutorial, but having some trouble with basic PHP concepts. If you could help me, I'd be much obliged. I'm having trouble understanding why the following code doesn't work. <?php function sum($x, $y) { $z = $x + $y;...

How to do custom rounding of numbers in Java?


java,rounding
Suppose I want to round numbers that have mantissa greater than 0.3 'up' and those below 'down'. How can I do it in Java? The only thing that came to my mind was Math.round(), but I can't seem to make it follow a certain rule....

BitmapFont class does not have getBound(String) method


java,android,libgdx
Previously I used getBound method for BitmapFont class in libgdx, but now, I am unable to use it. I cannot find the changes in latest version. Any help is appreciated. Thank you...

Create array from another with specific indices


javascript,arrays
I have two arrays, one of data and one of indices: var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; I would like to create a third array, using cells of data in order indicated...

Finding embeded xpaths in a String


java,regex
I have a string where I have the user should be able to specify xpaths that will be evaluated at runtime. I was thinking about having a the following way to specify it. String = "Hi my name is (/message/user) how can i help you with (/message/message) "; How can...