reading input into array without hard coding - java

So I was thinking that maybe other people might have had this problem. I'm a total beginner .I am using java to program for android so I can test on my phone. When I read in inputs from my array,
example:
int[] myArray = new int[5];
I tend to hard code the inputs into the array.
int input1= nextInt("input1");
int input2= nextInt("input2");
etc..
myArray[1]= input1;
myArray[2]= input2;
etc..
but this is time consuming, especially if the bounds of the array are higher.
ie.
int[] myArray = new int[50];
So my question is, how is this all done the shortest way possible? without the timely hard coding.

This is my suggestion if you know the input length:
int[] arr = new int[50];
for(int i = 0; i < arr.length; i++)
arr[i] = nextInt("input" + i);
Else I would suggest using a while-loop and an ArrayList.

You should consider using a for loop or while loop to save time and for repetitive actions.
e.g,
for(int counter = 0; counter < myArray.length; counter++)
{
myArray[counter] = counter;
}

Use loops:
for(int i=0; i<myArray.length; i++){
myArray[i] = nextInt("input" + (i + 1));; // or whatever...
}

Related

Is there a way to loop through a variables using a 'for' loop?

int oct1 = scan.nextInt();
int oct2 = scan.nextInt();
int oct3 = scan.nextInt();
int oct4 = scan.nextInt();
for(int i=1; i<5; i++){
System.out.println(oct+i);
}
This is my code and basically, I'm just wondering how I would go about looping through each of the oct variables.
I obviously know that the current print wouldn't work, but is there a way to make it so that a for loop can print each variable without just using four lines to print them all?
Ideally to handle many values and iterate them you should use a List implementation, an ArrayList is one of them. This could be an alternative way, more scalable and efficient.
List<Integer> octList = new ArrayList<Integer>();
octList.add(scan.nextInt());
octList.add(scan.nextInt());
octList.add(scan.nextInt());
octList.add(scan.nextInt());
for (int i = 0; i < octList.size(); i++) {
System.out.println(octList.get(i));
}
You can store them in an array, and then reference them based on index:
int[] arr = new int[]{scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt()};
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
For local variables and method parameter it is not possible. You can use an Array or a List to store the values and iterate.
For instance, using array,
// Declare an array of size 4
int oct[] = new int[4];
// Take input from user 4 times
for(int i = 0; i < 4; i++){
oct[i] = scan.nextInt();
}
// Print the array
for(int i = 0; i < 4; i++){
System.out.println(oct[i]);
}
Also check Is there any way to loop though variable names?.
Oracle have a very good introductory tutorial on arrays.
Oracle Tutorial On Arrays
There are two ways using standard Arrays. In my first solution, I assume the values oct1 ... oct4 have been populated. However, after the following example is another solution that does not assume this and also takes input using Scanner.
int[] values ={oct1, oct2, oct3, oct4};
// Two examples:
// Using a 'for each' loop to display values
for(int value : values){
System.out.println(value);
}
// Using a standard 'for' loop to display values
for(int i; i < values.length; i++){
System.out.println(values[i]);
}
This solution uses an array and reads into it using the Scanner, but you must know how many values are to be read in advance or else you will need to learn lists.
int count = 4;
int[] values = new int[count];
Scanner scan = new Scanner(System.in);
// Using a standard for loop to read in values
for(int i; i < values.length; i++){
System.out.println("Enter a number");
values[i] = scan.nextInt();
}
// Using a standard 'for' loop. Assume this
// would come later in the program because
// you would otherwise read in and display
// the values in a single loop.
for(int i; i < values.length;i++){
System.out.println(values[i]);
}
Use a map to name the values:
Map<String, Integer> values = new LinkedHashMap<>();
for (int i = 1; i < 5; i++) {
values.put("oct" + i, scan.nextInt());
}
for (Map.Entry<String, Integer> value : values) {
System.out.println(value.getValue());
}
Or to output their name too:
for (Map.Entry<String, Integer> value : values) {
System.out.println(value.getKey() + " = " + value.getValue());
}
And to get them:
int v = values.get("oct2");
There are two ways using standard Arrays. In my first solution, I assume the values oct1 ... oct4 have been populated. However, below is a solution that does not assume this.
int[] values ={oct1, oct2, oct3, oct4};
//Two Examples:
//Using a for each loop
for(int value : values){
System.out.println(value);
}
//Using a standard for loop
for(int i; i < values.length;i++){
System.out.println(values[i]);
}
This solution assumes no array, but you must know how many values are to be read in advance or else you will need to learn lists. Remember to import scanner with import java,util.Scanner; at the top of the class file you are using this code.
int count = 4;
int[] values = new[count];
Scanner scan = new Scanner(System.in);
//Using a standard for loop
//Assume this would go later in the
//program or else use a single loop
//to read in and display the values.
for(int i; i < values.length;i++){
System.out.println("Enter a number");
values[i] = scan.nextInt();
}
//Using a standard for loop
for(int i; i < values.length;i++){
System.out.println(values[i]);
}

I didn't understand the statement in the for loop! can any one please elaborate this?

int[] a = new int[101];
int n = in.nextInt();
for(int i = 0; i < n; i++){
a[in.nextInt()]++;
}
a is an array that is initialized; the next line get's you the amount of numbers that will follow after that.
Assuming that in is an initialized Scanner, nextInt() will read the next int from the console. Usually on websites like codingames.com or apparently hackerrank use this construct to put in data for your code to test it.
In the loop the code will read an index to be used in the pre-initialized array to increase the value by one at that given index.
That is basically it. To make it clearer, you could write:
int[] a = new int[101];
int numberOfIntsToFollow = in.nextInt();
for(int i = 0; i < numberOfIntsToFollow; i++){
int x = in.nextInt();
a[x]++;
}

User input numbers into a 2 dimensional array in java

I'm having trouble with user input in java, hope anyone can help :)
The user declares how big the 2d array will be(number d is the side of the square array), then inputs a number "n", which tells the program how many inputs of numbers there will be, and then needs to input these numbers (eg. if n=4, the input must be sth like : 5 17 3 20.
I have already written the same thing for a single row array
for(i=0;i<=n;i++) {
arr[i]=sc.nextInt();
}
but am having trouble doing basically the same for the 2d array.
Any ideas?
Use two nested loops and index like arr[i][j]
int d=sc.nextInt(); //length of rows and columns
int n=sc.nextInt(); //user input how many numbers
int[][] array=new int[d][d]; //length and heigth of array
for (int i=0;i<d;i++) {
for(int j=0;j<d;j++) {
array[i][j]=sc.nextInt();
}
}
int distance=0;
int c=0;
for(int i=0;i<d;i++){
for(int j=0;j<d;j++){
array[i][j]=c;
c++;
}
}
that in the end is sth else, I just wanted for the whole thing to be seen, if maybe I missed something elsewhere.
Sorry I don't have the ability to comment yet so I am posting this as an answer. Essentially you need to use a nested for loop as stated above. I will provide you a basic template
for (int i = 0; i < length; i ++){
for (int j = 0; j < width; j ++){
if (counter < userInput){
counter++;
arr[i][j] = value;
} else {
break;
}
}
}

How to replace single element of array

I will have a series of random arrays similar to.
array1[] = {1,2,3,0,0,5,6}
array1[] = {1,2,0,0,4,5,6}
I want them to end up like, so I replace the first 0 with X.
array1[] = {1,2,3,X,0,5,6}
array1[] = {1,2,X,0,4,5,6}
the code I'm using replaces all zeroes giving instead of just one.
array1[] = {1,2,3,X,X,5,6}
array1[] = {1,2,X,X,4,5,6}
Which isn't what I'm looking for. I'd be happy just replacing either one but only one.
The code I'm using,
for(int i=0; i<array.length; i++){
if(fruit[i] == 0)
fruit[i]=X;
}
Hope that was clear, thanks for any help! Being stuck at this for a little while now.
Try using break.
for(int i = 0; i < array.length; i++) {
if(fruit[i] == 0) {
fruit[i] = X;
break;
}
}
This will ensure only one is changed, max.

ArrayIndexOutOfBoundsException when trying to reverse an array

This seems simple enough but I get the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at reverse.main(reverse.java:28)"
I initially take inputs from the user to write an array, and then I want to print the array backwards. I understand there are other ways of doing this, but I mainly want to know why this is not working. Going through it line by line makes sense?
PS. If it's not a problem, is there any better way of doing this?
import java.util.Scanner;
public class reverse {
/**
* #param args
*/
public static void main(String[] args) {
System.out.printf("Enter the number of values in array: ");
Scanner scanner = new Scanner(System.in);
int n;
n = scanner.nextInt();
double[] a1 = new double[n];
int i;
System.out.printf("Enter the value in the array: ");
for (i = 0; i < n; i++){
Scanner scanner2 = new Scanner(System.in);
a1[i] = scanner2.nextInt();
}
double j;
double k;
for (i = 0; i < n/2; i++){
j = a1[i];
k = a1[n-i]; //error line;
a1[i]=k;
a1[n-i]=j;
}
for(i = 0; i < n; i++){
System.out.println(" "+a1[i]);
}}
}
When i = 0, n-i will result in n, which is one larger than the available indexes( 0 -> n-1 ).
for (i = 0; i < n/2; i++){
j = a1[i];
k = a1[n-i]; //error line;
a1[i]=k;
a1[n-i]=j;
}
Collections.reverse(Arrays.asList(array))
Will reverse an array for you, then just print its values out. It's great to do these kinds of problems as exercises but if you're ever woring in the industry it's usually better to rely on the Java API for trivial things like this. Probably going to be faster and a lot more simpler than anything you can come up with.
As said by Samhain, when i = 0, then n-i == n, which is greater than the last index of the array (since arrays start with index 0).
The simplest solution is to just subtract an additional 1 from n-i.
j = a1[i];
k = a1[n-i-1];
a1[i]=k;
a1[n-i-1]=j;
Also, creating a new Scanner is totally unnecessary. Just continue to use the first one you created.
for (i = 0; i < n; i++){
a1[i] = scanner.nextInt();
}
Finally, for what it's worth, if you're using nextInt you don't need to declare your array as a double[] (nor do j and k need to be doubles). You can just use ints.
Here's it running on ideone.

Categories

Resources