Here is the original question:
Write a program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
I edited the code now to show my new nested for loops at the bottom. These are supposed to compute the average of the entered numbers, however, I am not sure why it does not work?
You can use two variables, one for the row, and one for the column:
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i=0;
int j;
while (i < 3) {
j=0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j]=value;
j++;
}
i++;
}
This logic is weird and never can be met
while (count < 3) {
while (count < 9) {
at the moment that count is bigger than 3 you will never see again the while at count<9
you should think again and reorder the conditional check of that value..
while (count < 9) {
while (count < 3) {
could make more sense...
You could rewrite this segment:
int count = 0;
while (count < 3) {
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
count++;
}
}
...to
double row_sum, value;
double[] row_means;
int row_count = 0, col_count;
while (row_count < 3) {
row_sum = 0.0;
col_count = 0;
while (col_count < 3) {
System.out.print("Enter a number: ");
// TODO: consider adding some input validation
value = scnr.nextDouble();
row_sum += value;
scores[row_count][col_count++] = value;
}
row_means[row_count++] = row_sum / 3.0;
}
... which simultaneously populates your matrix and computes the mean.
Alternatively you can have one loop;
while (count < 9) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[count/3][count%3]=value;
count++
}
Think about it in terms of English or pseudo code first, it will be surprisingly easier.
//In English, to get average from 1 row:
/*
1) sum every elements in the row
2) divide sum by number of elements
*/
In codes:
int y = 0;
while(y < col){ //loop through all columns
sum += scores[0][y];
y++;
}
avg = sum / col;
If you can get the average of just one row, congratulations, your work is more than half done. Simply repeat the above process for all other rows with another loop. (This explains why you need 2 loops. One for the columns, the other for the rows).
//In English, to get average from all rows:
/*
1) sum every elements in the row
2) divide sum by number of elements
3) repeat the above till all rows are done
*/
In codes:
int x = 0;
while(x < row){ //loop through all rows
int y = 0;
while(y < col){ //loop through all columns
sum += scores[x][y];
y++;
}
avg[x] = sum / col; //avg needs to be array now, since you need to store 3 values
x++;
}
To get values from row and col:
int row = scores.length;
int col = scores[0].length;
Related
I have this assignment I solved, where the user enters X amount of rows. The program then determines how many columns there needs to be to add up to 50 total items. If it adds another column, this column will end up having too many items, so I needed to figure out how to not print these extra characters. I did figure a solution, but I was wondering if there was a more simpler way.
public class J1_Lab08_3 {
public static void main(String[] args) {
userInput();
}
public static void userInput(){
Scanner input = new Scanner(System.in); // scanner object
int rowAmount;
char[][] array;
while(true) {
System.out.println("Please enter the amount of rows 1-50. Enter 0 to quit program"); // asking the user to enter row amount
rowAmount = input.nextInt();
if(rowAmount == 0){
System.out.println("Thank you.");
System.exit(0);
} else if(rowAmount >= 51){
System.out.println("Please enter a value less than 50");
System.exit(0);
}
array = createArray(rowAmount); // created array
print2dCharArray(array); // prints array
}
}
public static char[][] createArray(int sizeX){
char[][] array = new char[sizeX][(50+sizeX-1)/sizeX];
int remainder = 50%sizeX;
int counter = 0;
for(int i = 0; i < sizeX; i++){ // goes through each row in the array
for(int j = 0; j < 50/sizeX; j++){ // goes through each column in the array
array[i][j] = (char)('a' + (Math.random() * ('z' - 'a'))); // creates a random letter from a-z
}
}
while(remainder > 0){
array[counter][(50/sizeX)] = (char)('a' + (Math.random() * ('z' - 'a')));
counter++; // goes to next row in array
remainder--; // subtracts by one to know when to stop going down rows
}
return array; // returns the array that was created with random characters
}
public static void print2dCharArray(char[][] array){
for(int i = 0; i < array.length; i++){ // goes through row of array
for(int j = 0; j < array[0].length; j++){ // goes through column of array
if(array[i][j] != 0) { // gets rid of remaining zeros
System.out.print("(" + array[i][j] + ") "); // prints row and column
}
}
System.out.println(); // prints a new line to start printing new row
}
System.out.println();
}
}
using the example number 7 rows, what I did for this is, I created the non-remainder amount of columns or arrays. So for 7 rows, it would then create 7 columns at first, with 8 being needed in total to reach 50. Then it would check for a remainder and then add on another column if there was a remainder, and every time it adds one it lowers the remainder until the remainder is 0.
Edit:
I added a variable to control how many items that need to be printed
public static char[][] createArray(int sizeX){
int pairAmount = 50; // total amount of items
char[][] array = new char[sizeX][(pairAmount+sizeX-1)/sizeX];
int remainder = pairAmount%sizeX;
int counter = 0;
for(int i = 0; i < sizeX; i++){ // goes through each row in the array
for(int j = 0; j < pairAmount/sizeX; j++){ // goes through each column in the array
array[i][j] = (char)('a' + (Math.random() * ('z' - 'a'))); // creates a random letter from a-z
}
}
while(remainder > 0){
array[counter][(pairAmount/sizeX)] = (char)('a' + (Math.random() * ('z' - 'a')));
counter++; // goes to next row in array
remainder--; // subtracts by one to know when to stop going down rows
}
return array; // returns the array that was created with random characters
}
keeping it at 50, and entering a number for example 5. would print to the console
using 5 as row amount, and 50 as total amount of items
using 6 as row amount, and 50 as total amount of items
if totalItems gets changed to 24 and we used the same numbers(5 and 6) it would also produce
using 5 as row amount, and 24 as total amount of items
using 6 as row amount, and 24 as total amount of items
You can make it slightly simpler by also adding the remainder characters in the loop. You can do that by simply counting how much you already added. For example like
public static char[][] createArray(int sizeX){
int pairAmount = 50; // total amount of items
int columnAmount = (pairAmount+sizeX-1)/sizeX;
char[][] array = new char[sizeX][columnAmount];
for(int i = 0; i < sizeX; i++){ // goes through each row in the array
for(int j = 0; j < columnAmount && pairAmount > 0; j++){ // goes through each column in the array
array[i][j] = (char)('a' + (Math.random() * ('z' - 'a'))); // creates a random letter from a-z
pairAmount--;
}
}
return array; // returns the array that was created with random characters
}
You can get the first n rows which will have additional columns/elements by doing pairAmount % sizeX, for example for pairAmount = 50 and sizeX = 6: pairAmount % sizeX = 2 which means the first two rows will have 9 elements. You can add this condition in the inner loop and get rid of the while loop completly:
public static char[][] createArray(int sizeX){
int pairAmount = 50;
char[][] array = new char[sizeX][(int) Math.ceil((double) pairAmount / sizeX)]; // I think this way it is clearer, but you can keep your approach if you don't like it
for(int i = 0; i < sizeX; i++){
for(int j = 0; j < ((i < pairAmount % sizeX) ? array[i].length : pairAmount/sizeX); j++){
array[i][j] = (char)('a' + (Math.random() * ('z' - 'a')));
}
}
return array;
}
or introduce a variable to make if you don't find the above not readable:
public static char[][] createArray(int sizeX){
int pairAmount = 50;
char[][] array = new char[sizeX][(int)Math.ceil((double) pairAmount / sizeX)];
for(int i = 0; i < sizeX; i++){
int maxColumn = (i < pairAmount % sizeX) ? array[i].length : pairAmount / sizeX;
for(int j = 0; j < maxColumn; j++){
array[i][j] = (char)('a' + (Math.random() * ('z' - 'a')));
}
}
return array;
}
I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}
I tested the program out with 88 and it was left with one star to complete the triangle. 87, two stars 86 three stars. This went on for certain numbers.
These are the two options for programming generate function
• One is to compute the length of the last line, say maxLen, and use a double for-loop to generate a line of one star, a line of two stars, a line of three starts, and so on, ending with a line of maxLen stars. The value of maxLen is the smallest integer that is greater than or equal to the
larger solution of the quadratic equation x ( x + 1 ) = 2 * num.
• The other is to use one for-loop to print num stars while executing System.out.println()wherever the newline is needed. The point at which the newline is needed can be computed using two accompanying integer variables, say len and count. Here the former is the length of the line being generated and the count is the number of stars yet to be printed in the line. We start by setting the value of 1 to both integer variables. At each round of the iteration, we decrease the value of count, if the value of count becomes 0, we insert the newline, increase the value of len and then copy of the value of len to count. When the loop terminates, if the value of count is neither equal to 0 nor equal to count, we extend the present line by adding more stars.
import java.util.*;
public class TriangleSingle
{
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
count = len;
}
}
if (count!= 0 || count != len)
{
System.out.println("*"); //Completes the triangle if needed
// This is the **problem spot**
}
Try this:-
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
for (int i = 1; i <= k; i++) {
System.out.print("*");
}
System.out.println();
}
}
The trick is to increment the count c of printed stars in the inner loop, which prints each row, but check it against the desired number n in the outer loop, which determines how many rows to print. This way we're sure to print complete rows, but we stop as soon as we've printed at least n stars.
public static void generate(int n)
{
for(int c=0, i=0; c<n; i++)
{
for(int j=0; j<=i; j++, c++)
System.out.print('*');
System.out.println();
}
}
Try this out !!!
public class pyramid {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Input Length of pyramid : ");
int length = s.nextInt();
for (int i = 1; i <= length; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*\t");
}
System.out.println("\n");
}
}
Check this out :
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x;)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
k++;
count = len;
}
}
How do I save it actually in the Array?
With this code it doesn't save anything in the array
I hope you can tell me more ways how to do it and explain in detail, thank you very much
import java.util.Scanner;
public class CountArray
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
int countPOZ = 0;
int countP5 = 0;
int countNONE = 0;
System.out.println();
System.out.print("Type elements: ");
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
}
System.out.println();
System.out.println(x[1]); //here it will display 0 because nothing is saved.. in the array
System.out.println("Positive: "+countPOZ);
System.out.println("Div.. with 5: "+countP5);
System.out.println("Others: "+countNONE);
}
}
You store a value in the ith position of your x array with:
x[i] = someValue;
In the context of your loop :
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
x[i] = numrat;
}
This stores the user's input in order.
x[i] = scan.nextInt();
Remove the local numrat and use x[i]. And please use braces, something like
x[i] = scan.nextInt();
if(x[i] > 0) {
countPOZ++;
} else if (x[i] % 5 == 0) {
countP5++;
} else {
countNONE++;
}
This is covered in and an example to JLS-10.4 - Array Access.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
Try, add values in array then use array for business logic.
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++){
System.out.print("Type numbers: ");
x[i] = scan.nextInt();
if(x[i] > 0)
countPOZ++;
else if (x[i] % 5 == 0)
countP5++;
else
countNONE++;
}
But you missing something int[] x = new int [scan.nextInt()] as per your code you are not passing only one element and add that element to your array.
I assist pass multiple elements as comma separated list 1,2,3,4,5,6,7 then in your code you can create array list int x[] = scan.nextInt().split(",") then use it.
in your code
int[] x = new int [scan.nextInt()];
you are defining the size of an array. you are not storing any elements in here.
So define any elements in an array you have to access it's index and store your value in that specific index
x[1] = scan.nextInt()
can store the values in specific index
Hi i am trying to auto populate a 2d array based on user input.
The user will enter 1 number, this number will set the size of the 2d array. i then want to print out the numbers of the array.
for example , if the user enters the number 4 . the 2d array will be 4 rows by 4 colums, and should contain the number 1 to 16, and print out as follows.
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
But i am struggling to think of the right statement that will do this.
for the moment my code just prints out a 2d array containing *.
Has anyone any ideas how i could print out the numbers , i'm really stuck.
my code follows:
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int num1 = input.nextInt();
int num2 = num1;
int length = num1 * num2;
System.out.println("room "+num1+"x"+num2+"="+length);
int[][] grid = new int[num1][num2];
for(int row=0;row<grid.length;row++){
for(int col=0;col<grid[row].length;col++){
System.out.print("*");
}
System.out.println();
}
}
Read n value,
int[][] arr = new int[n][n];
int inc = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
arr[i][j] = inc++;
Well, first of all you have to fill the array with the numbers. You can use your double for loop for this and a counter variable which you increment after each loop of the inner for loop.
int counter = 1;
for(int x = 0; x < num1; x++)
{
for(int y = 0; y < num2; y++)
{
grid[x][y] = counter++;
}
}
Afterwards you can output the array again with a double for loop.
I am not sure if I understand you right.
You have problem with the code printing *?
If yes, then the reason for that is this
System.out.print("*");
Should be
System.out.print(grid[row]);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room length");
int arraySize = input.nextInt();
System.out.println("Length: " + (arraySize*arraySize));
int[][] array = new int[arraySize][arraySize];
int count = 1;
for (int i=0;i<arraySize;i++) {
for (int j=0;j<arraySize;j++) {
array[i][j] = count;
if (j != (arraySize-1))
System.out.print(count + "-");
else
System.out.println(count);
count++;
}
}
}
This code should print out the numbers how you want them.