Assistance with Java - java

please help me with the question below, I'm a beginner at programming trying to get my head around it
public class LandVille {
private int[][] land;
private boolean hasHouse;
public static void main(String args[]) {
LandVille landVille = new LandVille(3, 4);
landVille.displayLand();
}
// Task A - constructor
LandVille(int numRows, int numColumns) {
land = new int[numRows][numColumns];
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numColumns; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
// Task B
public void displayLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
System.out.print(land[i][j] + " ");
}
System.out.println();
}
}
// Task C
public void clearLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
}
From the main method, ask the player for the row and column of the land. The number of rows
and the number of columns should be greater than 0 and less than or equal to 10. If any input is
not correct, show an error message and ask for that input again.
If all inputs are correct, create an object of LandVille class from main method. The row and column
values are passed as the parameter of its constructor.

Here's the code to accept the values using Scanner class:
Scanner ob = new Scanner(System.in);
int row = 0, col = 0;
while(true)
{
System.out.println("Enter the number of rows:");
row = ob.nextInt();
if(row <= 10 && row > 0) break;
else System.out.println("Invalid input. Try again.");
}
while(true)
{
System.out.println("Enter the number of columns:");
col = ob.nextInt();
if(col <= 10 && col > 0) break;
else System.out.println("Invalid input. Try again.");
}
LandVille landVille = new LandVille(row, col);
The purpose of the while loop:
If the user enters an invalid number, then the loop continues, asking the user to enter again.
If the user enters a valid number, then the loop stops, and the program continues.
ob is an object of Scanner class, and calling ob.nextInt() allows the user to input a number. The links provided in the comments may help to understand.

I understand your request. Below is some code that does what you need.
First, you need to use the object Scanner to interact with the user.
Second, it is better to use the do ... while synthax. With it, the user will enter at least one time in the loop before quit it if the provide answer is correct.
Finally, others comments are in the code.
Best regards.
/* You need to use the object Scanner to interact with the user */
import java.util.Scanner;
public class LandVille {
private int[][] land;
private boolean hasHouse;
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int row = 0, col = 0;
// enter the number of rows
// loop until you enter the right row (row can be 1-10)
do {
System.out.print("Enter the number of rows:");
row = keyboard.nextInt();
} while (row > 10 || row <= 0);
// enter the number of colums
// loop until you enter the right col (col can be 1-10)
do {
System.out.print("Enter the number of columns:");
col = keyboard.nextInt();
} while (col > 10 || col <= 0);
// when the variables (row, col) are correct, then the object LandVille can be created.
LandVille landVille = new LandVille(row, col);
landVille.displayLand();
}
// Task A - constructor
LandVille(int numRows, int numColumns) {
land = new int[numRows][numColumns];
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numColumns; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
// Task B
public void displayLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
System.out.print(land[i][j] + " ");
}
System.out.println();
}
}
// Task C
public void clearLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
}

Related

I'm having trouble with jetbrains academy tasks

I'm supposed to do this.
Multi-dimensional array Cinema
The cinema has n rows, each row consists of m seats (n and m do not
exceed 20). The two-dimensional matrix stores the information on the
sold tickets, number 1 means that the ticket for this place is already
sold, the number 0 means that the place is available. You want to buy
k tickets to the neighboring seats in the same row. Find whether it
can be done.
Input data format
On the input, the program gets the number of n rows and m seats. Then,
there are n lines, each containing m numbers (0 or 1) separated by
spaces. The last line contains a number k.
Output data format
The program should output the number of the row with k consecutive
available seats. If there are several rows with k available seats,
output the first row with these seats. If there is no such a row,
output the number 0.
But I'm stuck at finding a proper if statement to find the same adjacent coordinates k number of times
import java.util.Scanner;
import java.util.*;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner= new Scanner(System.in);
int dim1=scanner.nextInt();
int dim2=scanner.nextInt();
int[][] twoDimArray=new int[dim1][dim2];
// for (int i = 0; i < twoDimArray.length; i++) {
// twoDimArray[i][i]=scanner.nextInt();
//System.out.println(Arrays.toString(twoDimArray[i]));
// }
for (int i=0;i<dim1;i++){
for (int j=0;j<dim2;j++){
int current=scanner.nextInt();
twoDimArray[i][j]=current;
}
}
/* for (int k = 0; k< dim1; k++)
{
for (int l= 0; l< dim2;l++)
{
System.out.print(twoDimArray[k][l] + " ");
}
System.out.println("");
}
*/
int seatsToBuy=scanner.nextInt();
for (int k = 0; k< dim1; k++)
{
for (int l= 0; l< dim2;l++)
{
if ((twoDimArray[k][l]==twoDimArray[k][l+1])&&l<dim2){
System.out.println(twoDimArray[k]);
break;
}
}
System.out.println("");
}
I modified your code a bit. Can you try the below modified code?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dim1 = scanner.nextInt();
int dim2 = scanner.nextInt();
int[][] twoDimArray = new int[dim1][dim2];
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
int current = scanner.nextInt();
twoDimArray[i][j] = current;
}
}
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
System.out.print(twoDimArray[i][j] + " ");
}
System.out.println();
}
int seatsToBuy=scanner.nextInt();
int minConsSeats = seatsToBuy - 1;
int rowNum = 0;
for (int k = 0; k< dim1; k++)
{
int count = 0;
for (int l= 0; l< dim2;l++) {
if (twoDimArray[k][l] == 0 && count == minConsSeats) {
count ++;
} else if (l+1 < dim2 && twoDimArray[k][l] == 0 && twoDimArray[k][l+1] == 0) {
count++;
}
}
if (count >= seatsToBuy) {
rowNum = k + 1;
break;
}
}
System.out.println("Available row number: " + rowNum);
}
}
First I'd name variables with expressive names, not i, j, k, etc ..
So first gather inputs, I think you did that fine, I just renamed variables:
Scanner scanner = new Scanner(System.in);
System.out.print("Number of Rows: ");
int nbRows = scanner.nextInt();
System.out.print("Number of Cols: ");
int nbCols = scanner.nextInt();
int[][] seats = new int[nbRows][nbCols];
for (int row = 0; row < nbRows; row++) {
System.out.println("Row " + row);
for (int col = 0; col < nbCols; col++) {
System.out.print("Col " + col +": ");
int availability = scanner.nextInt();
seats[row][col] = availability;
}
}
System.out.print("Number of Seats to buy: ");
int seatsToBuy = scanner.nextInt();
Then it is always useful to have a little sanity check on what was input, so here is a little snippet to print out the seats for debugging
for (int row = 0; row < nbRows; row++) {
for (int col = 0; col < nbCols; col++) {
System.out.print(seats[row][col] + " ");
}
System.out.println();
}
Then I would use the following algorithm:
starts a counter at the beginning of the row to keep track of the maximum number of adjacent seats (maxAdjacentSeatsInRow). Then go seat by seat, if it is available, then increment the counter. If it is not, reset the counter to zero.
If at any point the counter equals the required number of seats, then that row is the one you want to return:
int availableRow = -1;
for (int row = 0; row < nbRows; row++) {
int maxAdjacentSeatsInRow = 0;
for (int col = 0; col < nbCols; col++) {
if(seats[row][col] == 0)
maxAdjacentSeatsInRow++;
else
maxAdjacentSeatsInRow = 0;
if (maxAdjacentSeatsInRow == seatsToBuy) {
availableRow = row;
break; // break out of the col loop
}
}
if(availableRow >= 0) {
break; // break out of the row loop if we found a row
}
}
// print out result
if(availableRow == -1) {
System.out.println("No seats available");
} else {
System.out.println("Seats available at row: " + availableRow);
}
Sample output:
Number of Rows: 3
Number of Cols: 4
Row 0
Col 0: 1
Col 1: 1
Col 2: 1
Col 3: 1
Row 1
Col 0: 1
Col 1: 0
Col 2: 0
Col 3: 1
Row 2
Col 0: 1
Col 1: 1
Col 2: 0
Col 3: 0
Number of Seats to buy: 2
1 1 1 1
1 0 0 1
1 1 0 0
Seats available at row: 1
The row index in the answer is zero based.
Also don't hesitate to make methods it makes things easier to read. Here is a version of the same thing but with methods:
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of Rows: ");
int nbRows = scanner.nextInt();
System.out.print("Number of Cols: ");
int nbCols = scanner.nextInt();
int[][] seats = gatherSeatsInputs(nbRows, nbCols);
System.out.print("Number of Seats to buy: ");
int seatsToBuy = scanner.nextInt();
printSeats(seats);
int availableRow = findAvailableRow(seats, seatsToBuy);
if(availableRow == -1) {
System.out.println("No seats available");
} else {
System.out.println("Seats available at row: " + availableRow);
}
}
private static int[][] gatherSeatsInputs(int nbRows, int nbCols) {
int[][] seats = new int[nbRows][nbCols];
for (int row = 0; row < nbRows; row++) {
System.out.println("Row " + row);
for (int col = 0; col < nbCols; col++) {
System.out.print("Col " + col +": ");
int current = scanner.nextInt();
seats[row][col] = current;
}
}
return seats;
}
private static int findAvailableRow(int[][] seats, int seatsToBuy) {
for (int rowIndex = 0; rowIndex < seats.length; rowIndex++) {
if(rowHasEnoughSeats(seats[rowIndex], seatsToBuy)) {
return rowIndex;
}
}
return -1;
}
private static boolean rowHasEnoughSeats(int[] row, int seatsToBuy) {
int maxAdjacentSeatsInRow = 0;
for (int seatAvailability : row) {
if (seatAvailability == 0) {
maxAdjacentSeatsInRow++;
if (maxAdjacentSeatsInRow == seatsToBuy) {
return true;
}
} else {
maxAdjacentSeatsInRow = 0;
}
}
return false;
}
private static void printSeats(int[][] seats) {
for (int[] row : seats) {
for (int seat : row) {
System.out.print(seat + " ");
}
System.out.println();
}
}

How I can read how many mines are around each empty cell.Game minesweeper

The program below ask the user how many mines he wants to see on the field and then display the field with mines.
In next step I need to calculate how many mines are around each empty cell. And I know that I
need to check 8 cells if the cell is in the middle, 5 cells if the cell is in the side, and 3
cells if the cell is in the corner. If there are from 1 to 8 mines around the cell, I need to
output the number of mines instead of the symbol representing an empty cell.
import java.util.Scanner;
import java.util.Random;
public class Minesweeper {
char[][] minesweeper = new char[9][9];
Random randNum = new Random();
Scanner sc = new Scanner(System.in);
public Minesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
minesweeper[i][j] = '*';
}
}
}
public void printMinesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(minesweeper[i][j]);
}
System.out.println();
}
}
public void randomX() {
System.out.print("How many mines do you want on the field?: ");
int numberOfMines = sc.nextInt();
int i = 0;
while (i < numberOfMines) {
int x = randNum.nextInt(9);
int y = randNum.nextInt(9);
if (minesweeper[x][y] == '*') {
minesweeper[x][y] = 'X';
i++;
}
}
printMinesweeper();
}
}
You can do it like this:
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
public static void main(String[] args) {
Minesweeper minesweeper = new Minesweeper();
minesweeper.randomX();
minesweeper.printMinesweeper();
}
char[][] minesweeper = new char[9][9];
Random randNum = new Random();
Scanner sc = new Scanner(System.in);
public Minesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
minesweeper[i][j] = '*';
}
}
}
public void printMinesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(getCharAt(i, j));
}
System.out.println();
}
}
private String getCharAt(int i, int j) {
if (mineAt(i, j)) {
return "X";
}
int minesNear = countMinesNear(i, j);
return Integer.toString(minesNear);
}
private boolean mineAt(int i, int j) {
return minesweeper[i][j] == 'X';
}
private int countMinesNear(int i, int j) {
int mines = 0;
for (int x = -1; x <= 1; x++) {//near fields in x direction
for (int y = -1; y <= 1; y++) {//near fields in y direction
if (x + i >= 0 && x + i < minesweeper.length && y + j >= 0 && y + j < minesweeper.length) {//check whether the field exists
if (minesweeper[x+i][y+j] == 'X') {//check whether the field is a mine
mines++;
}
}
}
}
return mines;
}
public void randomX() {
System.out.print("How many mines do you want on the field?: ");
int numberOfMines = sc.nextInt();
int i = 0;
while (i < numberOfMines) {
int x = randNum.nextInt(9);
int y = randNum.nextInt(9);
if (minesweeper[x][y] == '*') {
minesweeper[x][y] = 'X';
i++;
}
}
printMinesweeper();
}
}
The countMinesNear(int, int) method check whether the field near exists (to prevent index errors on the edges) and counts the mines if the fields exist.

Crossed words game in Java

I have been stuck on this exercise for 2 weeks now, hopefully someone can help...
So basically the user starts by providing the number of lines and columns and the corresponding crossed words table(which is a 2d char array) , then inputs the number of words and the words that have to be detected in that board.
The program is supposed to print the table that was given but with every non-word substituted for zeros.
An example:
Input:
4 5
GBCDP
AGGGM
MYIEU
ENBHJ
2
GAME
JUMP
Should output:
G000P
A000M
M000U
E000J
My problem is still in the method for finding the words...
this is my code(it's commented to be easier to understand)
NOTE: the words cannot be found diagonally... also I am missing the part of the program that's supposed to substitute non-words for zeros, because I still can't find the words
import java.util.Scanner;
class game {
private int rows;
private int cols;
private char m[][];
game(int r, int c)
{
rows = r;
cols = c;
m = new char[r][c];
}
//read the game
public void read(Scanner in) {
for (int i=0; i<rows; i++) {
m[i] = in.next().toCharArray();
}
}
//writes the game
public void write() {
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols; j++)
{
System.out.print(m[i][j]);
}
System.out.println();
}
}
//finds the words
public void find(String word) {
for(int i = 0; i < rows; i++)
{
if(word.equals(new String(m[i]))){
System.out.print(i);
}
}
for(int z = 0; z < cols; z++)
{
if(word.equals(new String(m[z]))) {
System.out.print(z);
}
}
}
}
public class wordg {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
game j = new game(rows,columns);
j.read(scan);
//j.write();
int wordnumber = scan.nextInt();
String words[] = new String[wordnumber];
for(int i = 0; i < wordnumber; i++)
{
words[i] = scan.nextLine();
}
for(int w = 0; w < words.length; w++)
{
j.find(words[w]);
}
}
}
Thanks!
How to fix the code
In this part of the answer, I will try to give a step-by-step guide on how to make your code work properly:
The first problem with your code is that you are using the rows instead of the columns, although you obviously want to use columns. This can be done like this:
String col = "";
for(int i = 0; i < rows; i++) {
col += m[i][z];
}
The next problem is that you also have to search for the reversed words. You can do that by just calling the method find with the reversed words also:
for(int w = 0; w < words.length; w++)
{
j.find(words[w]);
j.find(j.reverse(words[w]);
}
The reverse-method could look like this:
public String reverse(String word) {
String result = "";
for(int i = word.length() - 1; i >= 0; i--) {
result += word.charAt(i);
}
return result;
}
After this, your find-method should work.
To output the grid like you want it to look like, we will have to save, where we found a word. This can be done like this:
if(word.equals(new String(m[i]))){
System.out.println("Word found in row: " + i);
for(int j = 0; j < cols; j++) {
test[i][j] = true;
}
}
test is a boolean-array initialized with false in the constructor.
Now we just have to change the write-method:
//writes the game
public void write() {
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols; j++)
{
if(test[i][j]) { //Only print found words, otherwise print "0"
System.out.print(m[i][j]);
}
else {
System.out.print("0");
}
}
System.out.println();
}
}
At this point the program should produce the output you want it to produce.
Possible improvements
If you want to improve your find-method, you could make the program recognize words inside a row or a column, for example recognize the word "YOU" in this grid:
AAYOUA
AAAAAA
AAAAAA
AAAAAA
This can be done like this:
public void find(String word) {
for(int i = 0; i < rows; i++) {
int index = new String(m[i]).indexOf(word); //Index were found word starts (-1 if row/col doesn't contain the word)
if(index >= 0) {
System.out.println("Word found in row: " + i); //Added some information for the user
for(int j = index; j < index + word.length(); j++) {
test[i][j] = true; //Save that word was found in this "cell"
}
}
}
for(int z = 0; z < cols; z++) {
String col = "";
for(int i = 0; i < rows; i++) { //Get column
col += m[i][z];
}
int index = col.indexOf(word);
if(index >= 0) {
System.out.println("Word found in col: " + z);
for(int j = index; j < index + word.length(); j++) {
test[j][z] = true;
}
}
}
}
Some other suggestions:
Class-names should begin with an uppercase-letter
Try to always use the same indentation
Try to always use the same "bracket-style"
(I changed this for you in the final code.)
Final code
All in all your code looks like this now:
Game.java
import java.util.Scanner;
public class Game { //Classes start with uppercase
private int rows;
private int cols;
private char m[][];
private boolean test[][]; //Purpose: test if "cell" where word was found
Game(int r, int c) {
rows = r;
cols = c;
m = new char[r][c];
test = new boolean[r][c];
}
//read the game
public void read(Scanner in) {
for (int i=0; i<rows; i++) {
m[i] = in.next().toCharArray();
}
}
//writes the game
public void write() {
for(int i = 0; i < rows;i++) {
for(int j = 0; j < cols; j++) {
if(test[i][j]) { //Only print found words, otherwise print "0"
System.out.print(m[i][j]);
}
else {
System.out.print("0");
}
}
System.out.println();
}
}
//finds the words
public void find(String word) {
for(int i = 0; i < rows; i++) {
int index = new String(m[i]).indexOf(word); //Index were found word starts (-1 if row/col doesn't contain the word)
if(index >= 0) {
System.out.println("Word found in row: " + i); //Added some information for the user
for(int j = index; j < index + word.length(); j++) {
test[i][j] = true; //Save that word was found in this "cell"
}
}
}
for(int z = 0; z < cols; z++) {
String col = "";
for(int i = 0; i < rows; i++) { //Get column
col += m[i][z];
}
int index = col.indexOf(word);
if(index >= 0) {
System.out.println("Word found in col: " + z);
for(int j = index; j < index + word.length(); j++) {
test[j][z] = true;
}
}
}
}
public String reverse(String word) {
String result = "";
for(int i = word.length() - 1; i >= 0; i--) {
result += word.charAt(i);
}
return result;
}
}
WordG.java
import java.util.Scanner;
public class WordG {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rows = scan.nextInt();
int columns = scan.nextInt();
Game j = new Game(rows,columns);
j.read(scan);
int wordnumber = scan.nextInt();
scan.nextLine(); //To clear the scanner
String words[] = new String[wordnumber];
for(int i = 0; i < wordnumber; i++) {
words[i] = scan.nextLine();
}
for(int w = 0; w < words.length; w++) {
j.find(words[w]);
j.find(j.reverse(words[w])); //You also have to search for reversed words!
}
j.write(); //Write grid after searching
}
}
(I added comments on the right where I changed your code to explain what I did.)
Output
With your example-input, this code creates the following output:
Word found in col: 0
Word found in col: 4
G000P
A000M
M000U
E000J
And with the added functionality, the input
5 5
SHARK
AYOUB
MABCD
EABCD
ABCDE
3
YOU
ME
SHARK
gives the output
Word found in row: 1
Word found in col: 0
Word found in row: 0
SHARK
0YOU0
M0000
E0000
00000

Showing Multiple Variables in Console with Scanner

The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}

Sorting Two-Dimensional Array by Row

The requirement is to sort the rows of a two-dimensional array. I feel like my code is very close to being done, but I can't figure out why it isn't displaying the sorted array. I forgot to mention that we are not allowed to use the premade sorting methods. The problem is most likely in the sortRows method. Anyways, here's my code:
public class RowSorting
{
public static void main(String[] args)
{
double[][] numbers = new double[3][3];
double[][] number = new double[3][3];
int run = 0;
String answer = "";
while (run == 0)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-by-3 matrix row by row: ");
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
numbers[row][column] = input.nextDouble();
}
}
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
System.out.print(numbers[row][column] + " ");
}
System.out.print("\n");
}
System.out.println("The sorted array is: \n");
number = sortRows(numbers);
for(int row = 0; row < number.length; row++)
{
for(int column = 0; column < number[row].length; column++)
{
System.out.print(number[row][column] + " ");
}
System.out.print("\n");
}
System.out.print("\nWould you like to continue the program (y for yes or anything else exits): ");
answer = input.next();
if(answer.equals("y"))
{
continue;
}
else
break;
}
}
public static double[][] sortRows(double[][] m)
{
for(int j = 0; j < m[j].length - 1; j++)
{
for(int i = 0; i < m.length; i++)
{
double currentMin = m[j][i];
int currentMinIndex = i;
for(int k = i + 1; k < m[j].length; k++)
{
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
}
if(currentMinIndex != i)
{
m[currentMinIndex][j] = m[j][i];
m[j][i] = currentMin;
}
}
}
return m;
}
}
It looks like this block:
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
Will never happen. Because you just assigned currentMin to m[j][i] two lines before it. I believe you want to use k in that if check. Something like
if (currentMin > m[j][k]){
currentMin = m[j][k];
currentMinIndex = k;
}
As cited per ergonaut, you have a problem with the codeblock
if(currentMin > m[j][i]) ...
and also
m[currentMinIndex][j] = m[j][i];
However, you also have a problem with your for-loops.
for(int j = 0; j < m[j].length - 1; j++) ...
for(int i = 0; i < m.length; i++) ...
Both of these are oddly structured. You probably want to swap these for-loops so that you don't throw index exceptions. This will also cause you address the indices in your code. And modify your j-index for-loop to include the entire range.

Categories

Resources