how to automatically populate a 2d array with numbers - java

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.

Related

Multidimensional arrays from standard input

I'm trying to figure out how to read in a multidimensional array from standard input given the user provides the row and col size followed by integers of the array
e.g. Input:
2 3 <= row, col of array
8 3 10 < array integers
7 9 6
My code is currently:
int colA = scan.nextInt();
int rowA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i <rowA;i++){
for (int j=0; j<colA;j++){
array1[i][j] += scan.nextInt();
}
}
And the output of my array is: [[8,3,10,7,9,6]] but what I'd like to do is output [[8,3,10],[7,9,6]]
Here first the row and col value got from users is reversed that is the only mistake i could see
import java.util.Arrays;
import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rowA = scan.nextInt();
int colA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colA; j++) {
array[i][j] += scan.nextInt();
}
}
for (int[] innerArray : array) {
System.out.println(Arrays.toString(innerArray));
}
}
}
This is a working one
There are some errors in your code.
You inverted the order of the dimensions asked to the users.
Use this:
int rowA = scan.nextInt();
int colA = scan.nextInt();
Instead of this:
int colA = scan.nextInt();
int rowA = scan.nextInt();
You wrote array1 instead of array in array1[i][j] += scan.nextInt();
Note that you can use array[i][j] = scan.nextInt(); instead of array[i][j] += scan.nextInt()

How do I make a calculator that multiplies more than two numbers?

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;
}

Adding Items to an array in Java

I wanted to create an array that has a length specified by the user, and also wanted to have it filled by a loop command, and then it should be copied to another array by another loop command, so I wrote a code but it generates an error when trying to run it
Scanner input = new Scanner(System.in);
System.out.print("Hello, Please enter the amount of numbers: ");
int n = input.nextInt();
int array1[] = new int[n];
int array2[] = new int[n];
System.out.print("Please enter your numbers: ");
for (int i = 0; i < n; i++) {
int index = input.nextInt();
array1 [index] = array1 [i];
}
for (int i = 0; i < n; i++) {
array2[i] = array2[i];
}
System.out.println("Array 1 is: " +Arrays.toString(array1));
System.out.println("Array 2 is: " +Arrays.toString(array2));
so the code runs with a single issue that all the elements are set to zero if I entered the elements of the array less than the size of the array "n".
but if for example, I entered the size is 5, and tried to fill the array, the program crash if I tried to add any number larger than 5 in the array.
I know that the problem sounds silly, but I'll be grateful if you guys helped me out with it.
You have two problems in your code.
Substitute your for(s) with the following code:
for (int i = 0; i < n; i++) {
int element = input.nextInt(); //elemet inserted by the user
array1[i] = element;
}
for (int i = 0; i < n; i++) {
array2[i] = array1[i];
}
for add item in array
for (int i = 0; i < n; i++) {
int index = input.nextInt();
array1 [i] = index ;
}

sum of remaining array numbers after user input

hi guys i've had some help with this program today, basically what i want is for an array of 1 - 200 to be held, then the user inputs a number between 1 and 200.
The ramaning numbers are then added together and the answer outputted.
e.g. user enters 100, numbers from 100-200 are then added together and answer is output.
With the code i have so far it is always outputting 0 as the answer. Any ideas?
thanks.
//Importing scanner
import java.util.Scanner;
//Class name
class programfive{
//Main method
public static void main (String[]args){
//declaring and inizialising scanner
Scanner input = new Scanner (System.in);
//Declaring and inizialising variables
int userInput = 0;
int sum = 0;
//Array initializer
int array[] = new int [201];
//Prompt for user input
System.out.print("Please enter a value between 1 and 200: ");
userInput = input.nextInt();
//For loop - starts at number user inputted, stops when reaches 200, increments by 1.
for (int i = userInput; i<=200; i++)
{
sum += array[i];
}
System.out.println(sum);
}//End of main method
}//End of class
Because you haven't put anything in your array, it contains the default int value at each index, and that is 0 .
You have to fill it with the values you want, so that array[0] contains 0, array[1] contains 1, etc..
int array[] = new int [201];
for(int i=0; i<array.length;i++)
array[i] = i;
Also, you could get rid of the array and get the same result :
for (int i = userInput; i<=200; i++)
{
sum += i;
}
you need to initialize the array first, or changing the sum loop to:
for (int i = userInput; i<=200; i++)
{
sum += i;
}
Untested but should work:
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
int userInput = 0;
int sum = 0;
System.out.print("Please enter a value between 1 and 200: ");
userInput = input.nextInt();
for (int i = userInput; i<=200; i++)
sum += i
userInput.close();
System.out.println(sum);
}
you forgot to populate your array with numbers currently all of your array elements are pointing to the default value of 0.
add this line of code after the array declaration and your good to go:
for(int i=0;i<array.length;i++)
array[i]=i;
System.out.println("Enter five numbers: ");
Scanner scanner = new Scanner(System.in);
int[] array = new int [5] ;
for (int i =0; i < array.length; i++){
array[i] = scanner.nextInt();
}
int sum = 0;
for (int i : array){
sum = sum +i;
}
System.out.println(sum);

Adding to arrays and printing arrays in Java

I need help figuring out how to get the user to input a number of integers no more than 10, and then add them to an array and print them out from the array. The code I have below, when run, asks the user for the integers and then runs forever and doesn't work. What am I doing wrong?
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");
int[] nextNumber = new int[10];
int i = 0;
int number = input.nextInt();
while (i < nextNumber.length){
i++;
nextNumber[i] = number;
number = input.nextInt();
}
int a = 0;
while (a < nextNumber.length){
a++;
System.out.println(nextNumber[a]);
}
Seems to me like you increment your index too fast. You should increment your index variables at the end of your loops, not the beginning.
I would suggest you use for loops instead since they are designed for that:
Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");
int[] nextNumber = new int[10];
for (int i = 0; i < nextNumber.length; i++){
nextNumber[i] = input.nextInt();
}
for (int a = 0; a < nextNumber.length; a++){
System.out.println(nextNumber[1]);
}
Also, although I did not change it in the code, it seems like your last line should be:
System.out.println(nextNumber[a]);
Increment the array index after the values have been assigned to the arrays
while (i < nextNumber.length) {
number = input.nextInt();
nextNumber[i] = number;
i++;
}
The same applys to the second loop
while (a < nextNumber.length) {
System.out.println(nextNumber[a]);
a++;
}
Problem 1
Change
int i = 0;
int number = input.nextInt();
while (i < nextNumber.length){
i++; //here is one problem. you not assigning the value to nextNumber[0].
nextNumber[i] = number;
number = input.nextInt();
}
to
int i = 0;
while (i < nextNumber.length){
number = input.nextInt();
nextNumber[i] = number;
i++;
}
Problem 2
change
int a = 0;
while (a < nextNumber.length){
a++; //here is one problem ..You never get nextNumber[0] value
System.out.println(nextNumber[a]);
}
to
int a = 0;
while (a < nextNumber.length){
System.out.println(nextNumber[a]);
a++;
}
You can easily do this as follows. Better use for loop since you know the maximum number of iterations.
Scanner input = new Scanner(System.in); // create a new scanner
System.out.print("Enter integers between 1 and 100\n ");
int[] nextNumber = new int[10];
int i = 0;
while (i < nextNumber.length) nextNumber[i++] = input.nextInt();
int a = 0;
while (a < nextNumber.length) System.out.println(nextNumber[a++]);

Categories

Resources