Adding number in two dimensional table - java

I got for example two dimensional table 3x2 where all element have got 4x minus :"----". If I write in program for example 32. The first number tells us what number it is and second how many number is in row.
it will make my table like this (32):
---- ---- 33-- ----
---- ---- -> ---- ----
---- ---- ---- ----
Then when we write another one (53): it will check table [0][0] if it is empty and if it is not it will be checked table [1][0] and table [0][1] if both are empty it will select table with lower number in this case table [0][1].
33-- ---- 33-- 555-
---- ---- -> ---- ----
---- ---- ---- ----
there we can put other numbers:
33-- 555- 33-- 555-
---- ---- -> 444- 22--
---- ---- 333- 222-
we insert number in empty place- when all place is not empty we insert number there where
is more "-" symbols - we take number 42 and in 33-- change it on 3344
33-- 555- 3344 555-
444- 22-- -> 444- 22--
333- 222- 333- 222-
if we want insert more number in place where is not enough "-"- program ends
I started like this:
import java.util.Scanner;
import java.lang.Math.*;
public class Skladisce2
{
public static int dolzina;
public static int sirina;
public static int enote;
public static int tabela[][][];
////////////////////////////////////
//// PREGLED VRSTIC
////////////////////////////////////
public static boolean Vstavi(int barva, int visina) {
int pozdolzina = 0;
int pozsirina = 0;
int najbolProsto = 0;
for(int j=0; j<dolzina; j++) {
for(int i=0; i<sirina; i++) {
int prosto=0;
for(int k=0;k<enote;k++) {
if( tabela[j][i][k]==0){
prosto++;
}
if( prosto>najbolProsto ) {
pozdolzina = i;
pozsirina = j;
najbolProsto = prosto;
for (int l=enote-najbolProsto; ((l<enote) &&(visina>0)); l++) {
tabela[pozdolzina][pozsirina][l] = barva;
visina--;}
continue;
}k++;
}
}
}
return true;
}
/////////////////////////////////////
//// IZPIS TABELE
//////////////////////////////////////
public static void Izpis() {
for (int i=0; i<dolzina; i++){
for (int j=0; j<sirina; j++){
for (int k=0; k<enote; k++) {
if(tabela[i][j][k] == 0) {
System.out.print("-");
}
else{
System.out.print(tabela[i][j][k]);
}
}
System.out.print(" ");
}
System.out.println();
}
}
public static void main (String[] args) {
Scanner vnos_stevila = new Scanner(System.in);
System.out.print("Insert dimension: ");
int vnos = vnos_stevila.nextInt();
// int vnos razdeli na podenote - prva številka je dolžina, druga širina in tretja enota
dolzina = Integer.parseInt(Integer.toString(vnos).substring(0,1));
sirina = Integer.parseInt(Integer.toString(vnos).substring(1,2));
enote = Integer.parseInt(Integer.toString(vnos).substring(2,3));
// izpis tabele s črtami
tabela= new int[dolzina][sirina][enote];
// izriše črtice
Izpis();
// VPIS SODOV
while (true){
System.out.print("Insert color and number");
int sod = vnos_stevila.nextInt();
int dolzinaIzpisa = (int)(Math.log10(sod)+1);
int barva = Integer.parseInt(Integer.toString(sod).substring(0,1));
int visina = Integer.parseInt(Integer.toString(sod).substring(1,2));
Vstavi(barva,visina);
Izpis();
}}
}
but when I insert number 32 it write:
33-- 33--
33-- 33--
33-- 33--
How can I make program where will check the lowest table and insert number?

It is simply a matter of searching for the best free slot and inserting there. You may also find it easier to think of what you have as a three dimensional array, not a 2 dimensional one.
import java.io.Console;
public class ArrayDemo {
private final int sizeX, sizeY, sizeZ;
private final int[][][] values;
public ArrayDemo() {
this(2,3,4);
}
public ArrayDemo(int x, int y, int z) {
values = new int[x][y][z];
sizeX = x;
sizeY = y;
sizeZ = z;
for(int i=0;i<x;i++) {
for(int j=0;j<y;j++) {
for(int k=0;k<z;k++) {
values[i][j][k]=-1;
}
}
}
}
public boolean insert(int value, int count) {
// find first slot with enough room
int posX = -1;
int posY = -1;
int bestFree = 0;
// locate largest available slot
for(int j=0;j<sizeY;j++) {
for(int i=0;i<sizeX;i++) {
int free=0;
for(int k=0;k<sizeZ;k++) {
if( values[i][j][k]==-1 ) free++;
}
if( free>bestFree ) {
posX = i;
posY = j;
bestFree = free;
}
}
}
// did we find a slot?
if( bestFree<count ) return false;
// found slot, insert data
for(int k=sizeZ-bestFree;(k<sizeZ) && (count>0);k++) {
values[posX][posY][k] = value;
count--;
}
return true;
}
public String toString() {
StringBuilder buf = new StringBuilder();
for(int j=0;j<sizeY;j++) {
for(int i=0;i<sizeX;i++) {
if( i>0 ) buf.append(' ');
for(int k=0;k<sizeZ;k++) {
if( values[i][j][k]==-1 ) {
buf.append('-');
} else {
buf.append(Character.forDigit(values[i][j][k], 36));
}
}
}
buf.append('\n');
}
return buf.toString();
}
public static void main(String[] args) {
ArrayDemo array = new ArrayDemo();
Console cons = System.console();
while( true ) {
String in = cons.readLine();
in = in.trim();
if( in.length() != 2 ) {
cons.printf("Please supply two digits: value and number\n");
continue;
}
int inputVal = Character.digit(in.charAt(0),36);
int inputNum = Character.digit(in.charAt(1),36);
if( inputVal==-1 || inputNum==-1 ) {
cons.printf("Please supply two digits: value and number\n");
continue;
}
if( array.insert(inputVal,inputNum) ) {
cons.printf("Data inserted OK\n%s\n", array.toString());
} else {
cons.printf("Data could not be inserted. Finished. Final array is:\n\n%s\n",array.toString());
return;
}
}
}
}

Related

Magic Square Method needs to output if it is a magic square and the sum of rows and columns

I'm working on an assignment that takes a data file with a number matrix and determines if it is a magic square. If it is then it also needs to report the sum of the rows and columns. With the output:
The matrix is a magic square.
The sum of all the rows and columns is 34.
I'm not sure how to go about this with one method, I feel like its asking me to return 2 values. The closest I have came is by adding a System.out.println with the sum at the end of my method when it returns true.
But the issue with that is that my output is backwords:
The sum of all the rows and columns is 34.
The matrix is a magic square.
How do I get the sum when I've only been asked to create one method? Below is my code, the instructor gave the bottom 3 methods so I'm only concerned with the first 2.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class chp8magic
{
public static void main(String args[])
{
int matrix[][] = initMatrix();
printData(matrix);
if (isMagic(matrix)) {
System.out.println("The matrix is a magic square.");
}
else {
System.out.println("Not a magic square");
}
}
public static boolean isMagic(int[][] mat)
{
int n = mat.length;
int nSquare = n*n;
int M = (n*n*(n*n+1)/2)/n;
int sumRow = 0, sumColoumns = 0, sumPriDiag = 0, sumSecDiag = 0;
boolean[] flag = new boolean[n*n];
for(int row = 0; row < n; row++){
sumRow = 0;
sumColoumns = 0;
for(int col = 0; col < n; col++)
{
if( mat[row][col] < 1 || mat[row][col] > nSquare )
return false;
if(flag[mat[row][col]-1] == true)
return false;
flag[mat[row][col]-1] = true;
sumRow += mat[row][col];
sumColoumns += mat[col][row];
}
sumPriDiag += mat[row][row];
sumSecDiag += mat[row][n-row-1];
if(sumRow!=M || sumColoumns!=M)
return false;
}
if(sumPriDiag!=M || sumSecDiag!=M)
return false;
else
return true;
}
public static int[][] initMatrix()
{
int matrix[][];
Scanner filein = null;
try {
filein = new Scanner(new File("matrix.txt"));
int numRows = Integer.parseInt(filein.nextLine());
matrix = new int[numRows][];
parseData(matrix, filein);
filein.close();
return matrix;
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
if(filein != null)
filein.close();
return null;
}
}
public static void parseData(int matrix[][], Scanner in)
{
for(int r = 0; r < matrix.length; r++)
{
String splitLine[] = in.nextLine().split(" ");
matrix[r] = new int[splitLine.length];
for(int c = 0; c < matrix[r].length; c++){
matrix[r][c] = Integer.parseInt(splitLine[c]);
}
}
}
public static void printData(int matrix[][])
{
for(int r = 0; r < matrix.length; r++){
for(int c = 0; c < matrix[r].length; c++){
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Probably you just need to do:
System.out.println("is magic: " + isMagic);
System.out.ptintln("sum: " + sum);
However this is not really returning the values, just printing them. To return two values there are several options. You could return an object:
public class MagicSquareProperties {
private boolean magic;
private int sum;
public MagicSquareProperties(boolean magic, int sum) {
this.magic = magic;
this.sum = sum;
}
public boolean isMagic() {
return magic;
}
public int getSum() {
return sum;
}
}
// now to return both values: return new MagicSquareProperties(true, 34);
But in my opinion the best solution would be the following:
Create a class MagicSquare.
Add property declarations (e.g. private int sum).
Add a constructor, for example MagicSquare(File file), this constructor reads the file and populates the properties.
Add getters and setters if needed (e.g. getSum())
Execute the main method in another class and call new MagicSquare(...) to create a magic square object. Afterwards you can call the getters on the object whenever you need the value.

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

How to fill a multidimensional array dependant on variables

The program I am working on is a simple shipping program. What I am having difficulty with is populating a multidimensional array factoring in certain variables.
Example
320 items need to be shipped out to 1 receiver using different box sizes.
XL can hold 50 items
LG can hold 20 items
MD can hold 5 items
SM can hold 1 items
Use the least number of boxes so far.
Code
This is my code so far.
import java.util.Scanner;
public class Shipping {
public static void main(String [] args) {
Scanner kbd = new Scanner(System.in);
final int EXTRA_LARGE = 50;
final int LARGE = 20;
final int MEDIUM = 5;
final int SMALL = 1;
String sBusinessName = "";
int iNumberOfGPS = 0;
int iShipmentCount = 0;
displayHeading(kbd);
iShipmentCount = enterShipments(kbd);
int[][] ai_NumberOfShipments = new int [iShipmentCount][4];
String[] as_BusinessNames = new String [iShipmentCount];
for (int iStepper = 0; iStepper < iShipmentCount; iStepper++) {
sBusinessName = varifyBusinessName(kbd);
as_BusinessNames[iStepper] = sBusinessName;
iNumberOfGPS = varifyGPS(kbd);
calculateBoxes(ai_NumberOfShipments[iStepper],iNumberOfGPS, EXTRA_LARGE, LARGE, MEDIUM, SMALL);
}
//showArray(as_BusinessNames);
}
public static void displayHeading(Scanner kbd) {
System.out.println("Red River Electronics");
System.out.println("Shipping System");
System.out.println("---------------");
return;
}
public static int enterShipments(Scanner kbd) {
int iShipmentCount = 0;
boolean bError = false;
do {
bError = false;
System.out.print("How many shipments to enter? ");
iShipmentCount = Integer.parseInt(kbd.nextLine());
if (iShipmentCount < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
bError = true;
}
} while (bError == true);
return iShipmentCount;
}
public static String varifyBusinessName(Scanner kbd) {
String sBusinessName = "", sValidName = "";
do {
System.out.print("Business Name: ");
sBusinessName = kbd.nextLine();
if (sBusinessName.length() == 0) {
System.out.println("");
System.out.println("**Error** - Name is required\n");
} else if (sBusinessName.length() >= 1) {
sValidName = sBusinessName;
}
} while (sValidName == "");
return sValidName;
}
public static int varifyGPS(Scanner kbd) {
int iCheckGPS = 0;
int iValidGPS = 0;
do {
System.out.print("Enter the number of GPS receivers to ship: ");
iCheckGPS = Integer.parseInt(kbd.nextLine());
if (iCheckGPS < 1) {
System.out.println("\n**Error** - Invalid number of shipments\n");
} else if (iCheckGPS >= 1) {
iValidGPS = iCheckGPS;
}
} while(iCheckGPS < 1);
return iValidGPS;
}
public static void calculateBoxes(int[] ai_ToFill, int iNumberOfGPS) {
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++)
}
//public static void showArray( String[] ai_ToShow) {
// for (int iStepper = 0; iStepper < ai_ToShow.length; iStepper++) {
// System.out.println("Integer at position " + iStepper + " is " + ai_ToShow[iStepper]);
// }
//}
}
Change your definition of calculateBoxes() to also take an array that represents the volume of each of the boxes (in your case this will be {50, 20, 5, 1}:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
// while the remaining items to pack is greater than the current box size
while(iNumberOfGPS >= boxVolumes[iStepper]) {
// increment the current box type
ai_ToFill[iStepper]++;
// subtract the items that just got packed
iNumberOfGPS -= boxVolumes[iStepper];
}
}
}
Another way of calculating this (using / and % instead of a while loop) would be:
public static void calculateBoxes(int[] ai_ToFill, int[] boxVolumes, int iNumberOfGPS) {
// for each box size
for (int iStepper = 0; iStepper < ai_ToFill.length; iStepper++) {
if(iNumberOfGPS >= boxVolumes[iStepper]) {
// calculate the number of boxes that could be filled by the items
ai_ToFill[iStepper] = iNumberOfGPS/boxVolumes[iStepper];
// reset the count of items to the remainder
iNumberOfGPS = iNumberOfGPS%boxVolumes[iStepper];
}
}
}

java.lang.ArrayIndexOutOfBoundsException: 10 Array

I need some help with this one. I have trying to get this array to work properly but do not know what I am doing wrong. I am a noob to java and really need some help
private static int respondentID;
private static int count;
static void enterQuestions() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private String surveyName;
private boolean surveyStart = true;
private boolean surveyStop = true;
private String question [] = new String[10];
private int responses[][]= new int[10][10];
Scanner input = new Scanner(System.in);
// first overloaded constructor
public Phase2() {
this( "Customer Survey" );
respondentID = 0;
count = 0;
} // end
// second overloaded constructor
public Phase2( String title ) {
surveyName = title;
respondentID = 0;
count = 0;
} // end constructor Survey
// method to be called when a user starts filling out a survey ( surveyStart will have been set to "true" )
public int startSurveyCount( int ct ) { // parameter for testing only
if( surveyStart ) {
if( respondentID > 0 ) {
if( count >= respondentID ) {
count++;
} else {
setCount( getRespondentID() );
}
} else {
//test
setCount( ct );
count = getCount();
count++;
setCount( count - 1 );
}
}
return count;
} // end method
// method to be called when a survey is successfully
public int generateRespondentID() {
if( surveyStop ) {
//
count = getCount();
setRespondentID( count );
} else {
if( count < 2 ) {
count = 0;
respondentID = 0;
} else {
count--;
setCount( count );
}
}
return respondentID;
} // end method generateRespondentID
public void setRespondentID( int count ) {
// count is the number of completed surveys.
respondentID = count;
respondentID++; // and then incremented by 1.
} //end method
public int getRespondentID() {
return respondentID;
} // end method
public void setSurveyTitle( String title ) {
surveyName = title;
} // end method
public String getSurveyTitle() {
return surveyName;
} // end method
public void setCount( int ct ) {
count = ct;
} // end method
public int getCount() {
return count;
} // end method
public void setSurveyStart( boolean surveySt ) {
surveyStart = surveySt;
} // end method
public boolean getSurveyStart() {
return surveyStart;
} // end method
public void setSurveySubmit( boolean surveySub ) {
surveyStop = surveySub;
} // end method
public boolean getSurveySubmit() {
return surveyStop;
} // end method
public void logResponse(int respondentID, int questionNumber, int responseEntered)
{
responses[respondentID] [questionNumber-1] = responseEntered;
}
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no-1]+"Reply");
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}
else
{
System.out.print("Yes");
}
}
public void enterQuestion()
{
for (int i=0; i<10; i++)
{
System.out.println("Enter Question "+(i+1)+" : ");
question[i] = input.nextLine();
}
}
public void displayQuestionStats(int no)
{
int answer;
System.out.print("Question"+(no)+" : "+question[no-1]+" (0-No/1-Yes) : ");
answer = input.nextInt();
logResponse(respondentID, no, answer);
}
}
This is my tester
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println( "Below are the results of running the no–argument");
// demonstrates the no–arg constructor
Phase2 noArgSurvey = new Phase2();
System.out.printf( "The no–argument survey values are:\ntitle: %s\n"
+ "initial value of respondentID: %d\ncount: %d\n",
noArgSurvey.getSurveyTitle(), noArgSurvey.getRespondentID(),
noArgSurvey.getCount() );
// demonstrates the constructor with a title argument ( for user input of survey title )
System.out.println( "\nPlease enter a name for the survey" );
String inputTitle = input.nextLine();
System.out.println(); // inserts a blank line
Phase2 titleArgConst = new Phase2( inputTitle );
System.out.printf( "Survey Name is: %s\n"
+ "initial values of:\nrespondentID: %d\ncount: %d\n\n",
titleArgConst.getSurveyTitle(), titleArgConst.getRespondentID(),
titleArgConst.getCount() );
//respondent id test
System.out.println( "This will test the generateRespondentID method.\n\n"
+ "Enter the number of surveys that have been taken");
int testInt = input.nextInt();
// values for respondentID and count after 1 survey has been successfully submitted
System.out.println( "\nAssuming " + testInt + " surveys submitted");
Phase2 oneDone = new Phase2();
oneDone.startSurveyCount( testInt );
oneDone.generateRespondentID();
System.out.printf( "The Respondent ID is: %d\ncount: %d\n\n",
oneDone.getRespondentID(), oneDone.getCount() );
noArgSurvey.enterQuestion();
for(int i = 1; i <= 10; i++)
{
noArgSurvey.displayQuestionStats(i);
}
//Display The Inputs Entered by User
System.out.println("Result for Survey with Title \""+titleArgConst.getSurveyTitle()+"\" :");
for(int i=1; i<11; i++)
{
noArgSurvey.displaySurveyResults(i);
}
} // end main method
} // end class SurveyTest
Change loop condition to
for(int i = 1; i < 10; i++)
Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 use for(int i = 1; i < 10; i++) instead for iterating. or use arrayName.length length is a variable provided by JVM which gives you the size of array at runtime.
AS Vishrant mentioned *Java follows Zero indexing. So in your case question and responses array is of size 10 which means it will iterate from 0 to 9 *
in your tester class, you are trying to access 10th index in loop in 2 places
for(int i = 1; i <= 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=1; i<11; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
You should to write
for(int i = 0; i < 10; i++) (1)
{
noArgSurvey.displayQuestionStats(i);
}
for(int i=0; i<10; i++) (2)
{
noArgSurvey.displaySurveyResults(i);
}
EDIT Addition
public void displaySurveyResults (int no)
{
for (int j=0; j<10; j++)
System.out.print("Question"+(no)+" : " + question[no]+"Reply"); <<<--------- change [no-1] to [no]
if (responses[respondentID][no] == 0)
{
System.out.print("NO");
}

Random array of 1's and 0's using methods

I am trying to create a random sized array of 1's and 0's. I can get the program to run and compile if I remove the random aspect of the of it and enter the size of the array manually. For some reason when I bring in the random utility I can not get the program to compile.
mport java.util.Random;
public class Project1a {
int[][] sample={{0,0,1,1,1},
{1,1,0,1,1},
{1,1,1,0,1},
{0,1,0,1,1}};
int box[][];
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
int results[][] = new int [m][n];
int goodData = 1;
public static void main(String[] args){
analyzeTable();
printTable(results);
}
public void analyzeTable() {
int row=0;
while (row < sample.length) {
analyzeRow(row);
row++;
}
}
public void analyzeRow(int row) {
int xCol = 0;
int rCount = 0;
while (xCol < sample[row].length) {
rCount = analyzeCell(row,xCol);
results[row][xCol] = rCount;
xCol++;
}
}
int analyzeCell(int row, int col) {
int xCol = col;
int runCount = 0;
int rowLen = sample[row].length;
int hereData = sample[row][xCol];
while (hereData == goodData && xCol < rowLen) {
runCount++;
xCol++;
if (xCol < rowLen) { hereData = sample[row][xCol];}
}
return runCount;
}
public void printTable(int[][] aTable ) {
for (int[] row : aTable) {
printRow(row);
System.out.println();
}
}
public void printRow(int[] aRow) {
for (int cell : aRow) {
System.out.printf("%d ", cell);
}
}
}
Your class name conflicts with java.util.Random. Renaming your class is the easiest fix here.
the problem is you are declaring your instance variable in a block which makes it in-accessible in methods
check this : remove curly braces { } from here and the way you are accessing your results and goodData you need to declare them static
{ // remove this
Random randomNumbers = new Random();
int m = randomNumbers.nextInt(100);
int n = randomNumbers.nextInt(100);
static int results = new int [m][n];
static int goodData = 1;
} // remove this

Categories

Resources