2D array trouble finding char element(s) - java

I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
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][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}

I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.

Related

Matrix diagonal

I would like to let you know that I'm new to this platform, I'm trying to solve this question, could anyone help me?
statement
The user must be prompted for the size of the matrix to be created. After user input, a square matrix is ​​created with the information obtained.
Example: The user entered the value 3 so we will have it.
[][][]
[][][]
[][][]
However, when printing the matrix on the screen, the diagonal must be filled with the values ​​1 and the value 0 for the other positions, but the diagonal must start on the right side. Example of the expected solution:
[0][0][1]
[0][1][0]
[1][0][0]
I think this question I would start by figuring out how to create the matrix with input, then I would probably keep some type of pointer that starts at the end of the first row as it is being built then I would decrement the pointer after each row till I am at index 0 of the last row with the pointer value in this case an integer.
I will code it below:
import java.util.*;
public class QuestionOne {
public static int[][] createMatrix(Integer n) {
int pointer = n - 1;
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pointer == j) {
matrix[i][j] = 1;
pointer--;
continue;
}
matrix[i][j] = 0;
}
}
return matrix;
}
public static void printMatrix(int[][] matrix, int n) {
for(int i = 0; i < n; i++) {
for(int k = 0; k< n-1; k++) {
System.out.print(matrix[i][k] + ",");
}
System.out.print(matrix[i][n-1]);
System.out.println("");
}
}
public static void main(String[] args) {
System.out.print("Enter a number for declaring size:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] mat = createMatrix(n);
printMatrix(mat, n);
}
}

How to break correctlly in the array?

I have a question about break the input, because my code is typing two times "-1" to stop the input, actually I want to type "-1" single time to stop the input and then to show the array output.
Below is my code:
import java.util.Scanner;
public class NewTMA {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt(sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line break, end by -1:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++) {
for (int j=0; j<column; j++) {
String line = sc.nextLine();
if ("-1".equals(line)) {
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Below is my output:
run:
enter row size
3
enter column size
2
Type float numbers two-dimensional array of similar type and size with line breaks. end by -1:
1.4
2.4
-1
-1
The result is:
1.4 2.4
0.0 0.0
0.0 0.0
BUILD SUCCESSFUL (total time: 13 seconds)
Actually I just want to type "-1" a single time to stop the input,but I don't know why the output is showing "-1" twice to stop it. Hope someone can help me find which part I am doing wrong. Thanks.
break breaks out of the inner-most loop, so the outer loop iterates again and hits the input read again.
To break out of the outer loop, use a label:
outerLoop: // label the outer for loop
for (int i=0; i<row; i++){
for (int j=0; j<column; j++) {
String line = sc.nextLine();
if ("-1".equals(line)) {
break outerLoop; // break from the outer for loop
}
...
}
You can use any java allowable name for the label (I just called it “outerLoop” for clarity)
Another approach would be putting a flag as an indication if the argument is met:
for (int i=0; i<row; i++){
/* this is the flag */
boolean isInputNegative = false;
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
isInputNegative = true;
break;
}
a[i][j]=Float.parseFloat(line);
}
/* here is the checking part */
if (isInputNegative) {
break;
}
}

how to print a triangle in java without inner stars

The following code gives me the results but I want to make it more simple so i can learn logic of different scenario
public class Pyramid {
public static void main(String[] args) {
for (int i = 0; i <= 5; i++) {
for (int x = 0; x < 5 - i; x++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
But now i want to make a triangle without inner stars and i am not getting a logic i am trying and thinking for hours i don't want full coding i just want a logic explanation so i can make it by my self it feels good
You want to print the first and last star in each row, so you need to check if k is the first or last value in your loop. Here's pseudocode:
for (int k = 0; k <= i; k++) {
[if k is first or last possible value]
[print star]
[else]
[print space]
}

2D Array in Java with number manipulation

My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}

How to stop a "ArrayIndexOutOfBounds" exception

Hi guys I've been learning java over the summer and this is the last assignment, and I'm stuck. The program is supposed to take 13 numbers that I enter, sort them and then find the index number of the greatest number that I input in the original array. I'm trying to see if my selection method works but every time I try to enter in the numbers I get an out of bounds error. This is kind of frustrating and I've been trying to find and answer for a couple of hours now. Any help would be greatly appreciated. Thanks!
import java.util.Scanner;
public class fmax
{
public static void main(String[] args)
{
int indmax;
int[] fmax = new int[13];
fillmax(fmax);
//System.out.println(fmax);
indmax = maxfmax(fmax);
//indmin = minfmax();
System.out.println(indmax);
}
public static void fillmax(int[] farray)
{
Scanner sc = new Scanner(System.in);
int i = 0;
for(i = 0; i < farray.length; i++)
{
farray[i] = sc.nextInt();
}
}
public static int maxfmax(int[] farray)
{
int[] copy = farray;
int j, x=0, i;
boolean flag = true;
int temp;
while(flag)
{
flag = false;
for( j = 0; j < copy.length -1; j++)
{
if(copy[j] < copy[j+1])
{
temp = copy[j];
copy[j] = copy[j+1];
copy[j+1] = temp;
flag = true;
}
}
for(i=0; i <= farray.length; i++)
{
if(farray[i] == copy[1])
x = i;
}
}
return x;
}
}
This line will throw the out of bounds exception.
for(i=0; i <= farray.length; i++)
Your termination condition is incorrect. Try this:
for(i=0; i < farray.length; i++)
so that you stop the loop before you go past the last index (farray.length - 1).
You defined the Lenght of the Array as 13 than you run this line:
for(i=0; i <= farray.length; i++)
This means you will go for the items fmax[13] which doesnt exist, because java starts counting at 0. So the hightest index is fmax[12]. You need to change your condition to something like that:
for(i=0; i < farray.length; i++)
or
for(i=0; i <= farray.length -1; i++)
In this case length for array is returning size of your array - but it starts with 1 not with zero.
i <= farray.length - causes out of bounds exception
u have to use - as was mentioned i < farray.length in your for loop
Array always has index beginning with zero and ending with length-1
for(i=0; i <= farray.length; i++)
Your terminating condition is wrong. It is trying to access element located at index length, which does not exist and hence you get the exception. It should be modified to something like below to make it work:
for(i=0; i < farray.length; i++)

Categories