what happens when u increment array. {a[in.nextInt()]++;} - java

Please explain what is happening here as i dont understand what is getting incremented...
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[100];
for(int a_i=0; a_i < n; a_i++){
a[in.nextInt()]++; //here
}

You get the scanner tied to the system input (keyboard).
Scanner in = new Scanner(System.in);
Asking for an integer number n from the keyboard:
int n = in.nextInt();
Declaring an array of 100 int elements (from 0 to 99)
int[] a = new int[100];
And:
// Running a loop from 0 to the entered n value.
for(int a_i=0; a_i < n; a_i++){
// requesting an int number from keyboard in in.nextInt()
// and incrementing array element with the index obtained in in.nextInt()
a[in.nextInt()]++;
}
a[in.nextInt()]++; can be converted to code:
int idx = in.nextInt();
a[idx]++;

Related

Array method, return integers in the even positions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
import java.util.Scanner;
public class Trial7 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a array of numbers");
int n = input.nextInt();
int[] nums= new int[n];
int[] nums2= evenPositionsOnly(nums);
System.out.println(nums2);
}
public static int[] evenPositionsOnly(int[] nums){
//int[] result= new int[nums.length];
for(int i = 0; i<nums.length; i=i+2) {
if(i/2==0)
nums[i]= nums[i] ;
}
return nums;
}
}
This is an update. I keep getting error, but am unsure why. Can anyone help with what the problem may be?
Since the top part is mostly cookie-cutter, let's focus on the method evenPositionsOnly. We need to think about the logical steps to accomplish this task, "print the values found in the array where the index is even".
We need to have something to hold our found values. Let's call it evenIndexedValues:
int[] evenIndexedValues = new int[some size value here];
We need to know what size to make our new array. We know it's not going to be more than half the size of the original. We can add one just to make sure we have enough space, to keep this simple:
int size = (nums.length / 2) + 1;
int[] evenIndexedValues = new int[size];
Keep in mind that an int divided an int will only ever yield an int, with the "reminder" being truncated. So, if your array size is an odd number, (nums.length / 2) will yield a value that is less than the "real" half size; that's why we add one (although it's not actually necessary in this case, since our index won't reach that value).
Now that we have our container, we can loop through our nums array, grabbing the value found at each even index and inserting it into our new array:
int size = (nums.length / 2) + 1;
int[] evenIndexedValues = new int[size];
for(int index = 0; i < nums.length; i += 2){
}
But wait! How do we know where to put our even value? We can't use i, because that will have values like 0, 2, 4, etc. which would skip spots in our new array (not to mention go out of bounds pretty quickly). So, we need to define a local variable, and manually increment it by one each time through the loop:
int size = (nums.length / 2) + 1;
int[] evenIndexedValues = new int[size];
int j = 0;
for(int index = 0; i < nums.length; i += 2){
// some code here
j += 1;
}
So, the last bit is to add the code to insert our values, and then wrap this all in our method body:
public static int[] evenPositionsOnly(int[] nums){
int size = (nums.length / 2) + 1;
int[] evenIndexedValues = new int[size];
int j = 0;
for(int i = 0; i < nums.length; i += 2){
evenIndexedValues[j] = nums[i];
j += 1;
}
return evenIndexedValues;
}
Now that evenPositionsOnly is defined, let's think about what main should be doing. You start off mostly right:
Scanner input = new Scanner(System.in);
System.out.println("Please enter a array of numbers");
int n = input.nextInt();
int[] nums = new int[n];
The manner in which you use n suggests that your intention was to ask for how many numbers to enter. Assuming that's correct, let's correct the prompt:
Scanner input = new Scanner(System.in);
System.out.println("Please enter the size of the array to create");
int n = input.nextInt();
int[] nums = new int[n];
Once we have that, we need to either prompt for those values, or generate them randomly. I assume you're supposed to prompt, so:
Scanner input = new Scanner(System.in);
System.out.println("Please enter the size of the array to create");
int n = input.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++){
System.out.printf("Value #%i?: ", i+1);
int value = input.nextInt();
nums[i] = value;
}
Then, add the last two lines from your example, wrap it up in main, and you're pretty much done:
import java.util.Scanner;
import java.util.Arrays;
public class Trial7 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the size of the array to create");
int n = input.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++){
System.out.printf("Value #%i?: ", i+1);
int value = input.nextInt();
nums[i] = value;
}
int[] evens = evenPositionsOnly(nums);
System.out.println(Arrays.toString(evens));
}
public static int[] evenPositionsOnly(int[] nums){
int size = (nums.length / 2) + 1;
int[] evenIndexedValues = new int[size];
int j = 0;
for(int i = 0; i < nums.length; i += 2){
evenIndexedValues[j] = nums[i];
j += 1;
}
return evenIndexedValues;
}
}
Arrays.print is found in the same java.utils.* namespace as Scanner - it's up to you whether to use that or loop through the array and print each value manually. See What's the simplest way to print a Java array? for more suggestions.

Within a loop, is there a way to have the name of a variable change/depend on the value of the current index?

For example (we are told we want to go up to 'X'):
Scanner scan = new Scanner(System.in);
for (int i; i <= X; i++)
{
System.out.println("Enter the value for value " + i)'
int valuei = scan.nextInt();
}
So instead of constantly reasssining a value to the one variable 'valuei',
our program would create X number of integer variables as well as assigning them the corresponding user input as values.
'value1' gets the value the user had input as an answer at index 1
'value2' gets the value the user had input as an answer at index 2
...
'valuei' gets the value the user inputs as an answer at index i
If not possible, what would be the most efficient way to accomplish the above?
Thanks
It looks like you are wanting to use arrays
Scanner scan = new Scanner(System.in);
int arr [] = new int [X];
for (int i = 0; i < X; i++)
{
System.out.println("Enter the value for value " + i)'
arr[i] = scan.nextInt();
}
If you are just reading it then you can just need to read the value from user and it should be i<x because index starts at 0.
`Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
for (int i=0; i < x; i++) {
System.out.println("Enter the value for value " + i);
int valuei = scan.nextInt();
}`
If you want to read that in an array :
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int[] arr = new int[x];
for (int i = 0; i < x; i++) {
System.out.println("Enter the value for value " + i);
arr[i] = scan.nextInt();
}
You can use an array
int []valuei = new int[X];
valuei [0] gets first input.
valuei [1] gets second input.
....
valuei [X-1] gets Xth input.
Scanner scan = new Scanner(System.in);
int []valuei = new int[X];
for (int i=0; i < X; i++)
{
System.out.println("Enter the value for value " + i);
valuei[i]=scan.nextInt();
}
Arrays.
An array is a container object that holds a fixed number of values of a single type
For example:
int[] value = new int[X];
for (int i=0; i < X; i++)
{
System.out.println("Enter the value for value " + i);
value[i] = scan.nextInt();
}
Also note how loop changed to int i=0; i < X; i++

How Can this code be adjusted to input and print a list of numbers?

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

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++]);

User input arrays

I am trying to create a program that sorts user inputted integers from greatest to least. Also I need to find a way to print the maximum and minimum numbers. The code was sorting fine when I had defined values but now that I have switched it to user input it sends back "0"s for some reason. This is my code
import java.util.Scanner;
public class SortInteger {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i>number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length-1; i++){ //outputs the array to user
System.out.println(number[i]);
}
}
}
you have taken only one number
int num = input.nextInt();
and you are using it for array size :
int number [] = new int [num];
but in rest of the code you haven't taken any input so your array is empty.
Code::
import java.util.*;
class test{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please input three numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int number [] = {num1,num2,num3}; //Sorting Array
int temp;
boolean correct = false; // Forces the sorting to continue till the numbers are in order
while(correct ==false){
correct = true;
for(int i = 0; i<number.length-1; i++ ){
if(number [i] > number [i+1]){
temp = number [i+1];
number [i+1] = number[i];
number[i]= temp;
correct = false;
}
}
}
for(int i = 0; i<number.length; i++){ //outputs the array to user
System.out.println(number[i]);
}
}}
Output::
Please input three numbers
1
5
4
1
4
5
you are only initializing your array. you never initialized your array with elements, thus your array elements get default values.
System.out.println("Please enter size");
int num = input.nextInt();
int number [] = new int [num]; //Sorting Array
for(int i=0; i<number.length; i++){
System.out.println("Please enter element at index " + i);
number[i] = input.nextInt()
}
As others pointed out you need to populate your array with multiple values, currently you are requesting only one int.
Also, are you sure that works? Should't your first for loop read:
for(int i = 0; i<number.length-1; i++ )
Instead of:
for(int i = 0; i>number.length-1; i++ )
On a side note, it looks to me that your sorting algorithm is O(n2) you may want to look into mergesort and quicksort.

Categories

Resources