I have a problem figuring out how to pad the strings printed from my array values. I thought I had a good way to do it, but it doesn't read x.length correctly so I'm curious to alternative methods or even an explanation to the bug.
import java.util.Scanner;
//================================================================
public class Array {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice ;
String str = " ";
double sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
double average = 0;
int S;
int diff = 0;
int totalChar=0;
int minLen = 20;
String x= "";
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
double[][] figures = new double[rows][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 0.0;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group+" : ");
for(int col=0; col<figures[row].length; ++col) {
sum += figures[row][col];
average = sum/figures[row].length;
x = " "+figures[row][col];
diff = minLen - x.length();
System.out.printf("%1$" + diff + "s", x);
System.out.print(" ");
}
System.out.print("["+average+"]");
System.out.println();
}
}
}
I want to produce a table that looks like this:
A: 0.0 0.0 0.0 - [ 0.0, 0.0]
B: 0.0 0.0 0.0 0.0 - [ 0.0, 0.0]
C: 0.0 0.0 0.0 0.0 0.0 - [ 0.0, 0.0]
Where the - is where I want to fill with space until an arbitrary length. In other words I want my print array section to be able to print each line and add spaces up to a point. Is it possible to make a method for that? I'm not to familiar with all the java methods yet so any help is appreciated.
If this is a repeated question, I would appreciate a redirection to the original and I'll try to delete this one. Also sorry for the inconvenience in that case.
I am assuming you know how to build the string on the left and on the right, using StringBuilder or String concatenation.
Once you have your strings built, you can use printf as below to pad the output on the right to as many whitespace characters as you desire. In the sample code below, I have used 20 as the number of characters to pad to.
public class Pad {
public static void main(String[] args) {
String a = "0.0 0.0 0.0 ";
String b = "0.0 0.0 0.0 0.0";
String c = "[ 0.0, 0.0]";
System.out.printf("%-20s %s\n", a, c);
System.out.printf("%-20s %s\n", b, c);
}
}
You can use this idea in your code above by replacing your last loop with:
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing data row
StringBuilder sb = new StringBuilder();
group = (char)((row)+(int)'A');
sb.append(group+" : ");
for(int col=0; col<figures[row].length; ++col) {
sum += figures[row][col];
average = sum/figures[row].length;
x = " "+figures[row][col];
diff = minLen - x.length();
sb.append(String.format("%1$" + diff + "s", x));
sb.append(" ");
}
System.out.printf("%-75s[%f]\n", sb.toString(), average);
}
You need find the maximum number of column size and iterate in each row upto max column, and place the value if the length is less than actual row length and else blank spaces.
It will solve the issue.
I have added the changed code :
public class Array {
// String result = String.format("The format method is %s!", "great");
// System.out.println(result);
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter, letter;
String choice;
String str = " ";
double sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
double average = 0;
int S;
int diff = 0;
int totalChar = 0;
int minLen = 20;
String x = "";
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
double[][] figures = new double[rows][num];
int maxSize = 0;
for (int t = 0; t < rows; t++) {
rLetter = (char) ((t) + 'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
if (columns > maxSize) {
maxSize = columns;
}
figures[t] = new double[columns];
}
// filling the array
for (int row = 0; row < figures.length; ++row) {
for (int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 0.0;
}
}
// printing the array
for (int row = 0; row < figures.length; ++row) {
// printing data row
group = (char) ((row) + (int) 'A');
System.out.print(group + " : ");
for (int col = 0; col < maxSize; ++col) {
if (col < figures[row].length) {
sum += figures[row][col];
average = sum / figures[row].length;
x = " " + figures[row][col];
diff = minLen - x.length();
System.out.printf("%1$" + diff + "s", x);
System.out.print(" ");
} else {
System.out.print(" ");
}
}
System.out.print("[" + average + "]");
System.out.println();
}
}
}
Related
So far, my code is this one:
import java.util.Scanner;
public class PG1 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
//declaration,creation, initialization
double [][] matrix = new double [i][j];
//print element in row i
for (i = 0; i < matrix.length;i++){
//print element j in row i
for (j = 0; j < matrix[i].length; j++) {
System.out.print("The matrix is: " + matrix[i][j]);
}
System.out.println();
}
}
}
So basically, I want to print the 0s and 1s according to the user's input or row and column of the matrix. Your help will be much appreciated.
output:
Enter the length of the matrix: 4
The matrix:
0 1 1 1
0 0 0 0
0 1 0 0
1 1 1 1
All 0s on row 1
All 1s on row 3
No same numbers on a column
No same numbers on the diagona
you can achive like this:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
int count0s = 0;
int count1s = 0;
//declaration,creation,initialisation
double [][] matrix = new double [i][j];
//print element in row i
for ( i = 0; i < matrix.length;i++){
//print element j in row i
for ( j = 0; j < matrix[i].length; j++){
if(matrix[i][j] == 0){
count0s++
System.out.print("The matrix is: " + matrix[i][j]);
}
else if(matrix[i][j] == 1){
count1s++
System.out.print("The matrix is: " + matrix[i][j]);
}
}
System.out.println("Total no. of 0s="+count0s);
System.out.println("Total no. of 1s="+count1s);
}
}
}
If you dont want to print 0s and 1s :
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the length of matrix: ");
//array indicates
int i = input.nextInt();
int j = i;
int count0s = 0;
int count1s = 0;
//declaration,creation,initialisation
double [][] matrix = new double [i][j];
//print element in row i
for ( i = 0; i < matrix.length;i++){
//print element j in row i
for ( j = 0; j < matrix[i].length; j++){
if(matrix[i][j] == 0)
count0s++
else if(matrix[i][j] == 1)
count1s++
}
}
System.out.println("Total no. of 0s="+count0s);
System.out.println("Total no. of 1s="+count1s);
}
}
I try to print the matrix AxA with all of the values are showed in there, but I failed.
Output should be something look like this:
1 2 3
4 5 6
Thank you
So this is my code:
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j] = input.nextInt();
}
System.out.println(" " + array);
}
}
Updated:
I was able to print out the matrix, but now I run into the second question is calculating the average of each rows and columns of the matrix. I tried to use this code, but it didn't work, and I know that I have a major problem right here, but I couldn't find one.
I have been doing it since this morning until now. Not going to lie, this is my homework which to test my basic knowledge.
My new output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
ave=2.5, 3.5, 4.5
And this is my current code right now:
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
public static doube averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
public static doube averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}
You can use same logic for reading and writing array elements,Try this code
Reading an array...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
array[i][j] = input.nextInt();
}
}
Printing array elements...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
Use
Stream.of(array).map(Arrays::toString).forEach(System.out::println);
Which will print :
[1 ,2, 3]
[4, 5, 6]
or
System.out.println(Arrays.deepToString(array));
Reference
Keep in mind that you can't simply print the whole array. I.e.: System.out.println(" " + array);
You're on the right track but you need to print using a for loop (give printf a try, it's powerful):
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++){
System.out.printf("%d ", array[i][j]);
}
System.out.printf("\n");
}
There is another single loop way I can think of:
for (int[] a : array) {
String str = Arrays.toString(a);
System.out.println(str.substring(1, str.length()-1).replaceAll("[,]", ""));
}
The for loop basically iterates over each row, i.e. value of 'a' is an array (row) in the matrix.
Arrays.toString(a) returns the string equivalent of the array, e.g. for a = [1,2,3,4,5], it would return "[1, 2, 3, 4, 5]". Now simply remove the brackets (substring) and replace commas (",") with "", and you have the desired result.
Note that the first parameter of the replaceAll is a regex, not the string itself.
Except for an extra column produced by the code, everything works fine except my avg method which was meant to average the value in each row. I'm new to coding, so maybe I'm not seeing the problem, but the method isn't working as intended. At first I thought it was an issue with the sum but changing it didn't really resolve the initial problem. A column input of (2,1,3) will produce an exception error at 1 but does not occur when the input is (1,3,2). Also the avg is producing only 2 regardless of column length.
I'm aiming for the code to print this when column input of (1,2,3) is entered:
A:2.0 [1.0]
B:2.0 2.0 [2.0]
C:2.0 2.0 2.0 [3.0]
where the bracketed term is the average for that row.
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while((columns < 0) || (columns >= 8)) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 0; row < figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
public static double avg(double temp[][]) {
int sum = 0;
int avg = 0;
for (int row = 0; row < temp.length; row++){
for (int col = 0; col < temp[col].length; col++)
sum += temp[row][col];
}
avg = sum / temp.length;
return avg;
}
}
I think what you are doing wrong is instead of summing up all elements of a row and taking average, you are summing up the whole matrix and taking average which will always be the same value.
While working on a code for making a irregular 2D-array, I discovered a weird error while messing with different inputted values for the column. While the row works, the column length input returns either the wrong amount or a null pointer error occurs. I'm not sure what might be causing this since inputs such as ( 1 , 2 , 3) returns the correct table but (2 , 1, 3) will not. Also in a row of 4 with column inputs of (2, 3, 4, 5) returns "index out of bounds exception: 5" when there shouldn't be able to be out of bounds because of the while loop that should keep it with in reasonable range. Neither the main nor the display method seems to be saving the intended column length correctly and I can't seem to spot why.
It seems the array is set to 3 rows with column length of 1 , 2 , 3.
The output for row(3) and column(2,3,1) gives:
A:2.0
B:2.0 2.0
C:2.0 2.0 2.0
when I want is:
A:2.0 2.0
B:2.0 2.0 2.0
C:2.0
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
//greetings
System.out.println("");
System.out.println("Welcome to the Band of the Hour");
System.out.println("-------------------------------");
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+(int)'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while(columns < 0 || columns >= 8) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 1; row < figures.length; ++row) {
// printing data row
group = (char)((row-1)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
//----------MENU
System.out.print("(A)dd, (R)emove, (P)rint, e(X)it : ");
choice = Keyboard.next();
letter = choice.charAt(0);
letter = Character.toUpperCase(letter);
if(letter == 'P') {
display(figures);
}
}
public static void display(double x[][]) {
int average, total;
char group;
System.out.println(" ");
for(int row=1;row<x.length;row++) {
group = (char)((row-1)+(int)'A');
System.out.print(group+" : ");
for(int column=0;column<x[row].length;column++){
System.out.print(x[row][column]+" ");
}
System.out.print("["+","+avg(x)+"]");
System.out.println();
}
}
public static int avg(double[][] temp) {
int sum = 0;
int avg = 0;
for (int col = 0; col < temp[0].length; col++) {
sum = 0;
for (int row = 0; row < temp.length; row++)
sum += temp[row][col];
System.out.println(sum);
}
avg = sum / temp.length;
return avg;
}
}
In Creating 2D Array,
Change this
double[][] figures = new double[rows + 1][num];
to
double[][] figures = new double[rows][num];
and
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
to
figures[t] = new double[columns] ;
In Printing Array
Change this
for(int row = 1; row < figures.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < figures.length; ++row) {
group = (char)((row)+(int)'A');
In display function
Change this
for(int row = 1; row < x.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < x.length; ++row) {
group = (char)((row)+(int)'A');
It's this
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
I think you meant actually
figures[t] = new double[columns];
I have to take in a few ID numbers and how many boxes sold by the ID number...split those into two arrays...which I've done....then sort the array reporting the largest sale of boxes sold....the(and this is my problem) if the same id number is entered, add the number of boxes sold together and make it take up only one spot in the array
example....
idNum 1 = 100
idNum 3 = 500
idNum 1 = 200
so idNum 1 = 300
//declarations
int [][] stupidKids = new int[10][2];//10 rows....2 columns
int entry = 0;
int tempNum;
int tempTotal = 0;
int tempId;
int found = -1;
//user input section
for(int i = 0; i < 2; i++)
{
System.out.print("Please enter the class ID");
Scanner scan = new Scanner(System.in);
stupidKids[i][0] = scan.nextInt();
System.out.print("Please enter the amount of cookies sold");
stupidKids[i][1] = scan.nextInt();
System.out.println(stupidKids[i][0] + "Cookies " + stupidKids[i][1]);
}
//sorting process
for(int i = 0; i < 2; i++)
{
if(stupidKids[i][1] > stupidKids[i+1][1])
{
tempNum = stupidKids[i][1];
stupidKids[i][1] = stupidKids[i + 1][1];
stupidKids[i + 1][1] = tempNum;
tempId = stupidKids[i][0];
stupidKids[i][0] = stupidKids[i+1][0];
stupidKids[i+1][0] = tempId;
}
}
//comparing for same ID Num
for(int i = 0; i < 1; i++)
{
if(stupidKids[i][0] == stupidKids[i+1][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[i+1][1]);
}
}
System.out.println("Final num " + tempTotal);
You must loop through your for loops 10 times rather than just twice, this way you get through the whole array.
for(int i = 0; i < 10; i++)
Below is the code to compare the IDs against each other in the 2D array. Although I am not quite sure about why you would want it to take up only one space per ID as you will end up with a lot of NULL values in the array as you can not easily resize an array (to do this requires an implementation of a basic algorithm)
for(int i = 0; i < 10; i++)
{
tempID = stupidKids[i][0];
for(int j = 0; j < 10; j++)
{
if( i != j)
{
if(stupidKids[i][0] == stupidKids[j][0])
{
tempTotal = (stupidKids[i][1] + stupidKids[j][1]);
}
}
}
}
System.out.println("Final num " + tempTotal);