looping through array - only first index printing - java

I want to loop through an array and print any values that are not null, here is the code I am trying to use:
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();
}
}
Array:
static String[] studentNamesArray = new String[10];
The problem is that it is only printing out index[0]. How can I fix this?
EDIT:
Here is my full code:
static void deleteStudent() {
boolean studentFound = false;
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for (i = 0; i < 10; i++) {
for (i = studentChoice + 1; i < studentNamesArray.length; i++) {
studentNamesArray[i - 1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount - 1;
studentNamesArray[studentNamesArray.length - 1] = null;
for (i = studentChoice + 1; i < 9; i++) {
for (int y = 0; y < 3; y++) {
studentMarksArray[i - 1][y] = studentMarksArray[i][y];
}
}
markArrayCount = markArrayCount - 1;
for (int y = 0; y < 3; y++) {
studentMarksArray[9][y] = 0;
}
}
}
if (!studentFound) {
System.out.println("There are no students stored");
}
}

Use the for-loop only to print the students names. And read the studentChoice once after you printed all the students. Otherwise it waits for input after printing the studentNamesArray[0]
System.out.println("Which student would you like to delete?");
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println(i + ": " + studentNamesArray[i]);
}
}
int studentChoice = input.nextInt();

Make sure that the contents of the array are not null, or they wont print out

Only reason I can see here, other elements should be null. You can make sure it as follows
for (int i = 0; i < 10; i++) {
if (studentNamesArray[i] != null) {
studentFound = true;
System.out.println("Which student would you like to delete?");
System.out.println(i + ": " + studentNamesArray[i]);
int studentChoice = input.nextInt();// you need to check this
}else{
System.out.println(i + ": " + studentNamesArray[i]);
}
}
But may be there is another reason. If input.nextInt() is take from Scanner, your program will wait there for a user input. Then you have to provide that input to continue. Make sure those things.

Related

Battleship Code Too Many Hits

This project was to make a 2d battleship project using arrays. If you hit, it makes an "X." If it's one slot away up, down, right, or left, it is "H" for hot. If it's two slots away, it's "W" for warm. "C" for cool for three slots, and miss for everything else.
Every time I go to test out my code, it works for the first time perfectly fine, but afterwards it marks every input as a hit, when it should mark it as "H", "W", "C", or "M."
import java.util.Scanner;
public class Battleship
{
public static void main ()
{
int rowLoc = 0;
int colLoc = 0;
int rowGuess;
int colGuess;
int guesses = 1;
int shipNum = 5;
//variable declaration
String[][] battleGrid = new String[10][10];
String[][] battleGridKnown = new String[10][10];
//grid declaration
System.out.println("Welcome to Battleship!\nFive ships are hidden in row 0-9 and columns 0-9.");
System.out.println("After each guess, you will been told if your guess was...");
System.out.println("- Hit (X)\n- Close (H for hot)\n- Somewhat close (W for warm)\n- Not that close (C for cool)\n- Miss (M).");
//welcome message
for (int r = 0; r < battleGrid.length; r++)
{
for (int c = 0; c < battleGrid[r].length; c++)
{
battleGrid[r][c] = "-";
}
}
//initializes what is in battleGrid by default
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
battleGridKnown[r][c] = "-";
}
}
//initializes what is in battleGridKnown by default
for (int k = 1; k <= shipNum; k++)
{
do
{
rowLoc = (int)(Math.random() * 10 + 0);
colLoc = (int)(Math.random() * 10 + 0);
} while(battleGrid[rowLoc][colLoc] == "S");
battleGrid[rowLoc][colLoc] = "S";
}
//sets ships and also the stuff around the ships
/*for (int r = 0; r < battleGrid.length; r++)
{
for (int c = 0; c < battleGrid[r].length; c++)
{
System.out.print(battleGrid[r][c] + "");
}
System.out.println("");
}
System.out.println("");
//test printer*/
while(shipNum > 0)
{
System.out.print("Enter your row guess (0-9): ");
Scanner in = new Scanner (System.in);
rowGuess = in.nextInt();
System.out.print("Enter your column guess (0-9): ");
colGuess = in.nextInt();
// enter row + column guesses
if (battleGrid[rowGuess][colGuess] == battleGrid[rowLoc][colLoc])
{
shipNum--;
battleGridKnown[rowGuess][colGuess] = "X";
System.out.println("Hit! There are " + shipNum + " ships remaining.");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc-- || rowGuess == rowLoc++ || colGuess == colLoc-- || colGuess == colLoc++)
{
battleGridKnown[rowGuess][colGuess] = "H";
System.out.println("Hot!");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc - 2 || rowGuess == rowLoc + 2 || colGuess == colLoc - 2 || colGuess == colLoc + 2)
{
System.out.println("Warm...");
battleGridKnown[rowGuess][colGuess] = "W";
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else if(rowGuess == rowLoc - 3 || rowGuess == rowLoc + 3 || colGuess == colLoc - 3 || colGuess == colLoc + 3)
{
System.out.println("Cool...");
battleGridKnown[rowGuess][colGuess] = "C";
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
else
{
System.out.println("Miss.");
System.out.println("Guess attempt number: " + guesses + ".");
for (int r = 0; r < battleGridKnown.length; r++)
{
for (int c = 0; c < battleGridKnown[r].length; c++)
{
battleGridKnown[rowGuess][colGuess] = "M";
System.out.print(battleGridKnown[r][c] + "");
}
System.out.println("");
}
System.out.println("");
}
guesses++;
}
System.out.println("Thank you for playing!\nYou found all the ships in " + guesses + " guesses.");
}
}

How to show the contents of an array correctly

I'm trying to make a test correction simulator, that the user enters the test feedback at first an then the numbers of students in the class, the name and finally the answers.But the problem is: when I try to show the student names and the answer...they are below the other.So how I can fix this?
This problem is because i'm making two for's instead of one?So i can't display the student names and the answer correctly?
And my other problem is the score of the students.How I make it for each student and show it on the side.
Check my Stack trace below for a better understanding:
import java.util.Scanner;
public class testArray {
public static void main(String[] args) {
int score = 0, n, i, j = 0;
Scanner sc = new Scanner(System.in).useDelimiter("\r\n");
System.out.print("How many students in the class?: ");
n = sc.nextInt();
String name[] = new String[n];
char answer[][] = new char[n][5];
float media[] = new float[n];
char testFeedback[] = new char[5];
int socreArray[] = new int[n];
System.out.println("--Type (a,b,c,d or e)--");
for (int g = 0; g < testFeedback.length; g++) {
System.out.print("TestFeedback | question[" + g + "]: ");
testFeedback[g] = sc.next().charAt(0);
}
for (i = 0; i < n; i++) {
System.out.print("Student name: ");
name[i] = sc.next();
for (j = 0; j < 5; j++) {
System.out.println("answer nº" + (j + 1) + ": ");
answer[i][j] = sc.next().charAt(0);
if (answer[i][j] == testFeedback[j]) {
score++;
}
}
System.out.println("Score: " + score);
}
System.out.println("\nGeneral report: ");
System.out.println("Student - answer - score");
for (i = 0; i < n; i++) {
System.out.println(name[i]);
}
for (j = 0; j < n; j++) {
System.out.println(answer[j]);
}
if (score > 3) {
System.out.println("Congratulations, you went well!");
} else {
System.out.println("Too bad, you need to study more.");
}
}
}
If I understood your question correct, to show names and answer you could use 1 for:
for (i = 0; i < n; i++) {
System.out.print(name[i] + ": ");
for(int j = 0; j < answer[i].length; j++) {
System.out.print(answer[i][j] + " ");
}
System.out.println();
}
To show score, you have to store it somewhere, for example in anotherarray or list.
Yeah the problem is that you're outputting the students in a loop THEN you're outputting the answers in another loop. This should happen in the same loop so that you output a student and their answers in the same loop cycle.
Given that your student array and answer array are the same size (each student has a corresponding answer at the same index), you could do this:
for(int i = 0; i < n; i++) {
System.out.println(student[i]);
System.out.println(answer[i]);
}
Storing data in two parallel arrays is a bit awkward because you have to make sure that you update them together. This would be a good time to think about using some extra classes to represent the entities in your project and keep related things together.
You need a string builder in your for loop above the System.out.println( "General Report" );
You don't need the next two for loops. Move the
System.out.println( "General Report" );
System.out.println( "Student - answer - score " );
above this loop.
and move if ( score > 3) else inside your loop as in below code. You can delete everything after this loop.
System.out.println("\nGeneral report: ");
System.out.println("Student - answer - score");
for (i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
System.out.print("Student name: ");
name[i] = sc.next();
for (j = 0; j < 5; j++) {
System.out.println("answer nº" + (j + 1) + ": ");
answer[i][j] = sc.next().charAt(0);
sb.append( String.valueOf(answer[i][j]) );
if (answer[i][j] == testFeedback[j]) {
score++;
}
}
System.out.println( name[i] + " - " + sb.toString() + " - " + score );
if (score > 3) {
System.out.println("Congratulations, you went well!");
} else {
System.out.println("Too bad, you need to study more.");
}
}

Converting a 2d String array to a 2d double array

I am making a project in which I need to put a certain precision(0.00 or 0.000) on values in a 2d array. The 2d array is a String and i want to convert it to double. But when I try, I get a NullPointerException, I don't know why.
Afterwards I want to again convert it to a String array.
print-method code:
public void printSheet() {
int start = 'a';
char letter = (char) start;
//kolomnamen
for (int i = 0; i < COLUMNS + 1; i++) {
if (i == 0) {
System.out.print(" ");
} else if (WIDTH != 0) {
String s = "";
for (int j = 0; j < WIDTH / 2; j++) {
s += "-";
}
s += (char) (letter + i - 1);
for (int j = 0; j < WIDTH / 2; j++) {
s += "-";
}
System.out.print(s + "\t");
}
}
System.out.println("\n");
for (int i = 0; i < sheet.length; i++) {
System.out.print(1 + i + "." + " ");
for (int j = 0; j < sheet[i].length; j++) {
double[][] voorlopig = null;
voorlopig[i][j] = Double.parseDouble(sheet[i][j]); //<-- problem
double d = voorlopig[i][j];
// String s = " " + sheet[i][j];
System.out.println(voorlopig);
double thaprez = (precision / precision) + (Math.pow(precision, 10)) - 1;
d = Math.floor(d * thaprez + .5) / thaprez;
String s = " " + voorlopig[i][j];
if (sheet[i][j] == null) {
System.out.print(s + "\t\t");
} else if (sheet[i][j].length() < 10) {
System.out.print(s + "\t");
} else {
System.out.print(s);
}
}
System.out.println("\n");
}
}
Thanks in advance.
Try to initialize your array double[][] voorlopig maybe like this:
double[][] voorlopig = new double[sheet.length][sheet.length];
You get NullPointerException because the array voorlopig was double[][] voorlopig = null;
double[][] voorlopig = null;
voorlopig[i][j] = Double.parseDouble(sheet[i][j]);
voorlopig is set to null, you'll get a NullPointerException.Initialize voorlopig before using it.

How to convert an array to String format without commas/brackets and add parentheses as values

I want to take the array of random values I've generated and print the aforementioned array with parentheses outside the longest run of the same number.
For example, if the array was [0,1,1,1,2,4,7,4] I'd like to receive 0(111)2474 as an output.
This is my code thus far.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax {
runMax = counter;
runMin = i - counter + 1;
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter - 1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
}
}
try this code:
import java.util.Arrays;
import java.util.Random;
public class Snippet {
/**
* This method will generate my random numbers for my array.
*
* #param min
* minimum random value wanted
* #param max
* maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
// Part 1 - Generate a random array of length 40 with random 1-6
// inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
// Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
// Counts the longest run of the same number. A run continues only when
// consecutive numbers have the same value.
// RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 0;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax) {
runMax = counter;
startCounter = i - counter +2;
// runMin = i-counter+1;
variableNum = array1[i];
endCounter = i+1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax
+ " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter
+ " and ends at " + endCounter);
for (int i = 0; i < array1.length; i++) {
if (i==startCounter) {
System.out.print("(");
}
System.out.print(array1[i]);
if (i==endCounter) {
System.out.print(")");
}
}
System.out.println();
// Prints the array with parentheses outside the longest run, if there
// is more than one max run, use the last one.
}
}
Okay. I think I have this. The first answer was close, but if you run the program a few times, you discover issues. There is a logic error somewhere in your above code, but I have a work around. I think it is how you get the endCounter. It seems to count odd. But I got the program to work as far as I can tell. Try this out. I have run it several times and it seems consistent.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax ){
runMax = counter;
runMin = i - counter ;// was plus one I cahnged this.
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter -1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
String output = "";// added this
for(int x = 0; x < array1.length; x++)
{
if( x == startCounter)
{
output += "("+array1[x];
}
else if( x == startCounter + runMax )
{
else if( x == startCounter + runMax )
{
if(x == array1.length-1)
{
output += ")";
}
else
{
output += ")"+array1[x];
}
}
else
{
output += array1[x];
}
}
System.out.print("\n"+output);
}
}
Here's a shorter, more generic solution. This method takes any array of ints and prints parenthesis around the longest run of numbers. If there are two runs of the same lengths it prints it around the first one.
public String makeString(int[] ints) {
if (ints.length == 0) return ""; // Quit early if there's nothing to do.
// Initialize variables.
int lastNumber = ints[0];
// We keep track of the all time best run. Defaults to first int found.
int bestStart = 0;
int bestRun = 1;
// ... as well as the current run.
int currentStart = 0;
int currentRun = 1;
String s = ""+ints[0];
// Starting from the second int, we check if the current run is continuing.
for (int i = 1; i < ints.length; i++) {
int current = ints[i];
// If the current run continues, we update currentStart/currentRun, else we reset it.
if (current == lastNumber) {
currentRun++;
} else {
currentStart = i;
currentRun = 1;
}
// Now we check if the currentRun is better than the best.
// If so, we update bestStart/bestRun.
if (currentRun > bestRun) {
bestStart = currentStart;
bestRun = currentRun;
}
lastNumber = current;
s += current;
}
// Now that we've found it, we insert parenthesis aaaaaaand we're done!
return s.substring(0, bestStart)
+"("+s.substring(bestStart, bestStart+bestRun)+")"
+s.substring(bestStart+bestRun);
}

Array count logic error

Made some edits to the code to try and figure out why my X's [-1] are not being included in finding my average for that row. That is throwing of my averages. Any idea why It is not counting my -1's?
output[expected]:
USER INPUT: 3
O O O
X X X
X X X
TOTAL OPENNESS OF [I][J] = 1
TOTAL OPENNESS OF [I][J+1] = 2
TOTAL OPENNESS OF [I][J+2] = 1
TOTAL SUM AVERAGE FOR THAT ROW = 1.3
HOWEVER..FOR ROW 2 AND ROW 3
TOTAL SUM AVERAGE FOR THOSE ROWS = 0
WHICH IS INCORRECT IT SHOULD = -1
public static void openfactor(char[][] mazeValue, int n){
for(int i = 1; i<=n; i++)
{
double rowAvg=0;
double totalRowAvg=0;
for(int j=1;j<=n;j++)
{
int count=0;
int totalOpeness=0;
int totalRowOpeness = 0;
//double rowAvg=0;
if(mazeValue[i][j]=='X'){
System.out.println("tHIS IS AN X FOR : [" + i + "]" +"[" + j + "] IS -1 ");
count = -1;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=1)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1 && j-1>=1)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n && i+1<=n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<=n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=1 && i+1<=n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=1 && j+1<=n)
{
if(mazeValue[i-1][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " +totalOpeness);
totalRowOpeness = totalRowOpeness + totalOpeness;
//}//eND OF iF CONDITION\
}
rowAvg = (double)totalRowOpeness/(double)n;
System.out.println("ROW AVERAGE: "+rowAvg);
totalRowAvg = totalRowAvg + rowAvg;
System.out.println("SUM ROW AVERAGE: "+totalRowAvg);
}
System.out.println("TOTAL SUM ROW AVERAGE: " +totalRowAvg);
}
}
public static void printMaze(char mazeValue[][]) {
System.out.println("MAZE");
for (int i = 1; i < mazeValue.length; i++) {
for (int j = 1; j < mazeValue[i].length; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n + 1][n + 1];
System.out.println("ENTER A PATH: ");
for (int i = 0; i < mazeValue.length; i++) {
for (int j = 0; j < mazeValue[i].length; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
mazeValue[i][j] = 'X';
else {
mazeValue[i][j] = kbd.next().charAt(0);
}
}
}
printMaze(mazeValue);
horizontalPath(mazeValue, n);
System.out.println(" ");
verticalPath(mazeValue,n);
System.out.println(" ");
openfactor(mazeValue, n);
}
}
I do not completely understand what u want to accomplished but I am going to to assume you want to find repeated values, do this using some search algorithm below is an example of a binary search. Hope it helps.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Here's the complete code for your request. you need to reorder your if statements a little bit your logic was right:
and here is the output :
MAZE
O O X
O O O
X X O
TOTAL OPENESS FOR : [0][0] IS 3
TOTAL OPENESS FOR : [0][1] IS 4
THERE IS AN X HERE FOR : [0][2]
Average of O's in this row is : 66.66667%
TOTAL OPENESS FOR : [1][0] IS 3
TOTAL OPENESS FOR : [1][1] IS 5
TOTAL OPENESS FOR : [1][2] IS 3
Average of O's in this row is : 100.0%
THERE IS AN X HERE FOR : [2][0]
THERE IS AN X HERE FOR : [2][1]
TOTAL OPENESS FOR : [2][2] IS 2
Average of O's in this row is : 33.333336%
here's the code:
import java.util.Scanner;
public class sof {
public static boolean IsOutOfBound(int i, int j, int n)
{
if (i-1<1 || j-1<1 || i+1>n || j+1>n)
return true;
else
return false;
}
public static void openfactor(char[][] mazeValue, int n)
{
for(int i = 0; i<n; i++)
{
int TotalCounts=0;
for(int j=0;j<n;j++)
{
int count=0;
if(mazeValue[i][j]=='X'){
System.out.println("THERE IS AN X HERE FOR : [" + i + "]" +"[" + j + "] ");
//TotalCounts--;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=0)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0 && j-1>=0)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n && i+1<n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=0 && i+1<n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=0 && j+1<n)
{
if(mazeValue[j+1][i-1]=='O')
count++;
}
// System.out.println("cout: "+count);
//totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " + count);
TotalCounts++;
}//END OF else CONDITION
}//End of J loop
float Average = ((float)TotalCounts/(float)n) * 100;
System.out.println("Average of O's in this row is : " + Average+ "%");
}//End of I loop
}
public static void printMaze(char mazeValue[][],int n) {
System.out.println("MAZE");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for (int i = 0; i <n; i++) {
for (int j = 0; j < n; j++) {
//if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
// mazeValue[i][j] = 'X';
// else {
mazeValue[i][j] = kbd.next().charAt(0);
// }
}
}
printMaze(mazeValue,n);
openfactor(mazeValue, n);
}
}

Categories