So I help tutor an Algebra 2 class at my local high school, and the class is currently looking over matrices. Though not there, they will eventually get to multiplication of matrices. After taking Computer Science last year and learning Java, the teacher I help thought I should try to write a program to multiple matrices.
At the moment, I have up to defining the numbers for the first array that holds the information for the first matrix. However, I have a small issue. As represented by this picture:
the line asking for the index integers is being repeated after already recording the integers. I assume this is due to my layered for loops, but I can't be for certain. Usually new eyes see problems clearer. Any who could help me would be appreciated.
Code:
package matrixmultiplication;
import java.util.*;
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("What is the size of the first matrix?");
int matrix1Rows = matrixRows();
int matrix1Columns = matrixColumns();
int[] matrix1 = new int[matrix1Rows * matrix1Columns];
doubleSpace();
System.out.println("What is the size of the second matrix?");
int matrix2Rows = matrixRows();
int matrix2Columns = matrixColumns();
int[] matrix2 = new int[matrix2Rows * matrix2Columns];
doubleSpace();
if (matrix1Columns != matrix2Rows) {
System.out.println("These cannot be multiplied!");
System.exit(0);
} else {
matrix1Numbers(matrix1Rows, matrix1Columns);
}
}
public static int matrixRows() {
System.out.print("Rows:");
Scanner rowSc = new Scanner(System.in);
int rows = rowSc.nextInt();
return rows;
}
public static int matrixColumns() {
System.out.print("Columns:");
Scanner colSc = new Scanner(System.in);
int cols = colSc.nextInt();
return cols;
}
public static int[] matrix1Numbers(int rows, int cols) {
int[] numb = new int[rows * cols];
for (int j = 0; j <= numb.length; j += rows) {
for (int i = 1; i <= cols; i++) {
for (int k = 1; k <= rows; k++) {
System.out.println("What is the value for index ("
+ k + "," + i + ")?");
Scanner inp = new Scanner(System.in);
if (j + k <= numb.length) {
numb[j + k - 1] = inp.nextInt();
}
}
}
}
for (int i = 0; i < numb.length; i++) {
System.out.println(numb[i]);
}
return numb;
}
public static void doubleSpace() {
System.out.println();
System.out.println();
}
}
I use NetBeans 8.2 and the latest working version of Java for NetBeans.
I'm not familiar with the matrixmultiplication package, so I may be rambling here.
for (int j = 0; j <= numb.length; j += rows){
I'm not entirely sure what the outer for loop your have is for, but this most outer for loop causes you to ask for the values of the indices cols times more than you want.
I feel that you originally wanted to use this outer for loop to iterate through each row, and wasn't planning on having the second for loop iterating through cols perhaps?
Also, Kevin Anderson mentions this above. You might avoid this problem altogether if you return a double int array as opposed to storing all values in the matrix in a single dimension. I personally feel it would make more sense.
Just nitpicking, but I wouldn't make a new scanner every time you want to use one in a different method. You could just make a field at the top of your class, instantiate it once in your main method, and then pass it in as a parameter to all methods using the scanner.
Related
I have the following code in which a matrix is defined through system input:
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//define size of matrix
int size = in.nextInt();
int primeSum = 0;
int secSum = 0;
int[] matrix = new int[size*size];
//create matrix
for (int i=0; i<size*size;i++) {
matrix[i] = in.nextInt();
}
in.close();
//sum primary diagonal
for (int i=0; i < size*size;i += (size + 1)) {
primeSum = primeSum + matrix[i];
}
////sum secondary diagonal
// for (int i=(size - 1); i < size*size; i += (size - 2)) {
// secSum = secSum + matrix[i];
// }
System.out.println(Math.abs(secSum - primeSum));
}
}
The code above works in that it allows the user to define an NxN matrix through inputting N as the size - so in the case size = 2 the user would define 4 matrix elements. However, after commenting back in the code for the secondary diagonal, the scanner object keeps expecting input past 4 integers - I have no idea why this would affect the program as I close the input stream before that block of code is reached.
You wrote a potentially infinite loop. I.e. if size is not greater than 2, then i will count down or stay 0. You should cover these corner cases, then your code will be fine.
As far as I can see, you're emulating a two-dimensional array on a one-dimensional. This is something that's hard to understand and easy to mess up. You are better off with a two-dimensional array and some nested loops:
int[][] matrix = new int[size][size];
//create matrix
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
matrix[i][j] = in.nextInt();
}
}
// and so on...
Your this part of code:
for (int i=0; i<size*size;i++) {
matrix[i] = in.nextInt();
}
calls the method nextInt which demands for input as long as the array is filled.
package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop
I have an array a[5][5] and several values. I want to randomly assign values based on random percentages I create. For example one value is 6 and 25% of the elements in the array should have the value 6. With what I have so far: I created the random percentages and I'm able to randomly assign values for different elements in the array. My problem is: more than 25% of the elements have 6. My question is: How do I make sure that when assigning elements with 6, exactly 25% of the elements in the array a[5][5] have that value? I'm new to programming and tried several loops and ifs but nothing is working out for me. Please push me towards the right direction.
25% of 25 is about 6. It is not accurate. Here is a possible solution.
import java.util.Random;
import java.util.Scanner;
public class Matrix25 {
public static void main(String[] args) {
int[][] Matrix = new int[5][5];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number you want to fill the array to 25%: ");
int number = scanner.nextInt();
int percentage=25;
generateMatrix(Matrix,number,percentage);
printMatrix(Matrix);
}
public static void generateMatrix(int Matrix[][],int num, int perc) {
int n;
int max=Matrix.length*Matrix[0].length;
int[] numbers = new int[max];
Random rnd = new Random();
int m = (int)(max * (perc/100.0));
int x=num>m?m-1:m;
for(int i=0;i<max;i++)
numbers[i]=(i<x)?num:i+1;
for(int i=0;i<Matrix.length;i++)
for(int j=0;j<Matrix[i].length;j++) {
n=rnd.nextInt(max);
Matrix[i][j]=numbers[n];
numbers[n]=numbers[max-1];
max--;
}
}
public static void printMatrix(int Matrix[][]) {
for(int i=0;i<Matrix.length;i++) {
for(int j=0;j<Matrix[i].length;j++)
System.out.printf("%3d\t",Matrix[i][j]);
System.out.print("\n");
}
}
}
I would do it like this
import java.util.Random;
import java.util.Scanner;
class Random2darray {
/**
* #param args
*/
public static void main(String[] args) {
// Create array; you specified 5x5 but you probably shouldn't hard code like this
int[][] numbers = new int[5][5];
//Create a scanner to get user input
Scanner scanner = new Scanner(System.in);
//I am not doing anything to make sure they give a decimal so the program won't work
//right if you are not giving a decimal
System.out.println("How much do you want to fill? Enter a decimal.");
//Get a double
double populatePercentage = scanner.nextDouble();
System.out.println("What number do you want to fill with?");
//Get an int
int fillNumber = scanner.nextInt();
//Don't hardcode like this
int fillTimes = numberOfTimesToFill(25, populatePercentage);
//This is declared outside of the loops because otherwise it will be
//reset each time the loop runs
int count = 0;
//Create a random number generator; default seed is current time which is good enough for this
Random rand = new Random();
//Fill the array with numbers
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Check if you have filled with given number enough times
if(count < fillTimes){
numbers[i][j] = fillNumber;
//Increment count by 1; this is how you are keeping track
count++;
}else{
//Otherwise pick a random number generator
//This will pick a random int between 0 - 50 inclusive
int randomNumber = rand.nextInt(51);
//This will make sure that you are not generating random numbers that are the same
//as the number you are filling with; This says if it is the same generate a new number
while(randomNumber == fillNumber){
randomNumber = rand.nextInt(51);
}
//Once we know its random fill the spot in the array
numbers[i][j] = randomNumber;
}
}
}
//Print the array out
printArray(numbers);
}
private static void printArray(int[][] numbers) {
//Just loop through and print every number
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Print with formatting: this says print a digit (%d) followed by a
//tab(\t) and then specifies what number I want to print
System.out.printf("%d\t", numbers[i][j]);
}
//Print a new line after each row
System.out.printf("\n");
}
}
private static int numberOfTimesToFill(int elements, double populatePercentage) {
System.out.println((int)(populatePercentage * elements));
//Cast to an int to truncate the decimal part of the number because you can't have
//a fraction of an element
return (int)(populatePercentage * elements);
}
}
I have commented the code to explain what everything does. However it does not protect against bad user input and it hardcodes the size of the array, you should always try to avoid hardcoding. In this example I did it (and marked where) to be more clear. Also as was mentioned in the comments above, for your situation where you want exactly 25% of 25 is not possible. This is because .25 * 25 = 6.25 and you can't have .25 of an element.
I have declared an array that i would like to multiply the value of the first column by value of the second column of each row and create a grand sum of these products. I have tried the code listing below, what am i missing
public class Arrays {
public static void(String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum = 0;
for (int i = 0; i < array_x.length; i++) {
for (int j = 0; j < array_x.length; j++) {
array_x[i][j] = i * j;
System.out.println("\n" + array_x[i][j])
}
}
}
}
The output should be something like
9*8=72
2*17=34 etc then sum the whole results as 72+34+....
The code you wrote had several issues, including the fact that it would not compile because you had a different number of open and closed brackets, you didn't specify the function name (which I assumed to be main) and there was a ; missing. However the biggest issue was a logical one: you only need a single for to do what you want to do. You know that the indices of the second dimension of the array are going to be 0 and 1, because as you said the array has only two columns. Also, you need to accumulate the products into sum, instead you initialized sum to 0 and never updated it. Finally, the instruction array_x[i][j] = i * j multiplies the indices instead of the values, so the result is not what you expect, and this result is put into array_x, which is the wrong place because you really don't need to alter the input array.
class Arrays{
public static void main(String[] args){
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum=0;
for(int i=0;i<array_x.length;i++) {
int prod = array_x[i][0] * array_x[i][1];
System.out.println("\n"+prod);
sum += prod;
}
System.out.println("Final: " + sum);
}
}
The code you originally wrote is actually what you need to build a multiplication table, but in that case you need an array with an equal number of rows and columns.
public class Arrays {
public static void main (String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int multiply[] = new int[7];
for (int i = 0; i < array_x.length; i++) {
multiply[i] = array_x[i][0] * array_x[i][1];
}
int sum = 0;
for(int i = 0; i < multiply.length; i++)
{
System.out.println(array_x[i][0] + "*" + array_x[i][1] + "=" + multiply[i]);
sum += multiply[i];
}
System.out.println("Sum:" + sum);
}
}
I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.
I'm getting an error on the else if line in the function checkDuplicate.
Here's my code so far:
import javax.swing.JOptionPane;
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
+ "an integer:"));
}
checkDuplicate (array);
}
public static int checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
return 1;
}
}
The simplest way would be to add all of the elements to a Set<Integer> and then just print the contents of the Set.
First of all, the "else if" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "if (condition) ...").
Second, you cannot decide inside the inner loop, if a value should be printed: The way your code works you write a value array[i] for each value array[j] that is different from array[i]!
Third: the inner loop needs only to go from 0 to the outer index i-1: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.
A proper implementation of CheckDuplicate() would be:
public static void checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
}
But of course, some kind of Set would be much more efficient for bigger arrays...
EDIT: Of course, mmyers (see comments) is right by saying, that since CheckDuplicate() doesn't return any value, it should have return type void (instead of int). I corrected this in the above code...
Put them in a set ordered by insertion time, then convert back to an array if necessary.
new LinkedHashSet<Integer>(array).toArray()
Try throwing all of the integers into a Set. Duplicates will not ever be added to the Set and you will be left will a set of unique integers.
What you want can be accomplished using Java collection API, but not exactly as an one-liner, due to fact collection methods work with Objects and not primitives. J2SE lacks methods that convert, say, int[] to Integer[], but Apache Commons Lang library contains such useful methods, like ArrayUtils.toObject() and ArrayUtils.toPrimitive().
Using them, method to remove duplicated elements from an integer array looks something like this:
public static int[] removeDuplicates(int... array) {
Integer[] ints = ArrayUtils.toObject(array);
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(ints));
return ArrayUtils.toPrimitive(set.toArray(new Integer[set.size()]));
}
If your application is likely to include more of array/collection manipulation, I suggest you take a look at that library, instead of implementing things from scratch. But, if you're doing it for learning purposes, code away!
It would probably be better to add each number to a Set implementation rather than an array. Sets are specifically for storing collections of elements where you want to filter out duplicates.
Either use a Set as other people have suggested or use an List compatible class. With a list compatible class just use the Contains method to check if it already exists in the array.
import java.util.Scanner;
public class PrintDistinctNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int [] numberArray = createArray();
System.out.println("The number u entered are: ");
displayArray(numberArray);
getDistinctNumbers(numberArray);
}
public static int[] createArray() {
Scanner input = new Scanner(System.in);
int [] numberCollection = new int [10];
System.out.println("Enter 10 numbers");
for(int i = 0; i < numberCollection.length; i++){
numberCollection[i] = input.nextInt();
}
return numberCollection;
}
public static void displayArray(int[] numberArray) {
for(int i = 0; i < numberArray.length; i++){
System.out.print(numberArray[i]+" ");
}
}
public static void getDistinctNumbers(int[] numberArray) {
boolean isDistinct = true;
int temp = 0;
int [] distinctArrayNumbers = new int [10];
for ( int i = 0; i < numberArray.length; i++){
isDistinct = true;
temp = numberArray[i];
for( int j = 0; j < distinctArrayNumbers.length; j++){
if( numberArray[i] == distinctArrayNumbers[j] ){
isDistinct = false;
}
}
if(isDistinct){
distinctArrayNumbers[temp]=numberArray[i];
temp++;
}
}
displayDistinctArray(distinctArrayNumbers);
}
public static void displayDistinctArray(int[] distinctArrayNumbers) {
for( int i = 0; i < distinctArrayNumbers.length; i++){
if(distinctArrayNumbers[i] != 0){
System.out.println(distinctArrayNumbers[i]);
}
}
}
}