How To Create Empty Array And Then Assign Values To It

Feb 7, 2015

I am trying to create an empty array that has no assigned length as the amount of elements it needs to hold will be dependent on another value. I then want to use a while loop to assign values to it. Here is an example of what im looking for it doesnt work. Iam trying to do:

int x = 12;
int i = 1;
int k = 0;
int[] factors = {}
while (i<x) {
if (x%i==0) {
factors[k] = i;
k++;
i++;

View Replies


ADVERTISEMENT

Create For Loop That Randomly Assign Values To Each Element Within Array?

Apr 16, 2014

Started learning about Array's I'm doing an exercise where you create a for loop that randomly assigns values to each element within the array, but where is my code going wrong?

import java.util.Scanner;
public class ArrayExamples{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double exampleArray[] = new double[5];
System.out.print("Enter a Number: ");
int num1 = input.nextInt();

[Code] .....

View Replies View Related

How To Randomly Assign Specific Values In Array Or ArrayList

Apr 3, 2015

I'm trying to build a monopoly like game, and atm I'm trying to find way how to build the Community and Chance chest cards. so far, my logic is

1-create an ArrayList of cards with a given order

2-for a given number of times(for loop) generate 2 random numbers ,which will be the parameters for Collection.swap().

3-swap.

here's the code for the shuffler Button

shuffler.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0;i<shuffeledMessages.length;i++){
int randoma=(int)(Math.random()*4);
int randomb=(int)(Math.random()*4);
Collections.swap(myMessages,randoma,randomb);
}
}
});

For now things seem to work pretty ok, but I'm wondering if this is a good and efficient way to shuffle a card chest especially in case of large number of cards. plus, I'm not sure what would be a good loop count for effective shuffling, in my case I used i<arraylist.size

View Replies View Related

Shift-left Array Values - How To Assign Divisors Indexes To Start

Dec 16, 2014

I am writing a program for a game. It is between the user and a virtual player. The game starts with a pool of consecutive integers 1-100. The size of the pool is based on a random generated number at the beginning of the game. At the start, both players' scores are 0. For each turn, the player picks one number from the pool. That value is added to the player's score, the computer gets the sum of all the remaining numbers in the pool that divide evenly into the player's pick. The player's pick and its divisors are then removed from the pool.

The player should be able to play the game as many times as she wants without ending the program. Instructions should appear on the screen only once at the start of the program.

For each turn, both players' current score, the current pool of numbers, and a prompt for a number to be entered should show onscreen. I have written the code until I get to the function that updates the pool of numbers after a turn.

import java.util.Scanner;
import java.util.Random;
public class SlickPick {
public static void main (String[] args){
Scanner read = new Scanner(System.in);
int []pool = new int[100];

[Code] ....

My thinking is that I need to use the binary search to find the indexes of the divisors array and then use those indexes as the start values. I'm not sure how to assign the divisors indexes to start. Do I need an array for start? Whenever I run the program, the only value missing is 3.

//Name : poolUpdate
//Description : This function modifies the contents of the pool as a result of a turn of play.
//Parameters : The pool array, the divisors array, the size, and the user's pick.
// :
//Return :
public static void poolUpdate(int[] pool, int[] divisors, int size, int pick){
int low=0;
int high=size-1;

[Code] ....

View Replies View Related

How To Assign Values To Object

Apr 25, 2015

simple assignment of values to a previously initialized object?

See the method useModel ()

The idea is, assign the values to the temporary object, data

Then plunk it into this statement:

model.addRow ( data );

Simple enough?

I've been putzing with the syntax for multiple hours, over days, now.

With and without

[0];,

Netbeans keeps giving me: Illegal start of expression data is declared as an array of Object, although, in this case, it does not need to be an array. What is the correct syntax?

Java Code: //--
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import javax.swing.JFrame;

[Code]....

View Replies View Related

Assign Values To ArrayList?

Apr 27, 2015

This code currently just prints out the memory for the objects. What I am doing that it obviously wrong?

import java.util.ArrayList;
import java.util.List;
public class deck extends Card {
public final String[] SUITS = { "Heart", "Diamond", "Clubs", "Spade" };
ArrayList<Card> deck = new ArrayList<Card>();

[Code] .....

View Replies View Related

Can Assign Multiple Values To One Variable

Apr 25, 2014

Can I assign multiple values to one variable? For example I want myNum = 0 thru 9 you see im trying to program a password checker program to verify that the password meets all the criteria 8 char long, 1 upper case, 1 lower case, 1 numeric, 1 special, and don't contain and or end

View Replies View Related

Assign Values To Nodes Read From XML Using Java?

Apr 13, 2014

i am trying to assign unique values to nodes read from XML file.. eg: consider this XML file:
 
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description> ...Strong Belgian waffles...</description>
<calories>650</calories>

[code]....

now assigning these nodes "a unique value" has to be done following the LSDX labelling pattern i.e:

To the document element we first give an “a”.As there is no parent node for the document element, we assign “0” at the front of that “a” . “0a” is the unique code for the document element (breakfast_menu). For the children nodes of “0a”, we continue with the next level of the XML tree which is “1” then the code of its parent node which is “a” and a concatenation “.” . We then add a letter “b” for the first child, letter “c” for the second child, “d” for the third child and so on.Unique codes for children nodes of “0a” shall be “1a.b”, “1a.c”, “1a.d”, etc.Hence foe the above given XML the mapping would look something like this:

0a breakfast_menu
1a.b food
2ab.b name
2ab.c price
2ab.d description
2ab.e calories
2ab.f chef
3abf.b chef1
3abf.c chef2
1a.c food
2ac.b name
2ac.c price
2ac.d description
2ac.e calories
2ac.f chef
3acf.b chef1
3acf.c chef2

For more samples about LSDX labelling : 1.) Section 3.1 LSDX Labelling on this link: [URL]

2.) Fig 3 on page 1189 on this link:[URL]

right now i am using SAX parser to read xml and get the nodes in their hierarchical order..now the problem is that i have to assign these specific value to their respective nodes using java.

View Replies View Related

Button That Add Values Into Empty Database - Not Seeing Result

Apr 30, 2014

Here's my code for a button that add values into an empty database.

The program skips system.out.println("1");

And the database is still empty. I can't figure out why

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String url = "jdbc:mysql://localhost:3306/xxxxxxxxxxxx";
String driver = "com.mysql.jdbc.Driver";
String user = "xxxxxxxxxxxx";
String pass = "xxxxxxxxx";

[Code] .....

View Replies View Related

Cannot Assign Cloned String Array To Generic Type Array

Jun 21, 2014

I have the following code in which I am looping through the rows of one array (composed of Strings) and copying it to another array. I am using .clone() to achieve this and it seems work as it changes the memory location of the rows themselves. I did notice that the String objects are still pointing to the same location in memory in both arrays but I won't worry about that for now, at the moment I just want to understand why the array I am cloning is not successfully assigning to the other array.

This is the incorrect line: ar[r] = maze[r].clone();

My code:

private String[][] maze = {{"*","*","*"," ","*","*","*","*","*","*"},
{"*"," ", "*"," "," "," ","*"," ","*","*"},
{"*"," ","*","*","*"," ","*"," ","*","*"},
{"*"," "," "," "," "," "," "," "," ","*"},
{"*","*","*","*","*"," ","*","*","*","*"},
{"*","*","*","*","*"," ","*","*","*","*"}};
//private String[][] mazeCopy = copyMaze(new String[6][10]);
private <T> T[][] copyMaze(T[][] ar){
for (int r = 0; r < ar.length; r++){
ar[r] = maze[r].clone();
}
return ar;
}

My compiler says: Required: T[]. Found: java.lang.String[]

Since ar[r] is an array and .clone() also returns an array why is this line incorrect.

View Replies View Related

Default Constructor That Create Empty Cart

Feb 25, 2014

Java Code:

package collectionsHw_netid;
import java.util.ArrayList;
public class ShoppingCart {
//field items
static ArrayList <String> food = new ArrayList<String>();
static ArrayList <Double> price = new ArrayList<Double>();

[Code] ....

Create a new class, ShoppingCart, with a single field, items, that can hold any number of items (Hint: use an ArrayList)

Create a default constructor that creates an empty cart

Create the following methods. After you write each method, test it by running main.

insertItem which adds an Item to the end of the cart (use only 1 parameter)

print which prints the name and price of each item on a separate line using a loop

removeItem which removes an item at a given index

View Replies View Related

Add A New Jbutton For Every Empty Cell In Array

Apr 22, 2015

im trying to make a gui im trying to add a new jbutton for every empty cell in the array, and for some reason its giving me array index out of bounds error, this is what i have, im trying to to do it in an 80 by 80 array.

public JButton[][] buttons = new JButton[80][80];

public void addButtons(){
for(int i=0;i<buttons.length;i++){
for(int j=0;i<buttons[i].length;j++){
buttons[i][j]= new JButton();
}
}

}

View Replies View Related

How To Assign Numbers Obtain From Modular Equation To Certain Position In Array

Apr 16, 2015

My biggest issues are as follows:

1) I'm trying to use a logarithm to determine the length of a user input number. I keep getting an error stating <> indetifier expected. I'm assuming this means that the program is not recognizing the function of a logarithm. I know that normally you can include that information in the method, but my teacher has stated specifically that each of these methods be called something else, as shown in the code.

2) I'm not quite sure I understand how to assign the numbers I obtain from the modular equation to a certain position in the array. As I'm asking the user to input any number these values can change so therefore I can't simply state that first number = this place.Here is my code:

import javax.swing.*;
import javax.*;
public class getSize
{
public static void main( String[] args )

[code]...

View Replies View Related

Filling Array With Object - Deck Is Empty

Jun 6, 2014

I am trying to create an array filled with the object Card. It keep throwing the exception that the "deck is empty". I am not sure why that's happening because the code for filling the array seems fine.

public class Deck {
private Card[] deck;
private CardPile cardPile;
private int numCards;
public Deck() throws InvalidDataException{
this.deck = new Card[52];

[Code] .....

View Replies View Related

Create All Primitives With Different Values

Jul 6, 2014

I just recently started coding java and i have a problem.... So I was doing an exercise on LearnJavaOnline. The exercise was: Create all the the primitives with different values. Concatenate them into a string and print it to the screen so it will print: H3110 w0r1d 2.0 true.I attempted it and this is what i wrote

public static void main(String[] args) {

char H = 'h';
byte e = 3;
short l = 1;
int L = 1;
long o = 0;
char w = 'w';

[code]....

However it prints "109 w0r1d 2.0 true".But when i add 2 speech marks: String HelloWorld = H+""+e+l+L+o+" "+w+0+r+one+d+" "+two+" "+hi; It works perfectly.

View Replies View Related

Method That Returns New Array By Eliminating Duplicate Values In Array

Jun 15, 2014

Write a method that returns a new array by eliminating the duplicate values in the array using the following method header: public static int[] eliminateDuplicates(int[] list). The thing is that I found the working solution that is written below, but how it works. How to eliminateDuplicates method done with flag and flag2.

Here is the code:

Java Code:

import java.util.Scanner;
public class Exercise06_15 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter ten numbers: ");

[code]....

View Replies View Related

Transfer Random Array Values To A Separate Array?

Feb 16, 2015

filling out a Random array: An Array of Specific Length Filled with Random Numbers This time what I need to do is take the elements from this Random array and assign them to a new Byte array:

for(int i = 0; i < limit-10; i++) {
Random dice = new Random();
int randomIndex = dice.nextInt(array.length);
if (array[randomIndex] < 128) {
System.out.print(array[randomIndex] + " ");
} else if (array[randomIndex] >= 128) {
System.out.print(array[i] + " ");
}

byte[] noteValues = new byte[]

{ 64, 69, 72, 71, 64, 71, 74, 72, 76, 68, 76 }; //This is the byte array filled manually!

I've tried amending the manual input to fit in with the Random array, as follows:

byte[] noteValues = new byte[]
{ array[randomIndex] };

In this case, however, the Byte array can't interpret the int values. Also, if the Byte array is outside the 'for' loop, array[randomIndex] cannot be resolved.

View Replies View Related

Create 2D Array Out Of CSV File And Find Number Of Elements To Determine Array Size

Mar 24, 2015

I am taking the Class Algorithms and Datastructures and got an assignment for Lab that really throws me off. The goal is to create an Array out of a given CSV file, implement several Methods that get the size of array, etc.

I am still stuck in the first part where the CSV has to be imported into the Array. My problem is that I need a mechanism that figures out the needed size for the Array, creates the array, and only then transfers the data from the CSV.

The list consists of the following wifi related values:

MAC-Adress, SSID, Timestamp, Signalstrength.

These are on the list, separated by comma. The Columns are each of these, and the rows are the four types of values making up the information on a certain wifi network.

The catch is, we are not allowed to use any of the following:

java.util.ArrayList
java.util.Arrays
and any class out of java.util.Collection.

So far I used the BufferedReader to read in the file and tried to implement the array, but I get an arrayindexoutofboundsexception.

Below is my Code (Its still an active construction zone):

public class WhatsThere {
public WhatsThere(String wifiscan) throws IOException {
}
public static void main(String[] args) throws IOException {
// WhatsThere Liste = new WhatsThere(String wifiscan);
String[][] arrayListe = new String[0][0];

[Code] ....

View Replies View Related

Create Histogram That Allow To Visually Inspect Frequency Distribution Of A Set Of Values

Apr 4, 2014

Design and implement an application that creates a histogram that allows you to visually inspect the frequency distribution of a set of values . The program should read in an arbitrary number of integers that are in the range 1 to 100 inclusive; then produce a chart similar to the one below that indicates how many input values fell in the range 1 to 10, 11 to 20, and so on. Print one asterisk for each value entered.

No input prompt
Terminate input by typing CTRL/Z (two keys typed at the same time) on a separate input line (use CTRL/D on Linux/UNIX systems)
Use hasNextInt() to terminate your input
Format as below (slightly different from the text example)
Z:dbraffittWeek10> javac Histogram.java
Z:dbraffittWeek10> java Histogram

[Code] ....

What I can not figure out is how to use hasNextInt() to terminate the loop. How to not have an input prompt. How to use ctrl z to terminate the input. Or to make it where it doesn't involve range values like -1.

import java.util.Scanner;
public class Histogram {
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
int [] nums = new int[101];
 
[Code] .....

View Replies View Related

Create N Number Of Flows With Any Combination Of Values - Search Match

Apr 12, 2015

I have a requirement like to attach most suitable flow  to a request
  
Flows should be like below (eg:Flow1) .We can create n number of flows with any combination of values.

When I tried to create a request that have all the  features in the flow. And I have to attach the most suited flow to that request.

Suppose my request have the feature  Place = Place1 and company =Comp1 and Job=Job1 .here most suitable flow is Flow1.

So my question is how can I implement the logic in java for getting the most suitable match.

View Replies View Related

Compare Int With Array Of Values

Dec 24, 2014

I need to compare an int with an array of values generated with a for loop previously. I have something like that for the search..

for( int i = 0; i < 5; i++){
System.out.print("Indovina.. inserisci un valore: ");
// I memorize the value taken input
n = sc.nextInt();

[Code] ....

Also, I need to print the array each time I insert a value that is in the array. But, hiding the values still not "guessed".

View Replies View Related

Isolate Values From Array?

Feb 14, 2015

I'm trying to isolate specific values produced from that array at random. For example, if I were to have an array whose starting inputs are 5 & 10, the output is 5, 10, 15, 25, 40, 65 (the array stops before exceeding 100). Following this, I would generate 6 random numbers from this array (if the array is longer or shorter an equal number of random values from those arrays are generated) allowing for possible repetition of numbers.

So far, I have imported the Random utility and placed the following code below yesterdays code:

System.out.println();
for(int i = 0; i < limit; i++) {
if (array[i] < 100) {
System.out.println();
System.out.println("Rand. no. from array");
Random dice = new Random();
System.out.print(dice.nextInt(array[i])); //Call the Fibonacci array & generate rando numbers from it!!
}
}

Using the above (5, 10) array as an example, the output seems to generate 6 results for each position, but the random element is localised to each number, rather than the whole array. So, at position one we have number 5 and 'any' number between 1 & 5 is generated, rather than any 'specific' number from the 'whole' array. At the second position we have 10 and the printout will give the 2nd random number as anything between 1 & 10, and so on for the rest of the array. Ideally, I'd be looking for something like: 5, 40, 5, 65, 40, 15.

View Replies View Related

Increment Array Values

Jul 5, 2014

I'm attempting to increment the values by 1 in an array of objects but I'm not able to increment with the increment operator.

for(int i=1;i<a.length;i++){
a[i].getHour(); hour = hour++;
a[i].getMin(); miinute = minute++;
a[i].getSec(); sec = sec++;
}

It just loops the value of hour without incrementing.

View Replies View Related

Values Are Not Being Passed To Array

Sep 29, 2014

I have this class:

package model;
import java.awt.Color;
import shapes.Oval;
import shapes.Rectangle;
import shapes.Shape;
import java.awt.Container;
import java.lang.reflect.Array;

[Code] .....

And as it is now, the values are not being passed into the shapeArray array. If I "hard code" two shapes into the array in this class, everything works fine later on, but I do not manage to pass values into the array from the createShape() method. I tried several approaches, nothing works.

View Replies View Related

Values In Array Not Stored?

Oct 6, 2014

I just forgot to increment n while trying to store the humidity... I do this every time and I suddenly realize what I did wrong ...

My problem is that after printing humidity[n] in the "Humidity(%)" row, it seems that humidity[n] becomes 0. I checked like this:

System.out.println(humidity[5] + " " + humidity[6]);

In the "Humidity(%)" row, they come out fine, but when I do this, they come out as 0, which I think would explain why my heat indices are consistently lower than the temperature when the temperature is over 80.

My code:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class HeatIndex {
public static void main(String[] args) throws IOException {
System.out.printf("%70s", "Heat Index: Key West, Florida");

[Code] ......

View Replies View Related

Replacing Old With New Values In Array

May 24, 2014

how to replace the values in my array with the results of my function factorial.

public static void main(String[] args) {
//this is my main function:
int[] array = {5,4,3,2,1};
int i = 0;
System.out.print("results: ");
for (i = 0; i < array.length; i++){
System.out.print(factorial(array[i]));

[code]....

So, what I'm trying to do is change the contents of the array "array" into their factorial value. So, they should be replaced with {120,24,6,2,1}. then add those using linear sum but that's a different story.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved