The array of index value is not starting from 0 - arrays

I have 2 buttons to load the different texture images and when i press the 1st it loads the 4 images in textures and when i press the 2nd button it loads the 3 images in textures. But the problem is when i press the 1st button it loads the 4 images and when i press the 2nd it loads the images but it starting from 5th place. I can't reset the value to 0 when i press the second button.
private int clonevalue = 0;
public int i = 0;
string response = www.text;
IDictionary search = (IDictionary) Json.Deserialize(response);
IList linksObject = (IList) search["Products"]; //Here searching only products array
foreach (IDictionary modellinksArray in linksObject) {
string cat_id=string.Format("{0} ", modellinksArray["category_id"]); //From products array getting the category_id
//int catd_id_int = int.Parse(cat_id); //Converting the string value to integer
if(cat_id == myId){//Now, i have used static code value of 4 and if the value match and we can gets only matching category model. Here you can pass the id value of category list selected.
int clonevalue = 0;
int i = 0;
// i = 0;
cloneGO = Instantiate(myScrollTexture)as GameObject;
cloneGO.transform.parent = parentObject.transform;
cloneGO.transform.localPosition =new Vector3(127,30,0);
cloneGO.transform.localScale =Vector3.one;
cloneGO.name = "cloneScrollTexture"+i;
string myTexture = string.Format("{0} ", modellinksArray["imageurl"]);
string modelUrl = string.Format("{0} ", modellinksArray["modelurl"]);
i++;
//StartCoroutine(Load3D(modal3d,modal3d));
cloneGO.GetComponent<dynamicmodelload>().modelURL = modelUrl;
//Destroy(cloneGO);
WWW www1 = new WWW(myTexture);
Debug.Log("text"+myTexture);
yield return www1;
//if(!www1.isDone){
//yield return null;
//}
//if(www1.isDone){
Debug.Log (clonevalue);
//clonevalue = 0;
//DebugConsole.Log (clonevalue);
myTextureObject = GameObject.Find ("cloneScrollTexture" + clonevalue);
//Debug.Log (myTextureObject);
clonevalue++;
Debug.Log (myTexture);
myTextureObject.GetComponent<UITexture>().mainTexture = www1.texture;
Debug.Log ("myTextureObject"+myTexture);
//DebugConsole.Log ("myTextureObject"+myTexture);
if (myTextureObject.name == "cloneScrollTexture"+evenValues) {
myTextureObject.transform.localPosition =new Vector3(-81,30,0);
evenValues +=2;
Debug.Log (evenValues);
//DebugConsole.Log (evenValues);
}
if(myTextureObject.name == "cloneScrollTexture"+yevenValue){
yValue += 210;
Debug.Log("yevenValue"+yevenValue);
//DebugConsole.Log("yevenValue"+yevenValue);
yevenValue +=2;
}
//for(int i=0; i< 2; i++){
Debug.Log ("yValue"+yValue);
//DebugConsole.Log ("yValue"+yValue);
myTextureObject.transform.localPosition -=new Vector3(0,yValue,0);
Debug.Log ("myTextureObject"+myTextureObject.transform.localPosition);
//evenValues +=2;
// test = 5;
}
when i press the 1st button and the clone value passing to 0. So, the texture image properly loading in the 0th position but when i press the second button the clonevalue passing to number 5. so, the texture image displaying in the 5th place. So, how can i reset the clonevalue 0 when i press the 2nd button. So, that i can easily pass to 0.

Related

Java - Search only working for array [0], remaining array items returning "not found"

In the following method, searching for an item name that is included in the array should return "(item name) was found and its product id is (item array ID)".
This works for item [0], but if any other item name is entered, they return "That product was not found".
private int findProduct() {
System.out.println("Enter the item to search for:");
while (true) {
for (int i = 0; i < products.length; i++) {
String itemToFind = getNextStringLineFromUser();
String searchText = products[i];
if (searchText.equals(itemToFind)) {
System.out.println(itemToFind + " was found and its product id is " + i);
return i;
}
System.out.println("That product was not found");
return -1;
}
}
}
If anyone has an idea of why this issue is happening, I would be very grateful for some advice on how to resolve the problems.
Thank you in advance for any help.
I got you.
The reason why your method is only right when the target is at index 0, is that your method returns -1 when first time not matched, without examining the other array element. (When a method returned, it terminated.)
Modify and check your code, you will see.
private int findProduct() {
System.out.println("Enter the item to search for:");
while (true) {
for (int i = 0; i < products.length; i++) {
String itemToFind = getNextStringLineFromUser();
String searchText = products[i];
if (searchText.equals(itemToFind)) {
System.out.println(itemToFind + " was found and its product id is " + i);
return i;
}
System.out.println("That product was not found"); // line 1
return -1; // line 2
}
}
}
The line 1 and 2 I commented, should be placed out of the for-loop. If you put them at where they are now, they will be run after the above if-statement run.
So if the first element of array matches with itemToFind, it works normal. When the first element does not match with itemToFind, the below line 2 will be run, your method terminates right away at a wrong timing.
The right code should be:
private int findProduct() {
System.out.println("Enter the item to search for:");
String itemToFind = scanner.nextLine(); // receive the entered string
for (int i = 0; i < products.length; i++) {
String searchText = products[i];
if (searchText.equals(itemToFind)) { // check if matched
System.out.println(itemToFind + " was found and its product id is " + i);
return i; // exit the method
}
}
System.out.println("That product was not found");
return -1;
}

unable to get list of webelements text box value using getText(); and getAttribute();

I have made List of stored webelements, in that list some of element will get text box value through get getText(); and some will get through getAttribute();.here I made a for loop mentioning getAttribute(); to that list of webelement and get textbox values of each webelement, but here I am getting getAttribute(); text box values rest of elements which has getText(); I am unable to get those textbox values.
Is there any IF condition which has to satisfy both methods i.e gettext(); and getAttribute(); and get textbox values ,if I use only method I am getting for that method text box values rest of elements showing white spaces and printing HERE IS THE CONSOLE O/P null.
List<WebElement> e=new ArrayList<WebElement>();
e.add(sign.empchequedatetext);
e.addAll(sign.wagestlistvalues);
e.addAll(sign.taxesvalue);
e.addAll(sign.additionalincomelistvalues);
e.addAll(sign.otherdeductionslistvalues);
e.add(sign.netpayvalue);
int calculatevaluessize= e.size();
System.out.println("the total value size: "+calculatevaluessize);
System.out.println("taxes size is: " + taxesvalues+"||"+wages+"||"+add+"||"+deduc);
List<WebElement> emplist = s.getOptions();
int empsize = emplist.size();
System.out.println("emp size is: " + empsize);
try {
for (int i = 0; i < empsize; i++) {
WebElement emp = emplist.get(i);
emp.click();
String empname = emp.getText();
excel.setCellData(path, "Sheet2", i + 1, 0, empname);
Thread.sleep(1000);
for (int j = 0; j < calculatevaluessize; j++) {
WebElement taxesvalue = e.get(j);
Thread.sleep(1000);
String values = taxesvalue.getAttribute("value");
System.out.println("the calculate pay values are: "+values);
excel.setCellData(path, "Sheet2", i + 1, j + 1, values);
}
plz mention any if condition in my second for loop,i have tried but what type of condition i have to place
You can create a simple method to return one thing or the other:
private String getRowText(WebElement taxesvalue){
if (taxesvalues.getText() == null){
return taxesvalue.getAttribute("value");
}
return taxesvalues.getText();
}
This method should replace your taxesvalue.getAttribute("value");

How can I fix this error : 'Cannot invoke loadPixels() on the array type PImage[]'?

I'm kind of a beginner with Processing and I've been having difficulty with my pixel array. I have 10 images numbered from 0-9 that are being shown one after another... What I am trying to do on top of that is take each image and change its brightness level, turning it either white or black.
I've already tried to just change the brightness using one image, so not an array of images which works perfectly! But when joining those two together it doesn't work for me.
int maxImages = 10; // The number of frames in the animation
int imageIndex = 00; //initial image to be displayed first
PImage[] picture = new PImage[maxImages]; //the image array
void setup() {
size(500, 500); //size of sketch
frameRate(1); //frames processed per second
//loading images with numbered files into the array
for (int i = 0; i< picture.length; i++) {
picture[i] = loadImage("spast_" + i + ".jpg");
}
}
void draw() {
image(picture[imageIndex], 0, 0); //dispaying one image
loadPixels(); //accessing pixels
picture.loadPixels(); //accessing the image pixels too
//THIS is where it stops me and gives me 'Cannot invoke loadPixels() on the array type PImage[]'
for (int x = 0; x < width; x++) { //loops through every single x value
for (int y = 0; y < height; y++) { //loops through every single y value
int loc = x + y*width; // declare integer loc
float b = brightness(picture.pixels[loc]); //give me the brightness of pixels
if (b < 150) { //if the pixel is lower than 150
pixels[loc] = color(0); //then make those pixels black
} else { //otherwise
pixels[loc] = color(255); //make pixels white
}
}
}
imageIndex = (imageIndex + 1) % picture.length; //increment image index by one each cycle
updatePixels(); //when finished with the pixel array update the pixels
}
I'm expecting as each image is displayed it brightness value is changed and then it goes on to image 2 and so on...
Your picture variable is an array of PImage instances. You can't call loadPixels() on the array itself. You have to get a PImage at a specific index of the array, and then call the loadPixels() function on that instance.
Here's an example:
picture[0].loadPixels();
This line of code gets the PImage at index 0 and calls the loadPixels() function on it.
Note that you're already doing something pretty similar with this line:
image(picture[imageIndex], 0, 0);
Shameless self-promotion: here is a tutorial on arrays in Processing.
This is the updated and working code:
int maxImages = 10; // The number of frames in the animation
int imageIndex = 0; //initial image to be displayed first
PImage[] picture = new PImage[maxImages]; //the image array
void setup() {
size(500, 500); //size of sketch
frameRate(1); //frames processed per second
//loading images with numbered files into the array
for (int i = 0; i< picture.length; i++) {
picture[i] = loadImage("spast_" + i + ".jpg");
}
}
void draw() {
loadPixels(); //accessing pixels
image(picture[imageIndex], 0, 0); //dispaying one image
imageIndex = (imageIndex + 1) % picture.length; //increment image index by one each cycle
picture[imageIndex].loadPixels(); //accessing the image pixels in the array
for (int x = 0; x < width; x++) { //loops through every single x value
for (int y = 0; y < height; y++) { //loops through every single y value
int loc = x + y*width; // declare integer loc
float b = brightness(picture[imageIndex].pixels[loc]); //give me the brightness of pixels
if (b < 150) { //if the pixel is lower than 150
pixels[loc] = color(0); //then make those pixels black
} else { //otherwise
pixels[loc] = color(255); //make pixels white
}
}
}
updatePixels(); //when finished with the pixel array update the pixels
}

How do I interact with a grid using a 2D array (Proce55ing)

For a project I need to create Connect Four using Processing, I have created the grid which the game will be played in however I am lost when it comes to players interacting with it.
I have been told to use a 2D array however my knowledge of arrays is very limited. I am currently trying to code the bit where the program detects where a player has clicked and spawning a coin there.
int c = 8;
int r = 10;
int[][] grid = new int [c][r];
int CoinSpawn = -1;
void setup () {
size(1000, 800);
}
void draw () {
background(1, 1, 1);
translate(100, 100);
noStroke();
drawColumns();
drawRows();
}
void keyPressed () {
for (int i=0; i<grid.length-1; i++) {
grid[i][i] = grid[i+1][i+1];
}
}
void drawRows(){
for (int i=0; i < r; i++){
int x = 80;
x = x * i;
translate(x,0);
drawColumns();
translate(-x,0);
}
}
void drawColumns(){
for (int i=0; i < c; i++){
int y = 80;
y = y * i;
translate(0,y);
drawCell();
translate(0,-y);
}
}
void drawCell(){
fill(0,0,255);
rect(0,0,80,80);
noFill();
fill(0);
ellipseMode(CENTER);
translate(40,40);
ellipse(0,0,75,75);
noFill();
translate(-40,-40);
}
Would I be able to assign the 2D array to the grid? so that each slot in the grid represents an element from the array? That is the best option I can see at the moment however I have no idea how to do it.
I really appreciate any replies as I am completely lost at the moment.
You have a pretty good start, I made a lot more changes than I had planned... got a little into it!
Let me know if you have any questions, I did use one simple OOP class called cell that tracks the value and the cell's position, as well as provides a display function, I converted a lot of your variables and hard coded numbers to constants (starts with final and has the same value for the entire program)
you will notice I left the win conditions to you!
I hope this is helpful, I feel like seeing 2D arrays used in a context you are familiar with might help you understand them!
My normal process using 2D arrays for processing:
use Setup() to set initial array values
use Draw() to call each of the item's display function
use other functions to modify the array data, which the display function of the cell knows how to display
Main File
// Grid Size constants
final int GRID_COLUMNS = 10;
final int GRID_ROWS = 8;
// Display constants
final int CELL_SCALE = 80;
final int COIN_RADIUS = 75;
final int BOARD_PADDING = 100;
final color[] PLAYER_COLORS = new color[]{color(0), color(200, 10, 10), color(200, 200, 10)};
// cell values
final int EMPTY_CELL = 0;
final int PLAYER_1 = 1;
final int PLAYER_2 = 2;
// game data
Cell[][] grid = new Cell [GRID_COLUMNS][GRID_ROWS];
int currentPlayer;
void setup () {
size(1000, 800);
ellipseMode(CENTER); // only needs to be set once per sketch
setupBlankBoard();
}
// method to populate the array with blank cells, used to initiate and reset the game
void setupBlankBoard() {
currentPlayer = PLAYER_1; // reset game and start with first player
// populate array
for (int y=0; y < GRID_ROWS; y++) { // for every vertical row,
for (int x=0; x < GRID_COLUMNS; x++) { // for every horizontal cell in that row
// rather than translates I prefer to calculate the actual x,y position and just display it there,
// we add the padding offset to every cell, and then take the column/row times the width of the square cell
grid[x][y] = new Cell(BOARD_PADDING+x*CELL_SCALE, BOARD_PADDING+y*CELL_SCALE);
}
}
}
void changePlayers() {
if (currentPlayer == PLAYER_1) {
currentPlayer = PLAYER_2;
} else {
// already was player 2, so change to 1
currentPlayer = PLAYER_1;
}
}
boolean placeCoin(int column) {
boolean coinPlaced = false;
// now we know the column, we need to find the lowest cell in that column that is empty
for (int y = GRID_ROWS-1; y >= 0; y-- ) { // let's start at bottom and move up to reduce computations
// for every cell, test if it is empty
if (grid[column][y].isEmpty()) {
// if found a valid cell, place current players token and exit the loop (break)
grid[column][y].setValue(currentPlayer);
coinPlaced = true;
break;
}
}
return coinPlaced;
}
void checkCoins() {
// scan the array for 4 of the same value in a row
for (int y=0; y < GRID_ROWS; y++) { // for every vertical row,
for (int x=0; x < GRID_COLUMNS; x++) { // for every horizontal cell in that row
//grid[x][y]
// I will leave this to you ;)
// keep in mind to check neighbors all you need to do is add or subtract 1 from the x or y value
// however when you are at the edge of the board be careful not to try and look at a neighbor that is off the edge, you will get a null pointer or an array out of bounds exception
if (x+1<GRID_COLUMNS) {
Cell toTheRight = grid[x+1][y];
}
// for each cell you could look at the 3 above the current, 3 below the current, 3 to the right and 3 to the left, 3 diagnal in each direction and then manually try and find 4 adjacent same color cells
// or a bit more complicated is a recursive solution that checks its 8 immediate neighbor and for each that match the center cell run the same function to test its 8 neighbors keeping track of the current inARowCount and returning true when it is found.
// would be a bit hard because you would need to make sure the second cell doesn't follow back to the original cell, and start an endless loop
}
}
}
void draw () {
background(1, 1, 1);
noStroke();
// draw all cells
for (int y=0; y < GRID_ROWS; y++) { // for every vertical row,
for (int x=0; x < GRID_COLUMNS; x++) { // for every horizontal cell in that row
grid[x][y].display(); // draw this cell
}
}
// draw next coin floating above the board, contrain its positon to above the board
fill(PLAYER_COLORS[currentPlayer]);
int currentMouseX = constrain(mouseX, BOARD_PADDING+COIN_RADIUS/2, BOARD_PADDING+(GRID_COLUMNS*CELL_SCALE)-COIN_RADIUS/2);
//currentMouseX = 40*(ceil(abs(currentMouseX/40)));
ellipse(currentMouseX, BOARD_PADDING/2, COIN_RADIUS, COIN_RADIUS);
}
// press any key to rest the game, probably want to test for a certain key here!
void keyPressed () {
setupBlankBoard();
}
// on press attempt to place a coin
void mousePressed() {
int currentMouseX = constrain(mouseX, BOARD_PADDING+COIN_RADIUS/2, BOARD_PADDING+(GRID_COLUMNS*CELL_SCALE)-COIN_RADIUS/2);
// determine what column we are over
int column = (currentMouseX - BOARD_PADDING)/CELL_SCALE;
// if choice is a valid coin placement
if (placeCoin(column)) {
// toggle players if a coin was placed
changePlayers();
// after each placement check win conditions
checkCoins();
}
}
Cell Class
class Cell {
int x, y;
int value; // 0 for empty, 1 for team 1, 2 for team 2 (constants defined at top of main file)
Cell(int x, int y) {
// default constructor to create empty cell
this(x, y, EMPTY_CELL);
}
// allows cell value to be set at creation
Cell(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
}
boolean setValue(int value){
value = constrain(value, EMPTY_CELL,PLAYER_2); // keeps it from setting a value outside of our range
if(this.value == EMPTY_CELL){
this.value = value;
return true; // placed
}
return false; // was not able to place it as there is already a value
}
boolean isEmpty(){
return this.value == EMPTY_CELL;
}
void display() {
fill(0, 0, 255);
rect(this.x, this.y, CELL_SCALE, CELL_SCALE);
// Draw Circle color based on current value, could simply just put fill(playerColors[this.value]); but this seems a bit more clear
if(this.value == EMPTY_CELL){
fill(PLAYER_COLORS[EMPTY_CELL]);
}else if(this.value == PLAYER_1){
fill(PLAYER_COLORS[PLAYER_1]); // red
}else if(this.value == PLAYER_2){
fill(PLAYER_COLORS[PLAYER_2]); // yellow
}
ellipse(this.x + CELL_SCALE/2, this.y + CELL_SCALE/2, COIN_RADIUS, COIN_RADIUS);
}
}

jCombobox giving incremental value error on jTable

I am having problems with my code below, the code below shows a jComboBox being populated, when i select an item from this list it is added to the jTable below it.
There is alos code to check for duplicate entries ont he table. If a duplicate entry is found it should increase the qty column by one and not create a seperate entry.
This is where the problem comes in, when I press the back button on this screen and go to a different screen and then come back via same route as the first time, I get an incrementally different qty added to the table row/cell.
I have also included the code that populates the Round Details depending on Round Drop selected from table, for reference, but Im fairly certain the problem lies in the below code. The navigation is as follows...
To get to the below screen... Round Drop panel table of round drops) >> click on table row and taken to associated round details panel >> pressing the Till button takes user to screen with code below...
Test results:
First pass through below code using navigation above gives results as expected
Second pass gives an initial value of 2 (instead of one), and duplicate row increases qty by 2 instead of one
Third pass gives an initial value of 3 (instead of one), and duplicate row increases qty by 3 instead of one
Fourth pass gives an initial value of 4 (instead of one), and duplicate row increases qty by 4 instead of one
...and so on.
Any help, guidance on solution or a better design would be hugely appreciated.
Thanks
/*************Code sample ********************************/
public void tillOperations(String sourceCall) {
final DefaultTableModel model = (DefaultTableModel)main.tillPanel.tblTillSale.getModel();
if (main.tillPanel.cmbTillProdSelect.getItemCount() < 1) {
for (int d = 0; d < roundStockObj.length ; d++) {
main.tillPanel.cmbTillProdSelect.addItem(roundStockObj[d].getDescription());
}}
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount() - 1);
main.tillPanel.cmbTillProdSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent f)
{
int qty = 1;
for (int index = 0; index < 4; index++) {
addSelectedItem[index] = "";
}
int row;
selectedItem = null;
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount() - 1);
selectedItem = main.tillPanel.cmbTillProdSelect.getSelectedItem();
for (int d = 0; d < roundStockObj.length; d++) {
if (selectedItem.equals(roundStockObj[d].getDescription())) {
addSelectedItem[0] = roundStockObj[d].getDescription();
addSelectedItem[1] = Integer.toString(qty);
addSelectedItem[2] = Double.toString(roundStockObj[d].getPrice()).trim();
addSelectedItem[3] = Double.toString(roundStockObj[d].getPrice()).trim();
//break;
}
}
if(model.getRowCount() == 0) { //check if model is empty
model.addRow(new String[]{addSelectedItem[0], addSelectedItem[1], addSelectedItem[2], addSelectedItem[3]});
}
else { //check if there is a duplicate row
int duplicateRow = -1;
for (row = 0 ; row < model.getRowCount(); row++) {
if(addSelectedItem[0].equals(main.tillPanel.tblTillSale.getModel().getValueAt(row,0))) {
duplicateRow = row;
break;
}
}
if(duplicateRow == -1) { //if there is no duplicate row, append
model.addRow(new String[]{addSelectedItem[0], addSelectedItem[1], addSelectedItem[2], addSelectedItem[3]});
}
else { //if there is a duplicate row, update
main.tillPanel.jLabel1.setText(addSelectedItem[1]);
DecimalFormat fmtObj = new DecimalFormat("####0.00");
int currentValue = Integer.parseInt(main.tillPanel.tblTillSale.getValueAt(row, 1).toString().trim());
int newValue = currentValue + 1;
Integer newValueInt = new Integer(newValue);
model.setValueAt(newValueInt, row, 1);
double unitPrice = Double.parseDouble(main.tillPanel.tblTillSale.getValueAt(row, 2).toString().trim());
double newPrice = newValue * unitPrice;
Double newPriceDbl = new Double(newPrice);
main.tillPanel.tblTillSale.setValueAt(fmtObj.format(newPriceDbl), row, 3);
}
}
main.tillPanel.tblTillSale.removeRowSelectionInterval(0, model.getRowCount() - 1);
for (int index = 0; index < 4; index++) {
addSelectedItem[index] = "";
}
}
});
//This code loads the specific Round Details, based on the selection form the round drops table
public void displayRoundDropDetails() {
DefaultTableModel model = (DefaultTableModel)main.selectRoundDropPanel.tblSelectRoundDrop.getModel();
if (!loaded) {
for (int d = 0; d < roundDropsData.length; d++) {
if (roundDropsData[d][0].equals(defaultRoundID)) {
model.addRow(new Object[]{roundDropsData[d][3], roundDropsData[d][2],
roundDropsData[d][4], roundDropsData[d][5]});
}
}
loaded = true;
}
main.selectRoundDropPanel.tblSelectRoundDrop.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
int row = 0;
row = main.selectRoundDropPanel.tblSelectRoundDrop.getSelectedRow();
for (int index = 0; index < roundDropsData.length; index++) {
if (roundDropsData[index][3].equals(
main.selectRoundDropPanel.tblSelectRoundDrop.getModel().getValueAt(row, 0))) {
main.roundDetailsPanel.txtRoundDetailsAddress.setText(roundDropsData[index][6] + "\n"
+ roundDropsData[index][7] + ", " + roundDropsData[index][8] + "\n" +
roundDropsData[index][9]);
main.roundDetailsPanel.lblRoundDetailsName.setText(roundDropsData[index][2]);
main.roundDetailsPanel.txtRoundDetailsInstuct.setText(roundDropsData[index][10]);
main.roundDetailsPanel.txtDropDetailsIn.setText(roundDropsData[index][4]);
main.roundDetailsPanel.txtDropDetailsOut.setText(roundDropsData[index][5]);
main.roundDetailsPanel.txtRoundDetailsInstruct.setText(roundDropsData[index][12]);
break;
}
}
Globals.CURRENT_COMPONENT = "selectRoundDropPanel";
showRoundDetailsPanel();
}
});
}
Try changing the listener for JComboBox. try using stateChangeListener.

Resources