Affichage des articles dont le libellé est Active questions tagged arrays - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged arrays - Stack Overflow. Afficher tous les articles

dimanche 28 juin 2015

Populate a JCombo Box with each element of Array in Java

Please forgive me, I'm new to Java.

Basically I'm trying to display every element of an Array (i.e. peopleInfo[0], peopleInfo[1], and peopleInfo[2] ) into a JComboBox. I have added elements to the Array from a text file. However when I try to display the elements of the array in the JComboBox only the first element is displayed which is not what I want.

I have attempted to correct this by using a for loop however when I did this it didn't seem to correct my problem however I don't know whether I coded it correctly.

My code currently is:

private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();

public SplitFile() throws FileNotFoundException, IOException
{

    BufferedReader bReader = new BufferedReader(new FileReader("organisms.txt"));

    bReader.readLine(); // this will read the first line


    String line = null;
    while ((line = bReader.readLine()) != null){

        //removes the first space 
        String test = line.replaceFirst("\\s+", "");

        //used regex lookaround to split wherever there are 3 capital letters present, or where any of the tree are present
        String[] peopleInfo = test.split("(\\p{Upper}(?=\\p{Upper})\\p{Upper}\\p{Upper})|(?=Chromalveolata)|(?=Metazoa)|(?=Mycetozoa)|(?=Viridiplantae)|(?=Viruses)|\\;");

        //creates arrays for id, organism and tree
        String id = ">" + peopleInfo[0];
        String organism = peopleInfo[1];
        String tree = peopleInfo[2].replaceAll(";", "").replaceAll("\\d+.*", "");
       System.out.println(tree);
       ArrayList<String> testArray = new ArrayList<String>();
    String[] items = { tree , "Color", "Shape", "Fruit" };


    mainComboBox = new JComboBox( items );
    mainComboBox.addActionListener( this );

    getContentPane().add( mainComboBox, BorderLayout.WEST );

    //  Create sub combo box with multiple models

    //this code displays values dependent on what element is selected from the mainComboBox

    subComboBox = new JComboBox();
    subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
    getContentPane().add( subComboBox, BorderLayout.EAST );

    String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
    subItems.put(items[1], subItems1);

    String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
    subItems.put(items[2], subItems2);

}}

@Override
public void actionPerformed(ActionEvent e)
{
    String item = (String)mainComboBox.getSelectedItem();
    Object o = subItems.get( item );

    if (o == null)
    {
        subComboBox.setModel( new DefaultComboBoxModel() );
    }
    else
    {
        subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
    }
}

Any help would be much appreciated!

Thanks :)

How do I find all word combinations that add up to a certain length?

I need a little help with coming up with an algorithm to traverse through a sorted word array and finding all the possible combinations that add up to a certain length. Any help is greatly appreciated! Thanks :)

Fast array manipulation based on element inclusion in binary matrix

For a large set of randomly distributed points in a 2D lattice, I want to efficiently extract a subarray, which contains only the elements that, approximated as indices, are assigned to non-zero values in a separate 2D binary matrix. Currently, my script is the following:

lat_len = 100 # lattice length
input = np.random.random(size=(1000,2)) * lat_len
binary_matrix = np.random.choice(2, lat_len * lat_len).reshape(lat_len, -1)

def landed(input):
    output = []
    input_as_indices = np.floor(input)
    for i in range(len(input)):
        if binary_matrix[input_as_indices[i,0], input_as_indices[i,1]] == 1:
            output.append(input[i])
    output = np.asarray(output)
    return output   

However, I suspect there must be a better way of doing this. The above script can take quite long to run for 10000 iterations.

Add value in specific index array

i have array data like this.

[0] => Array (
    [id] => 1
    [id_requestor] => 1
    [jam_input] => 2015-06-20 06:00:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 30
    )
[1] => Array (
    [id] => 2
    [id_requestor] => 2
    [jam_input] => 2015-06-20 07:00:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 10
    )
[2] => Array (
    [id] => 3
    [id_requestor] => 3
    [jam_input] => 2015-06-20 06:30:00
    [jam_pakai] => 2015-06-28 08:00:00
    [total_poin] => 5
    )

In above data, there is total_poin. This total_poin that i use later. I want to sort total_poin array descending. But i wont to use php built in array function. Cause i have to use method from research paper like this.

for i=0 to i<main queue.size
   if jobi+1 length > jobi length then
    add jobi+1 in front of job i in the queue
end if
   if main queue.size = 0 then
    add job i last in the main queue
end if

And here is my implementation :

function LJFAlgorithm($time_str) {
        $batchData = getBatch($time_str);

        $ljf = [];
        for ($i=0; $i < count($batchData)-1; $i++) { 
            echo $batchData[$i+1]['total_poin'] ." >= ". $batchData[$i]['total_poin'] . " = " . ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']);

            if ($batchData[$i+1]['total_poin'] >= $batchData[$i]['total_poin']) {
                echo ", Add " . $batchData[$i+1]['total_poin'] . " in front of " . $batchData[$i]['total_poin'];
            } else {
                echo ", Add " . $batchData[$i]['total_poin'] . " in front of " . $batchData[$i+1]['total_poin'];
            }

            echo '<br/>';
        }

        print_r($ljf);
    }

But it not work perfectly, i get one data missing. Here is my output code :

10 >= 30 = , Add 30 in front of 10
5 >= 10 = , Add 10 in front of 5

5 value not added in array. How to fix that?

Thank you very much.

How to sum two dimensional arrays in Java?

I've created a short code to practice two-dimensional arrays but I've stumbled upon a problem that I can't solve in my code. Hope you guys can help me.

Desired Output:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

But instead I'm seeing this:

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 6

Enter number:1
Enter number:2
Enter number:3

NUMBERS THAT YOU ENTERED:
1
2
3

TOTAL: 12

______________________________________________________

It's adding up every number that I input instead of just adding three numbers in each iteration. Please check the code below:

PART I

package Test;

 public class Test1 {
   private int[][] number;
   private int number1;
   public Test1(int[][]n){
      number = new int[2][3];
    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            number[dx][ix]=n[dx][ix];
        }

    }
}

public Test1(int n){
    number1 = n;
}

public int getTotal(){
    int total = 0;

    for(int dx = 0;dx < number.length;dx++){
        for(int ix = 0;ix < number[dx].length;ix++){
            total += number[dx][ix];
        }

    }

    return total;
}

public int getNumbers(){

    return number1;
}

}

PART II

  package Test;
  import java.util.Scanner;
  public class TestMain {
  public static void main(String[]args){
    final int DIVS = 2;
    final int NUM_INSIDE = 3;
    Test1[][] t1 = new Test1[DIVS][NUM_INSIDE];
    int[][]numbers = new int[DIVS][NUM_INSIDE];
    getValues(numbers,DIVS,NUM_INSIDE,t1);

}

public static void getValues(int[][]numbers,int DIVS,int NUM_INSIDE,Test1[][] t1){
    Scanner hold = new Scanner(System.in);
    int num;
    for(int div = 0;div < DIVS;div++){
        for(int ins = 0;ins < NUM_INSIDE;ins++){
            System.out.print("Enter number:");
            numbers[div][ins]=hold.nextInt();
            num = numbers[div][ins];
            t1[div][ins] = new Test1(num);

        }
        Test1 t = new Test1(numbers);
        display(t,t1,div);

    }
}

public static void display(Test1 t,Test1[][] t1,int div){
    System.out.print("****************************\n");
    System.out.print("NUMBERS THAT YOU ENTERED:\n");

    for(int y = 0; y < t1[div].length;y++){
        System.out.print(t1[div][y].getNumbers() + "\n");
    }

    System.out.print("****************************\n");
    System.out.print("TOTAL: " + t.getTotal() + "\n");
    System.out.print("****************************\n");
}
}

Remove subarray from array when one of it's value match another arrays value (PHP)

I have two arrays:

$to_import = Array(
  [0] => Array(['native_id'] => 35339920, ['type'] => product)
  [1] => Array(['native_id'] => 22045872, ['type'] => product)
  [2] => Array(['native_id'] => 25913185, ['type'] => profile)
  [3] => Array(['native_id'] => 14354407, ['type'] => profile)
)

$existing = Array(
  [0] => Array(['native_id'] => 22045872)
  [1] => Array(['native_id'] => 25913185)
  [2] => Array(['native_id'] => 30836971)
)

I need to remove the record from the first array when the id is found in the second array, and when type matches 'profile'. So in this example, three remain:

$to_import = Array(
  [0] => Array(['native_id'] => 35339920, ['type'] => product)
  [1] => Array(['native_id'] => 22045872, ['type'] => product)
  [3] => Array(['native_id'] => 14354407, ['type'] => profile)
)

I have found similar questions, but I can't work out how to apply them to my requirements. This answer looks like it is close to what I want, but I can't get it to work, my knowledge is failing me.

Splitting NSString doesn't work in Swift

I have a long string i need split into an array by splitting when "|||" is found

I can split a String using two ways i found at SO

First one is this

 func split(splitter: String) -> Array<String> {
    let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)!
    let stop = "<SomeStringThatYouDoNotExpectToOccurInSelf>"
    let modifiedString = regEx.stringByReplacingMatchesInString (self, options: NSMatchingOptions(),
        range: NSMakeRange(0, count(self)),
        withTemplate:stop)
    return modifiedString.componentsSeparatedByString(stop)
}

Second one is this

var splt = str.componentsSeparatedByString("[\\x7C][\\x7C][\\x7C]")

I tried using the delimiter as both "[\x7C][\x7C][\x7C]" and "|||" and i tried using both String and NSString

Nothing seems to work though, i just get an array with the original string in it

Bash: Is ${@:2} the same as $2?

Is ${@:2} the same as $2 in Bash when my second argument is an array? My script does work with ${@:2} replaced by $2, but is there any downside?

Steve

Creating large arrays in Swift

I have an array in Swift that has 1000+ strings inside it. I am getting an error that looks like this: Command failed due to signal: Segmentation fault: 11

Is there a place I can store a lot of strings in a way that won't break xcode, and if there is, how do I put them in and get the strings from it?

Take sentence from user input with C

I wana take input from user and then print, I think I should also allocate memory could someone show me how to do that properly?

Here is my try:

    int days = 1;
    char * obligation[1500];
    char * dodatno[1500];

    puts("Enter nuber of days till obligation:\n");
    scanf(" %d", &days);
    puts("Enter obligation:\n");
    scanf(" %s", obligation);
    puts("Sati:\n");
    scanf(" %s", dodatno);

printf("%s|%s|%s \n",days,obligation,dodatno);

Alternative for #subList() for String array?

So I modified an API (for command management) to use String[] instead of a list of Strings.

My problem is here:strings.subList(1, strings.length) So I need to change this to a different alternative that would do the same job.

What exactly could I do here?

Why doesn't byte[] b = new byte[8](); work? [duplicate]

I already know that byte[] b = new byte[8]; works fine. But why doesn't byte[] b = new byte[8]; work?

For example, byte b = new byte(); works fine, so an array style also should work but it doesn't. I have no exact idea of this reason. Could someone please explain?

AS3: hitTestObject turning up null for no apparent reason

I'm currently coding a game, and in one part of the code, it's checking to see if the player is close enough to a monster in mArray for its health bar to appear. I use hitTestObject for this with var i incrementing to go through the list. However, I will randomly get this error message:

TypeError: Error #2007: Parameter hitTestObject must be non-null.

After seeing this for the first time, I put the test all under the conditional if (mArray.length > 0) to make sure the Array() was filled before even attempting the test... but it still occurs at random times. I even used trace(i) to see if it happened on a certain part of the list, but it's completely random each debug session! I know the player portion can't be null since it is on the screen at all times during the hitTest, so I'm at a loss for words right now.

The portion of code in question (nothing else is related to this except for the use of mArray[i] in different places):

for (var i:int = 0; i < mArray.length; i++) {
    if (mArray.length > 0) {

        trace(i); //my attempt to see if it occurred at a specific incrementation of i

        if (player.hitTestObject(mArray[i])) {
            mArray[i].healthBar.visible = true;
        } else {
            mArray[i].healthBar.visible = false;
        }

    }
}

Again, it works perfectly for everything all of the time except for random cases it gives me the TypeError. Is this just a hiccup in my code, is there some obvious problem that I'm overlooking, or does the code just like to throwback to 2007?

EDIT: The debug session ALWAYS points to the line with if (player.hitTestObject(mArray[i])).

The left hand side must be a variable (ArrayList and Array)

I'm a little confused between an ArrayList and an Array, I understand what a variable is but I don't understand why I can't convert the ArrayList to an Array and have the same effect.

This piece of code I currently have when using an ArrayList

import java.util.Objects;

import com.google.gson.Gson;
import com.google.gson.JsonObject;


public final class NpcDefinitionLoader extends JsonLoader {

    /**
     * Creates a new {@link NpcDefinitionLoader}.
     */
    public NpcDefinitionLoader() {
        super(DefinitionEditor.fileChooser.getSelectedFile().getAbsolutePath());
    }

    @Override
    public void load(JsonObject reader, Gson builder) {
        int index = reader.get("id").getAsInt();
        String name = Objects.requireNonNull(reader.get("name").getAsString());
        String description = Objects.requireNonNull(reader.get("examine").getAsString());
        int combatLevel = reader.get("combat").getAsInt();
        int size = reader.get("size").getAsInt();
        boolean attackable = reader.get("attackable").getAsBoolean();
        boolean aggressive = reader.get("aggressive").getAsBoolean();
        boolean retreats = reader.get("retreats").getAsBoolean();
        boolean poisonous = reader.get("poisonous").getAsBoolean();
        int respawnTime = reader.get("respawn").getAsInt();
        int maxHit = reader.get("maxHit").getAsInt();
        int hitpoints = reader.get("hitpoints").getAsInt();
        int attackSpeed = reader.get("attackSpeed").getAsInt();
        int attackAnim = reader.get("attackAnim").getAsInt();
        int defenceAnim = reader.get("defenceAnim").getAsInt();
        int deathAnim = reader.get("deathAnim").getAsInt();
        int attackBonus = reader.get("attackBonus").getAsInt();
        int meleeDefence = reader.get("defenceMelee").getAsInt();
        int rangedDefence = reader.get("defenceRange").getAsInt();
        int magicDefence = reader.get("defenceMage").getAsInt();

        NPCDefinitions.definitions.get(index) = new NPCDefinitions(index, name, description, combatLevel, size, attackable, aggressive, retreats,
            poisonous, respawnTime, maxHit, hitpoints, attackSpeed, attackAnim, defenceAnim, deathAnim, attackBonus, meleeDefence,
            rangedDefence, magicDefence);
    }
}

I get an error here

NPCDefinitions.definitions.get(index) = new NPCDefinitions(index, name, description, combatLevel, size, attackable, aggressive, retreats,
        poisonous, respawnTime, maxHit, hitpoints, attackSpeed, attackAnim, defenceAnim, deathAnim, attackBonus, meleeDefence,
        rangedDefence, magicDefence);

Saying the left side must be a variable. When I use an Array like this

NPCDefinitions.definitions[index] = new NPCDefinitions(index, name, description, combatLevel, size, attackable, aggressive, retreats,
        poisonous, respawnTime, maxHit, hitpoints, attackSpeed, attackAnim, defenceAnim, deathAnim, attackBonus, meleeDefence,
        rangedDefence, magicDefence);

Code works perfect.

I'm confused about this, how would I make this work by using an ArrayList?

Parse object containing array elements

I have a Parse object called Recipes and a column called ingredients, which is an array. I want to query my object list and retrieve a recipe based on some ingredients that I select.

If I use the whereKey:containsAllObjectsInArray: message on the query object, I will get recipes with more ingredients. Also, whereKey:containedIn: does not solve my problem. The retrieved objects should have an array of ingredients containing all my selected ingredients or only some of them. It should never have more ingredients than those I've selected.

Any ideas?

Cannot Assign Converted Value To Array

I would like to assign the integer value which is included in a string to an array.

The code:

int s[10][10];
string line="1asd";
char z=line[0];
s[0][0]=z-'0';

Error:

  `Invalid types 'char[int]' for array subscript`

How to declare a static array with variable length in delphi?

I need an array, that is optimized for one-time-initialization at runtime, with a given length. So memory should be allocated at runtime, but I don't need to change its length.

Is there a array-type other than the pure dynamic array? (it seems to be not the optimal choice for this task)

Bonus would be, if the initialized array is indexable via pointer-iteration, so all it's elements are allocated consecutive in memory.

Is this all just a daydream of a non-experienced programmer, or is there a possibility to achieve this?

I could imagine to do this with manual memory allocation, but maybe there's another way.

Binding a generic list with knockout.js in MVC5

I am using knockout.js to display the amount of articles I have in my shopping cart. The shopping cart information are saved in a List of the Model ShoppingCartItem. Because I did not read about a way to bind a list with knockout.js directly I am pushing my list items into an array and bind this array afterwards.

But no matter what I am trying the output is always "You have Articles in your shopping cart.". So the length of my array is not displayed.

I added knockout.js in the bundle config file:

bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout-3.3.0.js"));

            bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout-3.3.0.debug.js"));

            bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout.validation.js"));

            bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout.validation.debug.js"));

My view Model ShoppingCartItem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OnlineShop.Models
{
    public class ShoppingCartItem
    {
        public Products product { get; set; }
        public int amount { get; set; }
    }
}

My partial view where I want to use model binding with knockout.js:

@model List<OnlineShop.Models.ShoppingCartItem>

<script type="text/javascript">
    var myArray = [];

    @foreach (var d in Model)
    {
        @:myArray.push("@d");

    }

    var viewModel = {
        cartItems: ko.observableArray(myArray)
    };

    ko.applyBindings(cartItems, document.getElementById("test"));
</script>

<div id="top-cart" class="clearfix">
    <div class="shoppingcart-txt">
        @if (Model != null && Model.Count() > 0)
        {
            double sum = 0.0F;

            for (int i = 0; i < Model.Count(); i++)
            {
                sum = sum + (Model[i].amount * Model[i].product.PurchasePrice);
            }

            <p>
                You have <span id = "test" data-bind="text: cartItems().length">&nbsp;</span> articles in your shopping cart. <br /> 
                <strong>
                    Sum: @sum.ToString("#,##0.00") EUR <br />
                    excl. 3.00 EUR shipping costs
                </strong> 
            </p>
        }
        else
        {
            <p>
                You have no articles in your shopping cart.



            </p>
        }
    </div>
    <div class="shoppingcart-img">
        <a href="@Url.Action("ShoppingCart", "Home")">
            <img src="~/Photos/shoppingcart.png" alt="" border="0" />
        </a>
    </div>
</div>

I also tried to apply the bindings with the following:

ko.applyBindings(cartItems, document.body);

With the same result. The length of my array is not displayed.

I would really appreciate if anyone can tell me what I am doing wrong.

How to get checkbox value in angularjs?

I have a 10(or n)checkbox in my ng-view. Now I would like to ask here that What is the most efficient or simple way to check if checkbox is checked and if checked get the value of checkbox.

<ul>
  <li ng-repeat="album in albums">
   <input type="checkbox" ng-model="folder.Selected" value={{album.name}} />
   </li>
  </ul>

I have ng-controller(getAlbumsCtrl), in that I have an array in which I want to push all the checkedbox albums names into albumNameArray

2D MATRIX statement for 5 x 5 Grid

Given a 5 x 5 Grid comprising of tiles numbered from 1 to 25 and a set of 5 start-end point pairs. For each pair,find a path from the start point to the end point. The paths should meet the below conditions:

a) Only Horizontal and Vertical moves allowed.

b) No two paths should overlap.

c) Paths should cover the entire grid

Input consist of 5 lines. Each line contains two space-separated integers,Starting and Ending point.

Output: Print 5 lines. Each line consisting of space-separated integers,the path for the corresponding start-end pair. Assume that such a path Always exists. In case of Multiple Solution,print any one of them.

Sample Input

1 22

4 17

5 18

9 13

20 23

Sample Output

1 6 11 16 21 22

4 3 2 7 12 17

5 10 15 14 19 18

9 8 13

20 25 24 23