package Matrix;
import java.util.Scanner;
public class Matrix
{
public static void main(String[] args) {
System.out.print("Enter 2D array size : ");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int columns=sc.nextInt();
System.out.println("Enter array elements : ");
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=sc.nextInt();
}
}
System.out.print("\n \n");
for(int []x:twoD){
for(int y:x){
System.out.print(y+" ");
}
System.out.println();
}
System.out.println("");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
}
}
}
how can I print the sum of the columns as well?
here is what I have so far
My expected output must be :
5 9 8 = 22
3 8 2 = 13
4 3 9 = 16
___________
12 20 19
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
You already have added up the elements in the row. Now to add up the columns instead of trying to change the row in your for loop change the columns to add up.
Change
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
To
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
Therefore you will have a loop that runs effectively for every column and has the sum at 0 in the beginning and at the accurate sum at the end of going through each column and all that is left is just to print it out.
If you want to have this implemented in JOption than instead of using Scanner in Java, you would have to import the JOption Library with this import statement
import javax.swing.JOptionPane;
Then you would change your input of 2D Array Size to using the method of showInputDialog. Remember that showInputDialog returns a String and so you would need to use parseInt to turn it to a Integer. Here is an example
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D Array
Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
Next change the input of the Array to also use this method. Like this
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
Resulting in the Final Code being
import javax.swing.JOptionPane;
public class Matrix{
public static void main(String[] args) {
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
System.out.print("\n \n");
for(int []x:twoD){
int cSum = 0;
for(int y:x){
System.out.print(y+" ");
cSum+=y;
}
System.out.println(" = "+cSum);
}
System.out.println("");
System.out.println("___________");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
}
}
}
Related
I have try to create a code that can solve a matrix.
import java.util.Scanner;
public class Pratical_8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking A Matrix
System.out.println("Enter number of Rows and Column for first Matrix");
System.out.print("Enter Rows ");
int aRLen=sc.nextInt();
System.out.print("Enter Columns ");
int aCLen=sc.nextInt();
int [][] a = new int [aRLen][aCLen];
System.out.println("Enter Matrix");
for(int i=0;i<aRLen;i++)
{
for(int j=0;j<aCLen;j++)
{
a[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Taking B Matrix
System.out.println("Enter number of Rows and Column for second Matrix");
System.out.print("Enter Rows ");
int bRLen=sc.nextInt();
System.out.print("Enter Columns ");
int bCLen=sc.nextInt();
int [][] b = new int [bRLen][bCLen];
System.out.println("Enter Matrix");
for(int i=0;i<bRLen;i++)
{
for(int j=0;j<bCLen;j++)
{
b[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Creating resulting Matrix
int [][] r = new int [aRLen][bCLen];
// Check for Valid input
if(aCLen!=bRLen)
{
System.out.println("Error invalid input");
System.out.println("Multiplication of this matrix is not possible");
}
else
{
for(int i=0;i<aCLen;i++)
{
for(int j=0;j<bRLen;j++)
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
}//End of if-else
}//End of main
}//End of class
it have an error after sucessfully give an output
Output:-
Enter number of Rows and Column for first Matrik
Enter Rows 1
Enter Columns 3
Enter Matrix
1
2
3
Enter number of Rows and Column for second Matrix
Enter Rows 3
Enter Columns 1
Enter Matrix
1
2
3
14
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Pratical_8.main(Pratical_8.java:57)
Process finished with exit code 1
This Error only ocure in non Sysmetrix Matrix
What is the PROBLEM?
Since the final matrix is of order aRLen x bCLen the last for loops needs to be modified.
for(int i=0;i<aRLen;i++) // Instead of aClen
{
for(int j=0;j<bCLen;j++) //Instead of bRlen
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
This will work properly.
Please see this code:
import java.util.Scanner;
public class Array
{
public static void main(String args[])
{
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++)
{
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
Scanner scan2=new Scanner(System.in);
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextLine();
}
OUTER:
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":");
break OUTER;
}
INNER:
for (int l = 0; l < numbers.length; l++)
{
System.out.println(numbers[ l ]);
break INNER;
}
}
}
I am a newbie, learning Array as of now, in Java. I want to print the outcome of the code above as follows:
Enter 5 numbers:
//Say:
RED
GREEN
BLUE
PINK
YELLOW
Enter 5 numbers:
1
2
3
4
5
//Output of the code should be:
RED: 1
GREEN: 2
BLUE: 3
PINK: 4
YELLOW: 5
How can I print the array? I am only able to print up to "RED: 1" only, after which my program ends due to break statement.
Your last for does not a have any purpose. Just try :
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++){
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++) {
numbers[j]=scan.nextLine();
}
for (int k = 0; k < names.length; k++){
System.out.println(names[ k ] + ":"+ numbers[k]);
}
}
}
ANd it's stop at the first because you break your for
scan.nextLine() reads the whole line of input that is it reads until you don't enter \n new line charachter, so use nextInt() instead of that. Also each System.out.println() is used to print a whole line so only one loop can be used. If names and numbers have same length. And change numbers[] from String to int, that would be more type safe.
int numbers[] = new int[5];
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextInt();
}
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":" + numbers[k]);
}
Since the number of elements be it color or numericals that you're trying to get from the user is fixed here i.e 5, why complicate things? Use a single for loop to print all the contents of both the arrays:
for(int k=0;k<names.length;k++){
System.out.println(names[k] + ":"+numbers[k]);
}
I need help creating an array that counts up to a given number. The output should look something like this:
Enter a positive integer: 8
Counting up: 1 2 3 4 5 6 7 8
Counting down: 8 7 6 5 4 3 2 1
The first 8 multiples of 5: 5 10 15 20 25 30 35 40
The first 8 multiples of 10: 10 20 30 40 50 60 70 80
Here is what I have so far:
Scanner input = new Scanner(System.in);
int[] myList = new int[1];
System.out.print("Enter a positive integer: ");
promptUser(myList);
int[] testArray = { 1, 1, 2, 3, 5, 8, 13 };
System.out.print("Test array: ");
printArray(testArray);
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
}
public static void promptUser(int[] a){
Scanner input = new Scanner(System.in);
for(int i=0; i<a.length; i++){
a[i] = input.nextInt();
}
}
public static void printArray(int[] array){
for(int i=0; i<array.length; i++)
System.out.print(array[i]);
}
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
}
Everything seems to work alright except for the last method called countingUp.
Thank you so much!
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
change this to
public static int[] countUp(int n){
int [] temp=new int[n];
for(int i=0; i<n; i++){
temp[i]=i+1;
}
return temp;
}
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
In this line change to
int[] countingUp = countUp(n);
for(int i=0;i<countingUp.length;i++){
system.out.println(countingUp[i]+" ");
}
We can start by extracting the common logic of counting by providing an initial message, the number of times to run, an initial value and an increment. Something like,
private static void count(String msg, int times, int init, int inc) {
System.out.print(msg);
for (int i = 0; i < times; i++) {
System.out.print(' ');
System.out.print(init);
init += inc;
}
System.out.println();
}
We can then implement the entirety of the requirements with something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
System.out.flush();
do {
int num = scanner.nextInt();
count("Counting up:", num, 1, 1);
count("Counting down:", num, num, -1);
count(String.format("The first %d multiples of 5:", num), num, 5, 5);
count(String.format("The first %d multiples of 10:", num), num, 10, 10);
System.out.print("Enter a positive integer: ");
System.out.flush();
} while (scanner.hasNextInt());
}
This will produce the requested output given an input of 8, and will then prompt for more input.
First of all, If you are trying to change the Array Size Dynamically then It is NOT POSSIBLE in java Take a look # this accepted answer. I recommend you to use ARRAYLIST instead.
Although I have found below mistakes in your code. In your code I do not understand two things.
First One:
System.out.print("Counting up: ");
int[] countingUp = countUp(n);
printArray(countingUp);
What is the value of n? I think it is not being initialized.
Second One:
public static int[] countUp(int n){
for(int i=0; i<n; i++){
int count = 0;
while(count<n){
count++;
}
}
}
What will return this function? You have not returned anything from it.
Apparently you don't need an array just follow below steps.
First create a class which handle all your calculating and counting
class SupportCounting {
public void countUp(int num) {
System.out.print("Counting up : ");
for (int i = 1; i <= num; i++) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void countDown(int num) {
System.out.print("Counting Down : ");
for (int i = num; i > 0; i--) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("");
}
public void printMultiple(int num, int scalefactor) {
System.out.print("First " + num + " multiples of " + scalefactor + " : ");
for (int i = 1; i <= num; i++) {
System.out.print(i * scalefactor);
System.out.print(" ");
}
System.out.println("");
}}
Then make use of that class in you main method
public class Counting {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter a positive integer : ");
int n = reader.nextInt();
SupportCounting sc = new SupportCounting();
sc.countUp(n);
sc.countDown(n);
sc.printMultiple(n, 5);
sc.printMultiple(n, 10);
}}
Hope that helps
I need to write a program that will take a number n from the user and create an nxn matrix that counts up, then I need to transpose it. I've tried multiple methods of coding, but nothing displays correctly.
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
The result I'm currently getting is:
Enter the size of the Square Matrix:
3
123
234
345
I need it to look more like this:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
The nxn matrix counting up is
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
The transponse is
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
I wrote a code that does exactly what you need. It may seem overcomplicated but i think it grasp the idea that you would do with pencil and paper. You need to put the scanning user input part in though.
int n=10;
int[][] matrix =new int[n][n]; // a 2D array as one would imagine a matrix
int num=0;
int temp=0;// used in transposing
//initializing the arrays of the second dimension
for (int init=0;init<n;init++){
matrix[init]=new int[n];
}
System.out.println("filling and printing matrix");
for (int fill_row=0;fill_row<n;fill_row++){
for(int columns=0;columns<n;columns++){
matrix[fill_row][columns]=++num;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[fill_row]));
}
}
}
System.out.println("Transposed matrix");
for (int transp_row=0;transp_row<n;transp_row++){
for(int columns=transp_row;columns<n;columns++){
//store actual value to temp,
temp=matrix[transp_row][columns];
//by switching the order of the indicies assign new value to current position
matrix[transp_row][columns]=matrix[columns][transp_row];
//assgin temp value to what we used as replacement
matrix[columns][transp_row]=temp;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[transp_row])); // print each rows of the array
}
}
}
}
I hope it helps.
Given my current code, how could I output it in matrix format? My current output method simply lists the arrays in a straight line. However I need to stack them in their corresponding input parameters so a 3x3 input produces a 3x3 output. Thank you!
import java.util.Scanner;
for(int row = 0; row < rows; row++){
for( int column = 0; column < columns; column++){
System.out.print(array2d[row][column] + " ");
}
System.out.println();
}
This will print out a line of one row and then move onto the next row and print out its contents, etc... Tested with the code that you provided and works.
EDIT - Added the code for the way you wanted it:
public static void main(String[] args) {
Scanner scan =new Scanner(System.in); //creates scanner object
System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array
int rows = scan.nextInt(); //takes input for response
System.out.println("How many columns to fill?");
int columns = scan.nextInt();
int[][] array2d=new int[rows][columns]; //array for the elements
for(int row=0;row<rows;row++)
for (int column=0; column < columns; column++)
{
System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input
array2d[row][column]=scan.nextInt(); //Takes in current input
}
System.out.println(Arrays.deepToString(array2d));
String[][] split = new String[1][rows];
split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], [")); //split at the comma
for(int row = 0; row < rows; row++){
System.out.println(split[0][row]);
}
scan.close();
}
for (int i =0; i < rows; i++) {
for (int j = 0; j < columns ; j++) {
System.out.print(" " + array2d[i][j]);
}
System.out.println("");
}