Looping Through 2D Array?

Jan 13, 2015

looping through 2d arrays.

This code works when printing '*' to show the number of elements in a 2d array:

static int [][] gameboard = new int[3][7];

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

for (int j = 0; j < gameboard[0].length ; j++) {

System.out.print("*");

Thread.sleep(1000);

but then this does not:

static int [][] gameboard = new int[3][7];

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

for (int j = 0; j < gameboard[i].length ; j++) {

System.out.print("*");

Thread.sleep(1000);

The difference is on the third line where i did gameboard[i] instead of gameboard[0]. I get a runtime error on the second one.

View Replies


ADVERTISEMENT

Creating Magic Square - 2D Array And Looping

Sep 12, 2014

How to create a MAGIC SQUARE, i just wanted to learn the logic of it .. with 2d array and looping..

View Replies View Related

Looping Doesn't Change Value

Apr 28, 2014

Write a program that asks the user for the low and high integer in a range of integers. The program then asks the user for integers to be added up. The program computes two sums:

The sum of integers that are in the range (inclusive), and the sum of integers that are outside of the range. The user signals the end of input with a 0.

Your output should look like this:

Sample input/output

In-range Adder Low end of range: 20
High end of range: 50
Enter data: 21
Enter data: 60
Enter data: 49
Enter data: 30
Enter data: 91
Enter data: 0
Sum of in range values: 100
Sum of out of range values: 151

This is my assignment and below is my code.

import java.util.Scanner;
class InRangeAdder {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int low, high, data=1, rangesum=0, outrangesum=0;

[Code] ....

The problem is that the program simply gives an output of 0 for both "rangesum" and "outrangesum". I don't quite understand why that is. Also i have a quick question, the program needs me to end the program when the value of data is 0 but in order to initialize it I need to give it a value. Usually I would give it a value of 0 like I have for rangesum and outrangesum but if I do the program does not run till the loop as it considers the value of data to be 0 and ends the program right away. What would be a work around to this and when do I need to have a value to initialize an integer? for example, I do not need a value for low and high. Is this because the program recognizes that a value is going to be defined but cannot do that for the other integers as they are inside a loop?

View Replies View Related

Looping Thread Out Of Sync

Dec 12, 2014

I have a program ive been working on and it works, but the flags in the runnables seem to shift the output down 1. for instance i commented playa3. start(); to see whats going on, if i just run playa1 i got no issues, as soon as i enable playa2, i get this output:

Game continues...
Dealer places King and Queen on the table.

Game continues...
Dealer places Queen and Ace on the table.
Player one with 'Ace' places his card on the table.
Player one with 'Ace' wins the current deal.
King Queen

Game continues...
Dealer places Queen and King on the table.
Player two with 'King' places his card on the table.
Player two with 'King' wins the current deal.
Queen Ace

the second time the dealer deals, player one places his cards on the table when he was supposed to do that for the first deal which he didnt. the last line there, (king queen) is just a print statement that is referring to the dealers hand that, that iteration is responding too. below is my code, i

import java.util.*;
import java.io.*;
import java.lang.*;

public class P5
{
public static int i, count, dealerFirstCard, dealerSecondCard, player1, player2, player3;
public static String cardSet [] = {"Ace","King", "Queen"};
public static volatile boolean dealerFinished= false;
public static volatile boolean playersFinished= false;

[code]....

View Replies View Related

Looping Through Objects Vector

Nov 11, 2014

I'm having some issues, trying to solve this problem in java. I want to print some election results, and i have to loop through a vector of objects and retrieve the partial sums of each party's seats for each constituency and the national results for each party. For now i can print the results per contituency, but i'm having problems in getting the national results. Like, adding the seats for labour party in Constituency A and B and C, etc, and print the sum. And do the same for conservative party.

This is what i have.

Java Code:

while (i < h.geral.size()) {
show += "Constituency - "
+ ((Party) h.geral.elementAt(i)).getConstituency() + "

[Code] .....

View Replies View Related

Unknown Looping Error

Oct 7, 2014

int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("");
}while( x + x == 22 );

When i put x+x==22 than it gives 2 values of x which are 10 and 11, they are wrong but when i put any other value like x+x==24 it just shows 1 value which is 10. I am not able to understand what mistake is there. I have been searching it for past whole month but didn't got any reason.

View Replies View Related

Infinitely Looping Code

Dec 14, 2014

The player is defined as having 8 attributes which are in the array. The user enter attribute ratings that are restricted between 1 and 10. The total number of attribute points per player to allocate is 60. So my checks are that the inputted numbers are between 1 and 10 and the sum of them is 60. I continue to get an infinite loop when the code hits the if statement defining jamesTotalQuarter != 60. The code works however if the total is 60. What I want it to do is if the total != 60 revert back to the top of the code to allow the user to re-input their ratings. I've tried different combinations of continue and break statements without the outcome I'm looking for.

[public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);

//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "

[code]....

View Replies View Related

Static Looping With Main

Oct 3, 2014

I have written a small program that creates a loop that only fails to continue once we reach a StackOverflowError exception. It looks just like:

class MyFirstApp {
static int counter;
public static void main(String[] args) {
counter++;
System.out.println(counter + " in main.");
roundAbout();
}

public static void roundAbout() {
counter++;
System.out.println(counter + " in roundAbout.");
main( new String[0] );
}
}

The idea of the program is to go between each method without using an object. Each time the method is entered the static int counter variable is incremented and outputted along with its respective loop. The loop does, however, fail eventually.

By calling the between the methods we build a tower of stack frames that eventually topples. The number of times this runs before the StackOverflowError occurs varies, though. Sometimes I get 6553, 6554 or something else close to these values.

Is there a way to pop a method of the stack or clear part of the stack so I can keep this going? I don't know where I would use this but it would be nice to know.

View Replies View Related

Looping And Month Printing

Oct 4, 2014

Im working on an assignment with the following instructions:

Create a Date class with the following capabilities:

a)Output the date in multiple formats such as
MM/DD/YYYY
June 14, 1992

b )Use overloaded constructors to create Date objects initialized with dates of the formats in part a).

You should only have 3 member data: integer month, integer day, and integer year. Also, you should have at least 2 constructors and 2 methods in your Date.java.

View Replies View Related

Looping Through While Loop With Switch Statement?

Sep 23, 2014

I am having a problem with looping a while loop that contains a switch statement. Here is my code:

package hw4jenningsd;
import javax.swing.*;
public class HW4JenningsD {

[Code].....

View Replies View Related

Swing/AWT/SWT :: Looping Back To JOptionPane

Apr 28, 2014

how to have an application restart if the user inputs an incorrect integer in a JOptionPane question? I know how to do it with the Scanner class but nothing I do seems to work. This is the beginning of my code:

import javax.swing.JOptionPane;
public class Pay {
public static void main(String[] args) {
String level = JOptionPane.showInputDialog("Please select your skill level: 1, 2, or 3");
int levelPick = Integer.parseInt(level);

[code]...

View Replies View Related

Exception Handing Endlessly Looping

May 7, 2014

I'm making a program to handle temperature conversion. All the math is working properly, but I'm having trouble with making a loop to not let the user proceed until a valid input is given. The expected input is a double, then a space (though I found using enter works as well), then a char to represent Fahrenheit or Celsius. If I run this piece of code in the entire program with proper input, it works. When I use an invalid input, the catch works, and the code loops, but then the user isn't allowed to enter a new input, so thirdTester stays as equal to 2, so the loop repeats indefinitely.

do{
try{
System.out.println("Enter the temperature (example: 98.35 F).");
temperature = keyboard.nextDouble();
unit = (keyboard.next().charAt(0));

[Code] ....

View Replies View Related

Paint Not Looping Until Boolean Is True

Jan 19, 2015

I have a piece of code for an applet that I want to run as the main applet code, and I want it to loop until a boolean is true, but it needs to paint while the code is looping. Here is the relevant part of my code ....

public void paint(Graphics g)
{
g.drawImage(background, 0, 0, this);
if(over == false)
{
tick();

[Code] ....

(I have tried replacing the if with a for, that does not work.)

View Replies View Related

Looping Through JTextFields And Storing Data In Arrays

Aug 6, 2014

I am working on my second javafx program and I am getting confused. The program that I am writing is a payroll calculator. A secondary window opens at the start of the program where the user first enters the number of employees and clicks submit to save the number and to close this window. Then, the user begins to enters the employee information (first name, last name, pay rate and hours worked) when the user clicks the NextEmp button, I want the data in the text fields to be entered into arrays for later use, then clear the fields for the next use. I am running into 2 issues. The first is the close event for the secondary window that pops up. I cannot figure out the syntax. The second issue that I am running into is the loop to store the data into the arrays. I believe I am getting the text field data correctly, but I cannot figure out how to stop the loop until the NextEmp button is pressed again.

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.input.KeyCode;

[Code] .....

View Replies View Related

Looping In Java - Encountered Endless Loop Of 2s

Jun 22, 2014

I was learning looping in Java and decided to try this code and then I encountered an endless loop of 2s. why is that? I believe this line count=count++ caused it.

class ForDemo{
public static void main(String []args){
int count;
for(count=2;count<=5;count=count++)
System.out.println("count is:"+count);
System.out.println("Done!");
}
}

View Replies View Related

Test Values Stored In 2D Arrays - Program Keeps Looping

Jan 13, 2014

I am trying to test values stored in 2d arrays once but i my program just keeps looping what am i doing wrong

Java Code:

tempi=i;
tempx=x;
for( i=0;i<3;i++) {
for( x=0;x<4;x++) {
if(rounded[i][x]<395 || rounded[i][x] >405) {
System.out.println("there is an error with probes "+rounded[i][x]);

[Code] .....

View Replies View Related

Android - Looping Through Parse Data / Assigning To ArrayAdapter

Apr 24, 2015

I am looping through data in Android, using Parse data. I came up with this as a way to get user information; the larger goal is to create a model of data that I can use in an array adapter, so I can create a custom list view (as described here [URL] .... In the example, the data are hard-coded, not pulled from a database.

public static ArrayList<Midwifefirm> getUsers() {
//Parse data to get users
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.orderByAscending(ParseConstants.KEY_PRACTICE_NAME);
query.findInBackground(new FindCallback<ParseUser>() {

[Code] ....

The intention is that for every user that does not have the type patient, collect this data about them, then store it in the arrayList.

On the return statement, though, there is an error: cannot return a value from a method with a void return type.

I may be over complicating this...read through various sources to get a model for this...in the end, I want to display a list of information about specific users, after the user makes a selection of a city...it would therefore display all the information about the medical practices in that city.

View Replies View Related

Player One Type A Number And Player Two Suppose To Guess - Infinite Looping

Apr 2, 2014

Its a basic program that is played by 2 people. Player one is suppose to type a number and the second player is suppose to guess the number. However after I test it out, and if I guess too low or too high I get stuck in "Your guess is too low, try again." infinite loop, what is wrong.

import java.io.*;
class GuessingGame
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
String firstPlayer, secondPlayer;
int firstInput, secondInput;
int guessCount = 0;

[Code] .....

View Replies View Related

Generate 10 Random Integers / Store In Array And Then Calling A Method To Display Array

Nov 8, 2014

So I need to generate 10 random integers in the range 1-20 but i have to store them in an array called numbers. Then I have to call a method called displayArray which displays the contents of the array and for the assignment i have to use a for loop to traverse the array. The method header for the displayArray method is:

public static void displayArray(int[] array)

This is what I have done
 
public class RandomIntegers {
 static int numbers = 0;
public static void displayArray(int[] array) {
System.out.println(numbers + "Numbers Generated");

[Code] .....

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

Blue Pelican Java - Array Of Hope - Char Array For Loops?

Feb 13, 2014

i am working on the same project and i got the code to make them print going down but not sideways.

public class ArrayofHope
{
public static void main(String args[])
{
System.out.println("Decimal Character
");
for(int j = 65; j <= 90; j++)
{
System.out.print(j);
System.out.println(" " + (char)j); //Character
}
}
}

View Replies View Related

Java Number Spiral - Creating 2D Array With Given Input Of Dimensions Of Array

Aug 3, 2014

I am working on a problem where i have to create a 2d array with given input of the dimensions (odd number) of array, along with a number within the array and to then print out all of the numbers surrounding that number.

Anyway, i am working on simply making the spiral, which should look like the one below.

n = 3

7 8 9
6 1 2
5 4 3

where the 1 always starts in the center with the 2 going to the right, 3 down, then left etc. etc. I was able to create the code by starting on the outer edges rather than the center and working my way to the middle, however my code always starts from the top left and goes around to the center where it needs to start from the top right. I am having trouble altering my code to meet this criteria. This is what i have thus far.

import java.io.*;
public class Spiral
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of elements : ");
int n=Integer.parseInt(br.readLine());

[Code] .....

View Replies View Related

Populate Array Using Nested Loops With Letter From A Until Y And Display Array To Screen

Nov 15, 2014

We were given a class lab that asks us to write a program that create a multidimensional array ( 5 x 5 ), populates the array using nested loops with letter from A until Y, and displays the array to the screen. and the result should look like this:

A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y

How to write this program.. I have tried all my best but the results are not coming like this..

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

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

Array Index OutOfBounds Exception While Moving Creature Through 2D Array

Oct 13, 2014

I am receiving an ArrayIndexOutOfBoundsException for the following code, which moves a creature through a 2D array maze. I have altered the clauses of the first if statement for the four direct methods (north, south, east, and west) multiple times (i.e. x + 1 >= 0 && x > 0 && x - 1 > 0 && x < array.length...etc). However, while the code occasionally runs, more often than that it returns this exception. Catching the exception seems like a poor workaround though if worst comes to worst I'll do that.

I included only the relevant functions of the code:

public boolean goNorth(char[][] array) {
boolean success = true;;
x = getX();
//x = this.x;
y = getY();
//y = this.y;
if ((x - 1 >= 0 && x - 1 < array.length)
&& (y >= 0 && y < array[x].length)) {

[Code] .....

View Replies View Related







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