So i'm a beginner;
The task is to convert a given string into the array, the string always has the first characcter as the amount of rows and the second character as the amount of columns.
My problem is to solve how to move the rest of the string 's' into the 2D array from the 1D array.
Thanks in advance!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] s = scanner.nextLine().split(" ");
int arows = Integer.parseInt(s[0]);
int acols = Integer.parseInt(s[1]);
int[][] cells = new int[arows][acols];
for (int col = 0; col < acols; col++){
for (int row = 0; row <= arows;row++){
cells[row][col] = Integer.parseInt(s[2]);
}
}
}
}
You need to implement a counter for your for-loops to iterate through the input string. What you are doing right now is to fill your 2D-Array with the third element of your string.
One solution would be to just declare a variable i = 2, and increment it for each pass of the inner for-loop.
int i = 2
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
Edit: removed <= in row loop, changed the initial value of the index to 2
This is the solution, you have to put another iterator, and initialize it to 2, so to skip the first two elements of s[]
int i = 2;
for (int col = 0; col < acols; col++){
for (int row = 0; row < arows;row++){
cells[row][col] = Integer.parseInt(s[i]);
i++;
}
}
I found an exercise in my textbook that makes this 2D array.
I have the input loop working, and the table prints successfully but I can't find a way to take the values in each row and column and print out the totals as shown in the exercise.
I have asked my professor and he said he couldn't remember how to do it with a string array. I hope there is a way to convert each number from string to an int. I assume that creating a double array would have been much easier than a String array but at this point I wouldn't know convert all my work over.
package Assignment2;
import java.util.*;
/**
*
* #author Lyan
*/
public class Exercise7_20
{
public static void sales2DArray(int salesPerson, int product, double value)
{
}
public static void main(String[] args)
{
int salesP = 0; //salesPerson set to 0
String[][] table = new String[5][5]; // A matrix of '5 rows and '5 Columns'
//For loop that replaces null values in table with 0.00
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (table[i][j] == null) {
table[i][j] = " 0.0";
}
}
}
//Input for salesPerson
Scanner inSales = new Scanner(System.in);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//While loop to ask for salesPerson, product, and sales amount (val)
while(salesP > 0 && salesP < 5)
{
//input for Product number
Scanner inProduct = new Scanner(System.in);
System.out.println("Enter product number");
int productNum = inProduct.nextInt();
//input for sales amount
Scanner inValue = new Scanner(System.in);
System.out.println("Enter Sales amount");
double val = inValue.nextDouble();
//sets the values onto the table.
table[productNum - 1][salesP] = " " + Double.toString(val);
System.out.println("Enter salesPerson number (-1 to end): ");
salesP = inSales.nextInt();
//makes the 1-5 on the left hand side of the table
}
for(int i = 1; i < 6; i++)
{
table[i-1][0] = " " + i + "";
}
//Hardcoded header
System.out.println("Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson 4 Total");
//Makes the 2D array to print in a box format rather than a straight line.
System.out.println(Arrays.deepToString(table).replace("],","]\n"));
//Anything below is my testing to get the total to print out for each individual salesPerson (column)
//and the totals for the products for all salesPerson (rows)
System.out.print("Total ");
String total = "";
int sum = 0;
for(int down = 0; down < 5; down++)
{
//append
}
//successfully reads the last value of each column but does not print the total
//only successfully prints the last value
for(int c = 1; c < 5; c++)
{
for(int r = 0; r < 5; r++)
{
String temp = table[r][c];
total = temp;
}
System.out.print(total + " ");
}
}
}
You can use this simple logic to find the sum of each individual row and column of your 2D array.
double[] sumOfRows = new double[5];
double[] sumOfCols = new double[5];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table.length; j++) {
sumOfRows[i] = sumOfRows[i] + Double.parseDouble(table[i][j]);
sumOfCols[i] = sumOfCols[i] + Double.parseDouble(table[j][i]);
}
}
Here we declare 2 additional arrays to store the sum of each row and column respectively. You can print them according to your logic as desired.
Also note use Double.parseDouble(...) to convert a String to a double.
This is a school project. It is to display the info from the array into a tubular format with totals on the right side and across the bottom for each row and column. It does all the totals except one row. I can't find where the problem is. Can anyone help?!
import java.util.Scanner;
//program uses class Scanner
public class Ex6_20
{
//method begins java application
public static void main(String[] args)
{
//create Scanner to obtain imput
Scanner input = new Scanner(System.in);
int monthySales=0; //varible to hold mothly sales
int productNum; //varible to hold product number
int salesNum=0; //varible to hold saleperson number
int totalSales=0; //varible to hold total sales
int []totalProduct = {0,0,0,0,0};//build array to hold total product
int []salesTotal = {0,0,0,0,0};//build array to hold total salesperson
// Build array to hold sales information by salesperson and poduct
int[][]sales = {{2000,1500,500,800,0},
{500,2200,600,1000,0},
{1000,2000,300,2100,0},
{2500,4000,400,3000,0},
{300,3200,500,2300,0},
{0,0,0,0}};
//figure total by product
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
totalProduct[column] += sales[row][column];
}//end for
//figure total by salesperson
for(int column = 0; column < sales.length; column++)
{
for(int row = 0; row < sales[column].length; row++)
salesTotal[row] += sales[column][row];
}//end for
//fill totals for product
for(int i = 0; i < 5; i++)
{
sales[i][4] = totalProduct[i];
}//end for
//fill totals for salesperson
for(int i = 0; i < 4; i++)
{
sales[5][i] = salesTotal[i];
}//end for
// print info from array in table format
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
System.out.print(sales[row][column]+"\t");
System.out.println();
}//end for
} //end main method
} //end class
There are a few problems:
If you swap the variable names "row" and "column" in "figure total by salesperson" you'll notice that you are actually doing exactly the same calculation as "figure total by product", just with misleading variable names. (You're using column as the row index, and vice versa.) As of now, both totalProduct and salesTotal contain identical values, which is not right.
That is the main problem.
Also, when you display sales total and product totals, they are actually swapped. I suspect this is because you mean to have a total product per row with totalProduct[row] += ... and a total sales per column with salesTotal[column] += ..., but maybe the names are just swapped and the row/column indices are ok.
I'd actually recommend removing the extra sum fields from the sales array so all of the rows have the same number of columns and using hard-coded array bounds to start with, in order to make it more obvious what's happening until you get the sums correct. Then once the sums come up right, you can go back and make it work more generally. Otherwise, you may keep getting ArrayIndexOutOfBounds exceptions without it being obvious why, which is how I suspect you ended up with this solution so far.
For example, you could start with something very straightforward like this, then go back and make it a lot nicer and more general so it can work with different array sizes:
int[][] table = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } };
int[] rowSums = new int[3];
int[] colSums = new int[5];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
rowSums[i] += table[i][j];
colSums[j] += table[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(table[i][j]);
System.out.print('\t');
}
System.out.println(rowSums[i]);
}
for (int j = 0; j < 5; j++) {
System.out.print(colSums[j]);
System.out.print('\t');
}
System.out.println();
My program will output a graphical representation of some rows and columns. It asks the users to input the number of rows and columns they want to see the figure for. For example if the user chooses 4 rows and 3 columns, it should print a figure (let's say it's made up of character X) which has 4 rows and 3 columns.
The final output will look like this:
X X X
X X X
X X X
X X X
Now the problem is I can't set the logic in my for loop so that it makes the desired shape. I tried, but couldn't figure it out.
This what I have done so far:
package banktransport;
import java.util.*;
public class BankTransport {
static int NumOfRow;
static int numOfColum;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
showRowCol(NumOfRow, numOfColum);
}
public static void showRowCol(int NumOfRow, int numOfColum) {
System.out.println("Enter row: ");
NumOfRow = input.nextInt();
System.out.println("Enter Col: ");
numOfColum = input.nextInt();
System.out.println("");
System.out.println("Visual Representation: ");
//print column and row
for (int i = 0; i < numOfColum; i++) {
System.out.print(" X ");
//System.out.println("");
//for(int j=1; j<(NumOfRow-1);j++){
// System.out.print(" Y ");
//}
}
System.out.println("");
}
}
Try a loop like this:
for ( int i = 0; i < numOfRow; i++ )
{
for ( int j = 0; j < numOfColum; j++ )
{
System.out.print(" X ");
}
System.out.println();
}
Try:
for (int i = 0; i < numOfRow; i++) {
StringBuilder line = new StringBuilder();
for (int j = 0; j < numOfColumn; j++) {
line.append("X ");
}
System.out.println(line.toString());
}
You can also use Apache Commons Lang StringUtils.repeat method (which would prevent you from having a trailing space at the end of the line):
for (int i = 0; i < numOfRow; i++) {
System.out.println(StringUtils.repeat("X", " ", numOfColumn));
}
This question already has answers here:
Summing Up A 2D Array
(3 answers)
Closed 9 years ago.
I'm trying to repost this question but with more clarification. Given my code below, I wish to output the total of each column and each row. The row totals should be to the right of the last element in that particular row and the column total should be below the final element in a given column. Please see the comment in the beginning of my program to understand what I wish my output to be. How could I go about doing this? Also I want to print out the main diagonal of a given user-inputted array. So in the code below the main diagonal would be outputted as {1,3,5}. Thank you!
/*
1 2 3 Row 0: 6
2 3 4 Row 1: 9
3 4 5 Row 2: 12
Column 0: 6
Column 1: 9
Column 2: 12
*/
import java.util.Scanner;
import java.util.Arrays;
public class Test2Darray {
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
}
for(int row = 0; row < rows; row++)
{
for( int column = 0; column < columns; column++)
{
System.out.print(array2d[row][column] + " ");
}
System.out.println();
}
System.out.println("\n");
}
}
}
int[] colSums = new int[array2d.length];
int[] mainDiagonal = new int[array2d.length];
for (int i = 0; i < array2d[0].length; i++) {
int rowSum = 0;
for (int j = 0; j < array2d.length; j++) {
colSums[j] += array2d[i][j];
rowSum += array2d[i][j];
System.out.print(array2d[i][j] + " ");
if (i == j) mainDiagonal[i] = array2d[i][j];
}
System.out.println(" Row " + i + ": " + rowSum);
}
System.out.println();
for (int i = 0; i < colSums.length; i++)
System.out.println("Column " + i + ": " + colSums[i]);
System.out.print("\nMain diagonal: { ");
for (Integer e : mainDiagonal) System.out.print(e + " ");
System.out.println("}");