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 ;
}
Related
If you are accepting integers simultaneously one after another for a different array each time an int is accepted, then how do you form a third array with the digits of the 2 other arrays in the order in which they are accepted?
import java.util.Scanner;
class Integer_Acceptor
{
public static void main()
{
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
for (int i = 0; i < 10; i++)
{
if (i%2 != 0)
{
c[i] = a[i];
c[i+1] = b[i];
}
}
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
}
}
This is the program I made but obviously it doesn't work (ArrayOutofBounds) as the integer in array increases by 2 every time. How do I make this program give the combined integers of both arrays in the order in which they are accepted?
The idea of separating the inputs is interesting, but it seems to be giving you more problems than solutions when trying to join them together later.
Why not just accept everything into a single array, and when reading it, you test its index to see where it should go? If you have two possible uses for your numbers, odd and even positions will get you there; if three, multiples of 3 plus or minus one, and so on.
This seems to be a simpler solution, and both the input and data storage are as straightforward as can be.
The code you provided will give an ArrayOutofBounds error as you mentioned because c[10] does not exist. (In the second for loop when i = 9, you will be trying to set c[10] which does not exist).
From what I understand, you want array c to contain the following elements:
c = { a[0], b[0], a[1], b[1], a[2], b[2], a[3], b[3], a[4], b[4] }
What I did was to create two separate indices that will help navigate through array a and array b and set c[i] according to whether i was even or odd and then incrementing the respective aIndex or bIndex. I wrote this code below that works the way I described
System.out.println("\f");
Scanner sc = new Scanner(System.in);
int a[] = new int[5];
int b[] = new int[10];
int c[] = new int[10];
System.out.println("Enter an integer into each array simultaneously");
for (int i = 0; i < 5; i++)
{
a[i] = sc.nextInt();
b[i] = sc.nextInt();
}
// Fixed code snipped
int aIndex = 0;
int bIndex = 0;
for (int i = 0; i < 10; i++)
{
// even index
if(i%2 == 0){
c[i] = a[aIndex];
aIndex++;
}
else
{
c[i] = b[bIndex];
bIndex++;
}
}
////
System.out.println("Array contents are");
for (int i = 0; i < 10; i++)
{
System.out.println(c[i]+"\t");
}
Let me know if you need further clarification on how this works so I can edit in a more in-depth explanation.
Hello Guys i just need help this is the problem I want to solve:
Input data will contain the total count of pairs to process in the
first line.
The following lines will contain pairs themselves - one pair at each
line.
Answer should contain the results separated by spaces.
Example:
data:
3
100 8
15 245
1945 54
answer:
108 260 1999
i write the code and here it is
public class SumsInLoopAdvanced {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
int a =0;
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
a = arr[j]+arr[i];
}
System.out.print("Answer: \n" + a);
}
}
}
it just 245+15 the wrong answer so could you help me ??
your code is broken here:
for (int j = 0; j < num; j++) {
arr[j] = reader.nextInt();
}
because you are overwriting the previously filled array: arr[i]
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
If i got it right you need to print a sum of two arrays entries for each index.
First of all you are using the same array and you are overwriting everything that you did in a first loop by the second loop.
int arr [] = new int[250];
for (int i = 0; i < num; i++) {
arr[i] = reader.nextInt();
}
for (int j = 0; j < num; j++) {
//writing into the same array starting with 0 index
arr[j] = reader.nextInt();
}
And if I got this exercise right you don't need a nested loop, you need to to find a sum of two array elements from different arrays with the same index.
something like this:
for (int i = 0; i < num; i++) {
a = arr1[i] + arr2[i];
System.out.print(a + " ");
}
You're overwriting the values in arr on your second loop.
If you want to collect two sets of values, you'll need two arrays. (Well, not need, but that would be the reasonable way.) Also note that you don't need or want the nested loop at the end; just add the ith entry from the first array to the ith entry of the second.
Side note: Instead of a hardcoded upper bound on the array (250), use num so you know it's always big enough (e.g., if I tell you I'm going to enter 300 numbers, your code will blow up). int[] arr = new int[num];
But, now that the problem you're trying to solve is quoted in the question, note that your code doesn't want to read in a bunch of values, then read in a second bunch of values, and then add those together. The assignments says you'll enter things like "100 8" and then "15 245" and be meant to add those to get 108 and 260.
So you'll need to read the first number, then the second, add those and store them in your (one) array; then read the next third number, and the fourth, add those together and store them; and then output the results.
I'm trying to create a program that allows the user to input numbers into a array called "numArray", however an exception is thrown once the user inputs numbers into array. How can this be fixed?
import java.util.Scanner;
class ArrayNumList
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many nums would you like to enter? ");
int n = in.nextInt();
System.out.println("Enter " + n + " nums");
int[] numArray = new int[n];
for(int i = 0; i <= n; i++)
{
int index = in.nextInt();
System.out.print(numArray[index]);
}
}
}
There is no index index if the user inserts a big enough number / negative number. Fix it by using the actual loop variable i like this:
for(int i = 0; i <= n; i++) {
numArray[i] = in.nextInt();
System.out.print(numArray[i]);
}
The problem is that you aren't storing your data anywhere in the array.
for(int i = 0; i <= n; i++)
{
int index = in.nextInt();
System.out.print(numArray[index]);
}
Every time you run through the array, you store your input into the variable index. From there, you try to display the value in your array at that index. This can lead to a few problems.
1) You haven't put your numbers into this array yet, so each value in the array is going to be 0. To fix this:
numArray[i] = in.nextInt();
2) If someone inputs a number that's bigger than the size of your array, you'll get an IndexOutOfBoundsException. I don't think you were trying to do it this way, but this is what your code is currently attempting to do.
There are 3 issues:-
1) Use i < n as you start from 0
2) Trying to add input value as index in the array.
3) Printing out the values while entering which create confusion for you better to do that in separate loop but I leave it to u or Better to use println instead of print
Try this:-
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.println("How many nums would you like to enter? ");
int n = in.nextInt();
System.out.println("Enter " + n + " nums");
int[] numArray = new int[n];
for(int i = 0; i < n; i++)
{
numArray[i] = in.nextInt();
System.out.println(numArray[i]);
}
}
Firstly it should be i<n and not i<=n because n means the array length and i means the array index. The index starts from 0. For eg an array holds the values 1234, so the length is 4 but the index are 0,1,2,3. So the index is always one less than the array length. Also you have to store the input with the array index.
for(int i = 0; i < n; i++)
{
numArray[i] = in.nextInt();
}
And then later print it
for(int i = 0; i < n; i++)
{
System.out.println(numArray[i]);
}
I'm trying to write a program where on the first line, you enter the number of times you want a for loop to iterate, on the second line, you enter the value of the array, and on the third line, you enter the numbers that you want in the array. My program either does not do what I want it to do, or it crashes on me. This is the code that I have for the program so far:
import java.util.*;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = input.nextInt();
for (int i=0; i<n; i++)
{
int value = input.nextInt();
int[] arr = new int[value];
arr[i] = input.nextInt();
}
}
What can I do? Please help. I've tried everything! Also, it would help if someone could help me with sorting the numbers in ascending order, followed by displaying the middle number in each line, but first thing's first. Thank you.
I believe this is more of what you are after. I output the entries individually but you could combine that easily enough.
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
try
{
System.out.println("Number of times to loop:");
int numEntries = input.nextInt();
int[][] valueArrays = new int[numEntries][];
for (int i=0; i<numEntries; i++)
{
System.out.println("Size of array #"+i+": ");
int arrayLen = input.nextInt();
int[] inputArray = new int[arrayLen];
for (int j = 0; j < arrayLen; j++)
{
System.out.println("Enter value at index "+j+": ");
inputArray[j] = input.nextInt();
}
Arrays.sort(inputArray);
valueArrays[i] = inputArray;
}
for (int l=0; l < valueArrays.length; l++)
{
int[] values = valueArrays[l];
for (int m=0; m < values.length; m++)
{
System.out.println("Value of array #"+l+" saved at index "+m +": " + values[m]);
}
if ((values.length % 2) == 0)
{
int start = values.length/2;
int end = start + 1;
System.out.println("Middle values in array #"+l+" saved at indices " + start + " and " + end);
}
else
{
int start = values.length/2;
System.out.println("Middle value in array #"+l+" saved at index " + start);
}
}
}
finally
{
input.close();
}
}
You're creating a new array on each iteration inside the loop.
You should get int[] arr = new int[value]; out of the loop:
int arraySize = input.nextInt();
int[] arr = new int[arraySize];
for (int i=0; i<arraySize; i++)
{
int value = input.nextInt();
arr[i] = value;
}
If you don't want to limit the user for a size, use an ArrayList instead.
Problem 1:My program either does not do what I want it to do.
Dont initialize array inside for loop as loop wiil create a new array every time you iterate it.
Scanner input = new Scanner (System.in);
System.out.println("Enter no. of elements in array");
int n = input.nextInt();
int[] arr = new int[n];
System.out.println("Array length set to "+n);
for (int i=0; i<n; i++)
{
System.out.println("Enter value for index "+i);
arr[i] = input.nextInt();
System.out.println(arr[i]+" Value saved at index "+i);
}
DEMO1
Problem 2(described in comments below):Sorting arrays and displaying the middle number
class Ideone
{
static int[] countingSort(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
}
int[] sortedNumbers = new int[max+1];
for (int i = 0; i < numbers.length; i++) {
sortedNumbers[numbers[i]]++;
}
int insertPosition = 0;
for (int i = 0; i <= max; i++) {
for (int j = 0; j < sortedNumbers[i]; j++) {
numbers[insertPosition] = i;
insertPosition++;
}
}
return numbers;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner (System.in);
System.out.println("Number of times to loop:");
int n = input.nextInt();
// int[] arr = new int[n];
// System.out.println("Array length set to "+n);
for (int i=1; i<=3; i++)
{
System.out.println("Size of array #"+i+": ");
int alen = input.nextInt();
int[] arr = new int[alen];
System.out.println("Value in array #"+i+": ");
for (int j=0; j<alen; j++){
System.out.println("Enter value at index "+j+": ");
arr[j] = input.nextInt();
}
arr=Ideone.countingSort(arr);
for (int l=0; l<alen; l++)
System.out.println(arr[l]+" Value of array #"+i+" saved at index "+l);
System.out.println("Middle value in array #"+i+" saved at index "+arr[alen/2]);
}
}
}
DEMO2
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.