matrix manipulation in java OOP - java

This code gives me errors at lines 153, 158 and 163 stating"variables not found". i need to print them using the menu but not sure if this is working. help would be appreciated.
import java.io.*;
import java.util.*;
class Matrix {
double[][] element;
int rows, cols;
Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
element = new double[rows][cols];
}
public double getValue(int row, int col) {
return element[row][col];
}
public void setValue(int row, int col, double value) {
element[row][col] = value;
}
public int getNoRows() { // returns the total number of rows
return rows;
}
public int getNoCols() { // returns the total number of cols
return cols;
}
// The methods for the main calculations
public Matrix AddMatrix(Matrix m2) {
int row1 = getNoRows();
int col1 = getNoCols();
Matrix result = new Matrix(row1, col1);
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
result.setValue(i, j, this.getValue(i, j) + m2.getValue(i, j));
}
}
return result;
}
public Matrix MultiplyMatrix(Matrix m2) {
if (this.getNoCols() != m2.getNoRows()) {
throw new IllegalArgumentException("matrices can't be multiplied");
}
int row2 = this.getNoRows();
int col2 = m2.getNoCols();
Matrix result = new Matrix(row2, col2);
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
result.setValue(i, j, result.getValue(i, j) + this.getValue(i, j) * m2.getValue(i, j));
}
}
return result;
}
public Matrix TransposeMatrix() {
int row3 = this.getNoCols();
int col3 = this.getNoRows();
Matrix result = new Matrix(row3, col3);
for (int i = 0; i < row3; i++) {
for (int j = 0; j < col3; j++) {
result.setValue(i, j, this.getValue(j, i));
}
}
return result;
}
public void DisplayMatrix() {
for (int i = 0; i < this.getNoRows(); i++) {
for (int j = 0; j < this.getNoCols();
j++) {
System.out.print((this.getValue(i, j)) + " ");
}
System.out.print("\n");
}
System.out.print("\n");
}
}
public class Lab1 {
public static void main(String args[]) throws FileNotFoundException {
int choice;
Scanner in = new Scanner(System.in);
Boolean loopcont= true;
while (loopcont){
System.out.println("1. Add two matrices \n");
System.out.println("2. Multiplymatrix two matrices \n");
System.out.println("3. Take transpose of a matrix \n");
System.out.println("4. Display a matrix \n");
System.out.println("5. Exit \n");
System.out.println("Enter your choice \n");
choice = in.nextInt();
switch (choice) {
case 1:{
System.out.println("For the first matrix");
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
System.out.println("For the second matrix");
Matrix m2 = MatrixReader();
m2.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.AddMatrix(m2);
m3.DisplayMatrix();
break ;
}
case 2:{
System.out.println("For the first matrix");
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
System.out.println("For the second matrix");
Matrix m2 = MatrixReader();
m2.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m2.getNoCols());
m3 = m1.MultiplyMatrix(m2);
m3.DisplayMatrix();
break;
}
case 3:{
System.out.println("For the first matrix");
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.TransposeMatrix();
m3.DisplayMatrix();
break;
}
case 4:{
int printInput;
System.out.println("What matrix do you want to print?");
printInput = in.nextInt();
switch(printInput){
case 1:{
System.out.println("Printing Matrix m1");
m1.DisplayMatrix();
break;
}
case 2:{
System.out.println("Printing Matrix m2");
m2.DisplayMatrix();
break;
}
case 3:{
System.out.println("Printing Matrix m3");
m3.DisplayMatrix();
break;
}
default:{
System.out.println("Invalid Input. please enter again");
break;
}
}
}
case 5:{
loopcont= false;
break;
}
default:{
System.out.println("Incorrect input. Kindly enter again \n");
break;
}
}
}
}
public static Matrix MatrixReader() throws FileNotFoundException {
System.out.println("Give the filename for the matrix");
Scanner filescanner = new Scanner(System.in);
Scanner scanner = new Scanner(new File(filescanner.nextLine()));
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
Matrix test = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
test.setValue(i, j, scanner.nextDouble());
}
}
return test;
}
}

EDIT:
Under Case 4: variables m1, m2, m3 are not initialized.
Matrix m1;
Matrix m2;
Matrix m3;
switch (choice) {
case 1: {
System.out.println("For the first matrix");
m1 = MatrixReader();
m1.DisplayMatrix();
System.out.println("For the second matrix");
m2 = MatrixReader();
m2.DisplayMatrix();
m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.AddMatrix(m2);
m3.DisplayMatrix();
break;
}
case 2: {
System.out.println("For the first matrix");
m1 = MatrixReader();
m1.DisplayMatrix();
System.out.println("For the second matrix");
m2 = MatrixReader();
m2.DisplayMatrix();
m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.MultiplyMatrix(m2);
m3.DisplayMatrix();
break;
}
case 3: {
System.out.println("For the first matrix");
m1 = MatrixReader();
m1.DisplayMatrix();
m3 = m1.TransposeMatrix();
m3.DisplayMatrix();
break;
}
case 4: {
int printInput;
System.out.println("What matrix do you want to print?");
printInput = in.nextInt();
switch (printInput) {
case 1: {
System.out.println("Printing Matrix m1");
m1 = MatrixReader();
m1.DisplayMatrix();
break;
}
case 2: {
System.out.println("Printing Matrix m2");
m2 = MatrixReader();
m2.DisplayMatrix();
break;
}
case 3: {
System.out.println("Printing Matrix m3");
m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3.DisplayMatrix();
break;
}
default: {
System.out.println("Invalid Input. please enter again");
break;
}
}
}
case 5: {
loopcont = false;
break;
}
default: {
System.out.println("Incorrect input. Kindly enter again \n");
break;
}
}

If you tired to write your own code with matrix, just download library I developed. It can add, multiply, invert, transpond, calculate determinant and solve linear systems.
please check: Linear Math Library
This is open source you can download the source code too and look how in works.

Related

My Remove Method isn't Working

Create a program that keeps track of the following information input by the user:
First Name, Last Name, Phone Number, Age
Now - let's store this in a multidimensional array that will hold 10 of these contacts.
So our multidimensional array will need to be 10 rows and 4 columns.
You should be able to add, display and remove contacts in the array.
*/
import java.util.Scanner;
public class compLab2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] contacts = new String [10][4];
System.out.println("Select your options: \n");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact to list.");
System.out.println("2: Remove a contact from the list.");
System.out.println("3: Display contacts.");
System.out.println("0: Exit the list.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContacts(contacts);
break;
case 2:
removeContacts(contacts);
break;
case 3:
displayContacts(contacts);
break;
case 0:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
private static void addContacts (String [][] contacts) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
if (contacts[i][0] == null || contacts[i][0].equals(null)) {
contacts[i][0] = input.nextLine();
contacts[i][1] = input.nextLine();
contacts[i][2] = input.nextLine();
contacts[i][3] = input.nextLine();
boolean Inserted = true;
break;
}
}
}
private static void removeContacts(String [][] contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the contact you want to remove: ");
String removeContact = input.nextLine();
for(int i=0; i<contacts.length; i++){
for(int j = 0; j <contacts[i].length; j++){
if(contacts[i][j].equals(removeContact)) {
contacts[i][0]=" ";
contacts[i][1]=" ";
contacts[i][2]=" ";
contacts[i][3]=" ";
}
}
break;
}
}
private static void displayContacts(String [][] contacts) {
for (int i = 0; i< contacts.length; i++) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
You have to move your break inside the if condition(once element is remove break the loop) otherwise your first for loop will break in i=0 condition.
In if condition you have to check removeContact with contacts[i][j] because contacts[i][j] can be null.
Below you can find the code
if (removeContact != null) { //removeContact should not be null
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) { //removeContact is not null so check removeContact with contacts[i][j]
contacts[i][0] = " ";
contacts[i][1] = " ";
contacts[i][2] = " ";
contacts[i][3] = " ";
break; //break the loop once you remove
}
}
}
}
You should set null insteam of white space(" ")
if (removeContact != null) {
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) {
contacts[i][0] = null;
contacts[i][1] = null;
contacts[i][2] = null;
contacts[i][3] = null;
break;
}
}
}
}
Because you are checking null while adding a contact. So setting null will free a space in your array and will allow you to add a new contact to that space.
Also you should check null entry during displaying contacts
private static void displayContacts(String [][] contacts) {
for (int i = 0; i < contacts.length; i++) {
if (contacts[i][0] != null) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
An ArrayList with a custom class can solve this problem easily.

Matching array values with variables

In this code I have an array with 5 elements and each element contains a value. Below in the while loop, I'm trying to give the user 3 attempts to guess what number is contained in the array (the user enters their guesses). My problem is that I don't know how to make match the user's guess (stored in a variable choose) with the array values caja[i] to print whether the user won or lost depending on a correct or incorrect guess respectively.
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
Your problem is that you break out of your loop in every case:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
Instead of doing this (and printing the result after only the first comparison), you should have a Boolean indicating whether the number was found in the array:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
This way, you can check the variable and tell the user whether he won or lost.
Here are some additional suggestions. The answer by Alex (https://stackoverflow.com/a/36133864/6077352) is good. Please note the comments in the code.
import java.util.Scanner;
/** https://stackoverflow.com/q/36133524/6077352 */
public class GuessNumber {
public static void main(String[] args) {
int[] caja = new int[5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++) {
System.out.println(caja[i]);
}
System.out.println();
int tries = 3;
Scanner sc = new Scanner(System.in);// no need to create scanners in loop
while (tries-- > 0) {// count down tries
System.out.print("Please guess a number... ");
int guess = sc.nextInt();
boolean win = false;// flag to determine if won
for (int i : caja) {// iterate through array and check if guess is inside
win |= (i == guess);// when inside: win=true
}
System.out.println("Answer right? " + win);
System.out.println();
}
}
}
So if the user can attempt to get any of the values of the array you might to change your while loop to this one:
while (electionGame > 0) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
boolean ganaste = false;
for (int i = 0; i < caja.length; i++) {
o = o + 1;
if (choose == caja[i]) {
ganaste = true;
break;
}
}
if (ganaste)
System.out.println("Ganastes");
else
System.out.println("Perdiestes");
electionGame--;
}

Why is there StringOutofBoundException?

My code needs to read information from the textfile. And the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
Yes, I need to get # of rows and columns and also identify the number and location of 'X's. I'm almost done except my second constructor is giving me a StringOutOfBoundException in the line:
treasureLocations[location] = new Coord(i, j);
I need help only with the second constructor. Could smb please help me with that?
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
// COMPLETE THIS METHOD
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
// COMPLETE THIS METHOD
public TreasureMap(String fileName) throws Exception{
rows = 0;
cols = 0;
int treasures = 0;
char x = 'X';
Scanner data = new Scanner(new File(fileName));
while(data.hasNextLine())
{
String line = data.nextLine();
for (int i = 0; i < line.length(); i++)
{
if(x == line.charAt(i))
{
treasures++;
}
}
cols = line.length();
rows++;
}
int location = 0;
treasureLocations = new Coord[treasures];
Scanner temp = new Scanner (new File(fileName));
while(temp.hasNextLine())
{
String line = temp.nextLine();
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
// This method does not require modification
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
You should not use the for i as you do. Your i means the current row, doesn't it? So every time you input a line(temp.nextLine()), your i must be added one.
int i=0;
while(temp.hasNextLine())
{
String line = temp.nextLine();
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
++i;
}

Sorting Java Multidimensional Array

I'm trying to sort the contents of an array and while it seems to be working (no runtime errors; is performing sort tasks), the first 10 rows, while sorted, are not in order with the rest of the rows.
class coordSort.java
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class coordSort {
#SuppressWarnings({ "unchecked", "unused" })
public static void main (String args[]) throws IOException {
String xCoord, yCoord;
int coordSum;
Scanner input = new Scanner(System.in);
//Get x coordinate from user
System.out.print("Enter x coordinate: ");
xCoord = input.next();
//Get x coordinate from user
System.out.print("Enter y coordinate: ");
yCoord = input.next();
boolean sort = false;
char[] a = xCoord.toCharArray();
char[] b = yCoord.toCharArray();
//validate user input is a digit
if ( (Character.isDigit(a[0])) ) {
if(Character.isDigit(b[0]) ){
//digits entered - begin processing all coordinate values
sort = true;
}
}
//If validation failed, inform user
if(!sort){
System.out.println("Please enter a positive numeric value.");
}
if(sort){
//determine SUM of user entered coordinates
coordSum = Integer.parseInt(xCoord) + Integer.parseInt(yCoord);
//define coordinate array
String[][] coordUnsortedArray = new String[26][3];
int counter;
int commaCount;
String xCoordIn, yCoordIn;
int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;
//define input file
FileInputStream fileIn = new FileInputStream("coords.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fileIn));
for (int j = 0; j < coordUnsortedArray.length; j++){
counter = 0;
commaCount = 0;
//line from file to variable
String coordSet = reader.readLine();
//look for the second "," to determine end of x coordinate
for(int k = 0; k < coordSet.length(); k++){
if (coordSet.charAt(k) == ',') {
commaCount++;
counter++;
if (commaCount == 2){
break;
}
}else{
counter++;
}
}
//define x coordinate
xCoordIn = (coordSet.substring(2,(counter - 1)));
intXCoordIn = Integer.parseInt(xCoordIn);
//define y coordinate
yCoordIn = (coordSet.substring((counter),coordSet.length()));
intYCoordIn = Integer.parseInt(yCoordIn);
//coordinate calculations
sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt(yCoordIn);
coordDiff = sumCoordIn - coordSum;
//load results to array
coordUnsortedArray[j][0] = xCoordIn;
coordUnsortedArray[j][1] = yCoordIn;
coordUnsortedArray[j][2] = Integer.toString(coordDiff);
//Output Array (BEFORE SORTING)
//System.out.println((j + 1) + ") " + coordUnsortedArray[j][0] + " : " + coordUnsortedArray[j][1] + " : " + coordUnsortedArray[j][2]);
}
System.out.println("\n");
fileIn.close();
String[][] coordsSorted = new String[26][3];
//Sort array coordDiff, column 3
Arrays.sort(coordUnsortedArray, new ColumnComparator(2));
//Print the sorted array
for(int i = 0; i < coordUnsortedArray.length; i++){
String[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < row.length; j++) {
//System.out.print(row[j] + " | ");
coordsSorted[i][j] = row[j];
System.out.print(coordsSorted[i][j] + " : ");
}
System.out.print("\n");
}
}
}
}
class sortCoords.java --
import java.util.Comparator;
#SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}
//overriding compare method
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[columnToSort].compareTo(row2[columnToSort]);
}
//overriding compare method
public int compare1(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[columnToSort].compareTo(row2[columnToSort]);
}
}
I am trying to sort the array in numerical order by the 3rd column. The unsorted array is populated by a text file containing something like:
a,44,67
b,31,49
c,93,6
I am performing calculations on the array compared to user input and populating the array as follows:
44,67,101
31,49,70
93,6,89
I would like the sortedArray to output the following:
31,49,70
93,6,89
44,67,101
One possible confusion here:
return row1[columnToSort].compareTo(row2[columnToSort])
This is a string comparison, not a numerical one. If you sort based on strings, you will get different results than if you do by numbers - ie "1","10","100","9" vs 1,9,10,100
Check out Integer.parseInt and if you can't figure out the rest, feel free to ask more questions.
As spinning_plate stated. You need to compare their int values i.e. you need a cast there
int num1 = Integer.parseInt(row1[columnToSort]);
int num2 = Integer.parseInt(row2[columnToSort]);
if(num1 > num2)
return 1;
else
return 0;
Place this code in the compareTo method and check. Swap the return statements to sort in reverse order.
Also, adding some error checking in the compareTo method will make the code more efficient.
Ok, so after the assistance provided here, below is the solution that we found. Thanks again for the help everyone! Hopefully the code below helps someone else out.
Code for class1 --
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class coordSort {
#SuppressWarnings({ "unchecked" })
public static void main (String args[]) throws IOException {
String xCoordChar, yCoordChar;
int xCoord, yCoord, coordSum;
Scanner input = new Scanner(System.in);
//Get x coordinate from user
System.out.print("Enter x coordinate: ");
xCoordChar = input.next();
//Get x coordinate from user
System.out.print("Enter y coordinate: ");
yCoordChar = input.next();
boolean sort = false;
char[] a = xCoordChar.toCharArray();
char[] b = yCoordChar.toCharArray();
//validate user input is a digit
if ( (Character.isDigit(a[0])) ) {
if(Character.isDigit(b[0]) ){
//digits entered - begin processing all coordinate values
sort = true;
}
}
//If validation failed, inform user
if(!sort){
System.out.println("Please enter a positive numeric value.");
}
if(sort){
//Parse user input characters to Integers
xCoord = Integer.parseInt(xCoordChar);
yCoord = Integer.parseInt(yCoordChar);
//determine SUM of user entered coordinates
coordSum = xCoord + yCoord;
//define coordinate array
int[][] coordUnsortedArray = new int[26][3];
int counter;
int commaCount;
String xCoordIn, yCoordIn;
int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;
//define input file
FileInputStream fileIn = new FileInputStream("coords.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader (fileIn));
for (int j = 0; j < coordUnsortedArray.length; j++){
counter = 0;
commaCount = 0;
//line from file to variable
String coordSet = reader.readLine();
//look for the second "," to determine end of x coordinate
for(int k = 0; k < coordSet.length(); k++){
if (coordSet.charAt(k) == ',') {
commaCount++;
counter++;
if (commaCount == 2){
break;
}
}else{
counter++;
}
}
//define x coordinate
xCoordIn = (coordSet.substring(2,(counter - 1)));
intXCoordIn = Integer.parseInt(xCoordIn);
//define y coordinate
yCoordIn = (coordSet.substring((counter),coordSet.length()));
intYCoordIn = Integer.parseInt(yCoordIn);
//coordinate calculations
sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt (yCoordIn);
coordDiff = sumCoordIn - coordSum;
if (coordDiff < 0){
coordDiff = coordDiff * (-1);
}
//load results to array
coordUnsortedArray[j][0] = intXCoordIn;
coordUnsortedArray[j][1] = intYCoordIn;
coordUnsortedArray[j][2] = coordDiff;
}
fileIn.close();
System.out.print("\n");
System.out.println("Array Before Sorting:");
System.out.println("=====================");
//Array Before Sorting
for(int i = 0; i < coordUnsortedArray.length; i++){
int[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < (row.length - 1); j++) {
coordUnsortedArray[i][j] = row[j];
if(j < 1){
System.out.print(coordUnsortedArray [i] [j] + ",");
}else{
System.out.println(coordUnsortedArray [i] [j]);
}
}
}
System.out.print("\n");
System.out.print("\n");
//Sort array coordDiff, column 3
Arrays.sort(coordUnsortedArray, new ColumnComparator(2));
System.out.println("Array After Sorting:");
System.out.println("====================");
//Original Array After Sorting
for(int i = 0; i < coordUnsortedArray.length; i++){
int[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < (row.length - 1); j++) {
coordUnsortedArray[i][j] = row[j];
if(j < 1){
System.out.print(coordUnsortedArray[i][j] + ",");
}else{
System.out.println(coordUnsortedArray [i] [j]);
}
}
}
}
}
}
Code for class2 --
import java.util.Comparator;
#SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}
//Compare method
public int compare(Object o1, Object o2) {
int[] row1 = (int[]) o1;
int[] row2 = (int[]) o2;
int intRow1 = (row1[columnToSort]);
int intRow2 = (row2[columnToSort]);
return new Integer(intRow1).compareTo(new Integer(intRow2));
}
}

while loop for boolean user input

After getting the program to work for the most part (the help is appreciated :)). All I needed was to add the while loop so the user gets the menu option as many times he wants to. It starts giving me errors as "; expected" at the line where continue switches to false. Here is the code.
import java.io.*;
import java.util.*;
class Matrix {
double[][] element;
int rows, cols;
Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
element = new double[rows][cols];
}
public double getValue(int row, int col) {
return element[row][col];
}
public void setValue(int row, int col, double value) {
element[row][col] = value;
}
public int getNoRows() { // returns the total number of rows
return rows;
}
public int getNoCols() { // returns the total number of cols
return cols;
}
// The methods for the main calculations
public Matrix AddMatrix(Matrix m2) {
int row1 = getNoRows();
int col1 = getNoCols();
Matrix result = new Matrix(row1, col1);
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
result.setValue(i, j, this.getValue(i, j) + m2.getValue(i, j));
}
}
return result;
}
public Matrix MultiplyMatrix(Matrix m2) {
if (this.getNoCols() != m2.getNoRows()) {
throw new IllegalArgumentException("matrices can't be multiplied");
}
int row2 = this.getNoRows();
int col2 = m2.getNoCols();
Matrix result = new Matrix(row2, col2);
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
result.setValue(i, j, result.getValue(i, j) + this.getValue(i, j) * m2.getValue(i, j));
}
}
return result;
}
public Matrix TransposeMatrix() {
int row3 = this.getNoCols();
int col3 = this.getNoRows();
Matrix result = new Matrix(row3, col3);
for (int i = 0; i < row3; i++) {
for (int j = 0; j < col3; j++) {
result.setValue(i, j, this.getValue(j, i));
}
}
return result;
}
public void DisplayMatrix() {
for (int i = 0; i < this.getNoRows(); i++) {
for (int j = 0; j < this.getNoCols();
j++) {
System.out.print((this.getValue(i, j)) + " ");
}
System.out.print("\n");
}
}
}
public class Lab1 {
public static void main(String args[]) throws FileNotFoundException {
int choice;
Scanner in = new Scanner(System.in);
Boolean continue = true;
while (continue){
System.out.println("Enter your choice /n");
choice = in.nextInt();
System.out.println("1. Add two matrices \n");
System.out.println("2. Multiplymatrix two matrices \n");
System.out.println("3. Take transpose of a matrix \n");
System.out.println("4. Display a matrix \n");
System.out.println("5. Exit \n");
if (choice == 1) {
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m2 = MatrixReader();
m2.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.AddMatrix(m2);
m3.DisplayMatrix();
}
if (choice == 2) {
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m2 = MatrixReader();
m2.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m2.getNoCols());
m3 = m1.MultiplyMatrix(m2);
m3.DisplayMatrix();
}
if (choice == 3) {
Matrix m1 = MatrixReader();
m1.DisplayMatrix();
Matrix m3 = new Matrix(m1.getNoRows(), m1.getNoCols());
m3 = m1.TransposeMatrix();
m3.DisplayMatrix();
}
if (choice == 4) {
System.out.println("Will need to call the DisplyMatrix method for the object \n");
}
if (choice == 5) {
continue = false;
}
else {
System.out.println("Incorrect input. Kindly enter again \n");
}
}
}
public static Matrix MatrixReader() throws FileNotFoundException {
System.out.println("Give the filename for the matrix");
Scanner filescanner = new Scanner(System.in);
Scanner scanner = new Scanner(new File(filescanner.nextLine()));
scanner.nextLine(); // removes the first line in the input file
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());
String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
Matrix test = new Matrix(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
test.setValue(i, j, scanner.nextDouble());
}
}
return test;
}
}
Everything looks fairly good except
Boolean continue = true;
and
continue = false;
etc.
continue is a reserved word and may not be used as an identifier. Rename the variable to cont or something similar.
And by the way, I would recommend you to use boolean instead of Boolean in this application.
Also, I believe there is an error in your if-structures:
if (choice == 1)
...
if (choice == 2)
...
if (choice == 5)
...
else
...
The else branch will be taken in all cases when choice != 5 (that is, even when choice is 1, 2, 3, .... So perhaps you want to change it to
if (choice == 1)
...
else if (choice == 2)
...
else if (choice == 3)
...
else
...
Finally, you may also want to consider using a switch for the choice:
switch (choice) {
case 1:
...
break;
case 2:
...
break;
...
default:
...
}
I'm not sure if this may cause conflicts, but "continue" is also a statement within Java. Maybe, by changing the variable name of continue, your problem will be solved. The link attached refers to how continue is used as a statement within Java: http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html And what you could also do is make a switch() statement from the if() construction you have, but that's something of personal taste :)
To avoid getting the "m1 is already defined" error, write the switch like that (including the curly braces):
switch (choice) {
case 1: {
...
break;
}
case 2: {
...
break;
}
...
default: {
...
}
}
If you have converted to 'switch' then declare the 'Matrix m1 = null;' just before the switch statement. And in the initialization of each 'case' just use 'm1 = new MatrixReader()'. Do the same for 'm2' variable.

Categories

Resources