Changing values in an array - java

Ok, so here are my codes (main method and method I'm trying to call)
I want my method "rotateRR" to basically take the value from board[0] and put it on [1] and keep doing that for that single row. For example:
old array -> [1][2][3][4][5] to become [5][1][2][3][4] <- what new array should look like.
but after I call my method, I put my regular input which should be "1 rr", but it returns the same array. I need to return the updated array from rotateRR method, but it doesn't let me add a return statement.
public class Numbrosia {
static int [][] board = new int[5][5];
public static void main(String [] args){
Scanner scan = null;
try{
scan = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e){
e.printStackTrace();
return;
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = scan.nextInt();
}
}
Scanner input = new Scanner (System.in);
while (true){
showBoard();
System.out.println("What's your move?");
int rowOrCol = input.nextInt();
String action = ("");
action = input.nextLine();
if (action.equals(rowOrCol + " rr")){
rotateRR(board);
System.out.println("The new board looks like: ");
//Im guessing I should put something here?
}
}
}
public static void showBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
System.out.print(board[row][col] + " ");
}
System.out.println(" ");
}
}
//METHODS
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
//Its not letting me add a "return" type, tells me it is a syntax error on and an invalid type

The main problem with the method is that it's not even doing what you described as the functionality:
public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
Should be changed to:
public static void rotateRR (int [][] board){
// Saves the last entry of board, because
// each entry should be shifted to the right
int[] temp = board[board.length - 1];
// Here you should only run till board.length - 2, because
// if you add 1 to i for accessing the next entry
// you can maximal access the entry with number board.length - 1
for (int i = 0; i < board.length - 1; i++){
board[i] = board[i+1];
}
// Set the first entry to temp
board[0] = temp;
}
So after that method your array you inserted as a parameter is changed the way you described above. Notice that you don't need a return type, since the change affects the original array (keyword call-by-reference).

You have made the function void therefore you cannot return anything from it. So what you need to do is change it from void to something like char * and then return the associated char * to solve your problem
Read this: http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html for any further doubts.

Change this:
public static void showBoard()
to this
public static return-type showBoard()

Related

How to change element in a matrix (2D array) using setter method?

I'm trying to make my personal sudoku generator in Java, but I have a problem with setter element method of the matrix.
Field Class:
public void setField(int [][] field){
this.field = Arrays.copyOf(field, field.length);
}
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
//Change the element of the field
public void setElement (int i, int j, int n) {
getField()[i][j] = n;
setField(getField());
}
Main:
// First Print
for (i = 0; i < field.getField().length; i++) {
System.out.println();
for (j = 0; j < field.getField()[i].length; j++)
System.out.print(field.getField()[i][j]);
}
System.out.println();
System.out.println("Select Row");
i = input.nextInt();
System.out.println("Select Column");
j = input.nextInt();
System.out.println("Put Number");
n = input.nextInt();
field.setElement(i,j,n);
// Second Print
for (i = 0; i < field.getField().length; i++){
System.out.println();
for (j = 0; j < field.getField()[i].length; j++)
System.out.print( field.getField()[i][j]);
}
I don't know why the second print is the same as the first one.
You are creating copies of the matrix in the setField and getField methods
public void setField(int [][] field){
this.field = Arrays.copyOf(field, field.length);
}
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
Doing that in the method setElement you:
get a copy of the original matrix.
change an element of the copy
set a copy of the original matrix
Here your code with comments explaining each step:
public void setElement (int i, int j, int n) {
// 1 - Get a copy of the original matrix
getField()
// 2 - Change an element of the copy
[i][j] = n;
// 3.a - get a copy of the original matrix
// 3.b - Set the copy
setField(getField());
}
So the final effect doesn't change the original matrix.
You can have the desired result doing the following:
public void setField(int [][] field){
this.field = field;
}
public int[][] getField() {
return field;
}
//Change the element of the field
public void setElement (int i, int j, int n) {
field[i][j] = n;
}
// you do a copy of internal array
public int[][] getField() {
return Arrays.copyOf(field, field.length);
}
// and then chane element of this copy
public void setElement (int i, int j, int n) {
getField()[i][j] = n;
setField(getField());
}
I ran your program. It is running ok. But, in the beginning, I was getting null pointer exception error. So, maybe you should consider changing following things:
Add private int[][] field = new int[3][3]; in MyBean class.
the main() method:
public static void main(String[] args) {
MyBean myBean = new MyBean();
myBean.setElement(0, 0, 113);
myBean.setElement(0, 1, 114);
myBean.setElement(0, 2, 115);
int i1,j1,n;
Scanner input = new Scanner(System.in);
//First Print
for (int i = 0; i < myBean.getField().length; i++) {
System.out.println();
for (int j = 0; j < myBean.getField()[i].length; j++)
System.out.print(myBean.getField()[i][j]);
}
System.out.println();
System.out.println("Select Row");
i1 = input.nextInt();
System.out.println("Select Column");
j1 = input.nextInt();
System.out.println("Put Number");
n = input.nextInt();
myBean.setElement(i1,j1,n);
//Second Print
for (int i = 0; i < myBean.getField().length; i++){
System.out.println();
for (int j = 0; j < myBean.getField()[i].length; j++)
System.out.print( myBean.getField()[i][j]);
}
input.close();
}

Parsing multiple ints from Joptionpane

Im trying to practice some java and I am confused. I am trying to enter in multiple numbers into a 3*3 array, however when I run my program I get a compliation error (Exception in thread "main"java.lang.NumberFormatException)? How can parse multiple ints from a Joptionpane into the arrays?
public static int[][] enterMatrix() {
String NumberstoParse = JOptionPane.showInputDialog("Enter list: ");
int UserInput = Integer.parseInt(NumberstoParse);
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = UserInput;
return matrix;
}
}
I think the main issue is when parsing the String from the JOptionPane. Integer.parseInt() sees the commas and throws NumberFormatException. Might be worthwhile to do some testing of this method, possibly with JShell!
Here, I have taken the input String "1, 2, 3, 4, 5, 6, 7, 8, 9" and used method split from class String to make an array of String that is split by (",\s+"). This means, split around the matching regular expression, which here is "a comma and one or more white space characters". Each individual String from the array is then processed with Integer.parseInt().
public static int[][] enterMatrix() {
String numberstoParse = JOptionPane.showInputDialog("Enter list: ");
String[] splitNumbers = numberstoParse.split(",\\s+");
int[][] matrix = new int[3][3];
int ctr = 0;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = Integer.parseInt(splitNumbers[ctr]);
ctr++;
}
return matrix;
}
Adding to what Alex already added below is the code which will take care of some border line issues there are some test cases include few test cases. The code is documented, I hope this helps...
public class Dummy
{
public static void main(String[] args)
{
String temp = "";
for(int x = 0; x <10; x++){
temp = temp + x+"";
int[][] matrix = enterData(temp);
System.out.println("Given Input:" + temp);
if(matrix != null){
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
System.out.println("-------------");
temp +=",";
}
}
//Once you understand the test cases, you can remove the argument and use the JOptionPane for input
public static int[][] enterData(String input)
{
//TODO: Please user JOPtionPane I have added this just to make the test cases work
//String input = JOptionPane.showInputDialog("Enter list: ");
//This will split the Input on the basis of ","
String[] inputArr = input.split(",");
//Variable has a counter which which will represent the number of inputs received
int inputArrCount = 0;
int[][] matrix = new int[3][3];
//If the size is greater than 9, then as u suggested an error is printed
if(inputArr.length > 9 ){
System.err.println("Number length > 9");
return null;
}
for(int i = 0; i <matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
//If to just track that inputArrCount never goes beyond the inputArr elements
if(inputArrCount < inputArr.length){
int temp = Integer.parseInt(inputArr[inputArrCount++]);
matrix[i][j] = temp;
}
}
}
return matrix;
}
}

How to display methods in the console that read from a file?

I need to be able to display the Average, ColumnTotal, Highest/Lowest in row, RowTotal. I'm not sure whether it depends on something I did in the methods themselves that has to be changed, or if I can simply that call them with the correct arguments to read from a file. The text file that it reads from basically just inputs two integers that are separated by a space on the same line, those are the arguments I would like to be able to input. I'm not entirely sure how to do this. This is just an assignment from a College text book basically amped up by my Instructor called "TwoDimArray" which I've been able to find many examples of online but none of them had the 'read from file' portion that I have to do here, they all just used a normal array input such as "int[][] array = {{22, 37, 48, 68}} for the main method. I'm going to include the entire program in order to show exactly what I need to be displayed via println. I've been thinking about how to do this for quite a few hours now and decided that I definitely need help. Any help would be greatly appreciated! Thanks ahead of time.
import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TwoDimArray {
private int arr[][];
public TwoDimArray() {
loadArray();
}
public void loadArray(){
/**
* loadArray() method loads user defined filename
* #return text file's contents
*/
String fileName = "";
try {
fileName = JOptionPane.showInputDialog("Enter file name: ");
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
return;
}
try {
Scanner in = new Scanner(new File(fileName));
int rows, cols;
rows = in.nextInt();
cols = in.nextInt();
arr = new int[rows][cols];
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
arr[i][j] = in.nextInt();
}
}
in.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "can not open " + fileName + " to read");
}
}
public int getArrayMaxValue(){
/**
* #return the max vale of the array
*/
int maxVal = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] > maxVal){
maxVal = arr[i][j];
}
}
}
return maxVal;
}
public int getArrayMinValue(){
/**
* #return the minimum value of the array
*/
int minVal = Integer.MAX_VALUE;
for(int i = 0; i < arr.length; ++i){
for(int j = 0; j < arr.length; ++j){
if(arr[i][j] < minVal){
minVal = arr[i][j];
}
}
}
return minVal;
}
public static int getTotal(int[][] array) {
int total = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
}
return total;
}
public static int getAverage(int[][] array) {
return getTotal(array) / getElementCount(array);
}
public static int getRowTotal(int[][] array, int row) {
int total = 0;
for (int col = 0; col < array[row].length; col++) {
total += array[row][col];
}
return total;
}
public static int getColumnTotal(int[][] array, int col) {
int total = 0;
for (int row = 0; row < array.length; row++) {
total += array[row][col];
}
return total;
}
public static int getHighestInRow(int[][] array, int row) {
int highest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] > highest) {
highest = array[row][col];
}
}
return highest;
}
public static int getLowestInRow(int[][] array, int row) {
int lowest = array[row][0];
for (int col = 1; col < array[row].length; col++) {
if (array[row][col] < lowest) {
lowest = array[row][col];
}
}
return lowest;
}
public static int getElementCount(int[][] array) {
int count = 0;
for (int row = 0; row < array.length; row++) {
count += array[row].length;
}
return count;
}
public static void main(String[] args){
/**
* what to put in int[][] array to allow println of average, getrowtotal,
* etc..
*/
int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(getAverage(array));
}
}
0) Create numbers.txt in the root of your project. This is the file you will load array from. Example content as follows (2 rows, 3 columns):
2 3
1 2 3
4 5 6
1) You don't need your explicitly created int[][] array = ??? because there is already existing private int arr[][] which will be automatically loaded from file after you type it's name as intended in TwoDimArray constructor.
2) Since main method located at the same class as private int arr[][], you can access this private array without public getter/setter, and get average value like this:
// you don't need following line at all
// int[][] array = ???;
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue()); // Max value: 5
System.out.println("Min value: " + twoDimArray.getArrayMinValue()); // Min value: 1
// Average value
System.out.println(getAverage(twoDimArray.arr)); // 3, because 21 / 6 = 3
3) You probably got confused because getArrayMaxValue is signed as public int, and got invoked as twoDimArray.getArrayMaxValue(), whereas getAverage is public static int and must be called in different way.
I suggest marking getAverage as public int instead of public static int, and use private int arr[][] instead of int[][] array provided from arguments, so you will be able to call it the same way you do with other methods:
// Somewhere up
public int getAverage() {
return getTotal(arr) / getElementCount(arr);
}
// In your main method
System.out.println(twoDimArray.getAverage());
Basically, what you have there is a jagged array, it is not a bidimensional array. I will explain you the idea, you do the rest. That it is not a bidimensional array. This is an array of array, in each position you are pointing to a new array of int. If you never instantiated a new array on each position, then you have a position with a null value.
So going back with your question, you should read the entire line with the two integers that are on the same line. Be sure that the line in your file has in the first line 2 numbers separated by a space.
Then use the next() method to get the complete string
String line = in.next();
String[] parts = line.split(" ");
int val1 = Integer.parseInt(parts[0]);
int val2 = Integer.parseInt(parts[1]);
For this question:
what to put in int[][] array to allow println of average, getrowtotal,
int[][] array = new int[4];
array[0] = new int[] {10,20,30,40,50};
array[1] = new int[] {60,71,80,90,91};
array[2] = new int[] {1};
Hope this helps
Now, what do you think you have in array[3]? The answer is: NULL
you already read the array from file in your method loadArray...
Use it instead of trying to load the same thing again, remove static modifier from all method and use field arr instead of parameter array
private int getTotal() {
int total = 0;
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
total += arr[row][col];
}
}
return total;
}
private int getAverage() {
return getTotal() / getElementCount();
}
private int getElementCount() {
int count = 0;
for (int row = 0; row < arr.length; row++) {
count += arr[row].length;
}
return count;
}
public static void main(String[] args) {
TwoDimArray twoDimArray = new TwoDimArray();
System.out.println("Max value: " + twoDimArray.getArrayMaxValue());
System.out.println("Min value: " + twoDimArray.getArrayMinValue());
System.out.println(twoDimArray.getAverage());
}

Merge sort 3 way java

I have to make a 3 way merge sort of an array. the array length is a in a power of 3, i.e. 3,9,27 etc. So I can use only one split function and not "left","mid","right".
Would like to get an answer how to repair it and why does not it work.
I have written the code, however don't know how to get it to work.
Here it is:
EDITED THE CODE, STILL DOES NOT WORK
public class Ex3 {
public static void main(String[] args) { //main function
Scanner in = new Scanner(System.in); //scanner
int size = in.nextInt();
int[] arr = new int[size];
for (int i = 0; i<arr.length; i++){
arr[i] = in.nextInt();
}
in.close();
arr = merge3sort (arr); //send to the function to merge
for (int i = 0; i<arr.length; i++){ //printer
System.out.print(arr[i]+ " ");
}
}
static int[] split(int[] m, int thirdNum) { //split function that splits to 3 arrays
int third[] = new int[m.length/3];
int third1[]=new int[m.length/3];
int third2[]=new int[m.length/3];
for(int i = 0; i<=m.length/3; i++)
third[i]=m[i];
for(int i=0; i<=m.length/3;i++)
third1[i]=m[i+thirdNum];
for(int i=0; i<=m.length/3;i++)
third2[i]=m[i+2*thirdNum];
return merge(third,third1,third2);
//return null;
}
static int minOf3(int[] a3) { //function that finds out how what is the index of the smallest number
int num0 = a3[0];
int num1 = a3[1];
int num2 = a3[2];
int idx = 0;
if(num0<num1 && num1<num2)
idx=0;
if(num1<num0 && num0<num2)
idx=1;
else
idx=2;
return idx;
}
static int[] merge(int[] th0, int[] th1, int[] th2) { //function that sorts the numbers between 3 arrays
int len0=th0.length;
int len1=th1.length;
int len2=th2.length;
int[] united = new int[len0+len1+len2];
int ind = 0; int i0=0; int i1=0; int i2=0;
while(i0<len0 && i1<len1 && i2<len2){
if(th0[i0]<th1[i1]){
if(th0[i0]<th2[i2]){
united[ind]=th0[i0];
i0=i0+1;
}//end inner if
else{
united[ind]=th2[i2];
i2=i2+1;
}//end inner else
}//end outer if
else{
united[ind]=th1[i1];
i1=i1+1;
}//end outer else
ind=ind+1;
}//end while
for (int i = i0; i < len0; i = i + 1) {
united[ind] = th0[i];
ind = ind + 1;
}
for (int i = i1; i < len1; i = i + 1) {
united[ind] = th1[i];
ind = ind + 1;
}for (int i = i2; i < len2; i = i + 1) {
united[ind] = th2[i];
ind = ind + 1;
}
return united;
}
static int[] merge3sort(int[] m) { //function that glues all together
if (m.length == 1) {
return m;
}
else{
return merge(merge3sort(split(m,m.length/3)),merge3sort(split(m,m.length/3)),merge3sort(split(m,m.length/3))); }
}
I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ololosh1.Ex3.split(Ex3.java:27)
at ololosh1.Ex3.merge3sort(Ex3.java:98)
at ololosh1.Ex3.main(Ex3.java:15)
Look at this part of your code:
for(int i = 0; i<=m.length/3; i++)
third[i]=m[i];
for(int i=0; i<=m.length/3;i++)
third1[i]=m[i+thirdNum];
for(int i=0; i<=m.length/3;i++)
third2[i]=m[i+2*thirdNum];
Arrays are indexed from 0 to length-1. Each third* array has length m.length/3. Therefore their index can only go up to m.length/3 - 1. Yet you are indexing up to and including m.length/3.
Once you get your application working correctly, you really should clean it up. There is a lot of redundancy. For example, you are using the expression m.length/3 multiple times in method split() but you are also passing that same value to it as an argument.

2D Array Methods & Demo

I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.

Categories