How to find missing number in array by taking user input - java

This is my code and Iam getting ArrayIndexoutofBoundsException and cant able to find where
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int sum=0,sumtotal;
Scanner sc = new Scanner(System.in);
System.out.println("Enter x");
int x = sc.nextInt();
sumtotal = (x+1)*(x+2)/2;
System.out.println("Enter the size of array");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter values of array");
for(int i = 0;i<n;i++){
a[i] = sc.nextInt();
}
for(int i = 0;i<=a.length;i++)
sum = sum+a[i];
int miss = sumtotal-sum;
System.out.println(miss);
}
}
I put size of array 5 values are 1,2,4,5,6
and value of x is 5

You need to change the for loop from
for(int i = 0;i<=a.length;i++)
to
for(int i = 0;i<a.length;i++)
because the range of i is from 0 to 5 and your array a have index from 0 to 4 only.

Related

How Arrays.sort function works?

I am new to java programming and i am trying to sort arrays using Arrays.sort() function. After using Arrays.sort(array),I am printing the final sorted array.
For example:
Input : 1 3 2 4
Output comes as : 0 0 0 0.
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,temp,count;
int[] array = new int[MAX_SIZE];
n = input.nextInt();
for(int i = 0 ; i < n ; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for(int i = 0 ; i < n ; ++i) {
System.out.print(array[i]+" ");
}
}
}
You have initialized you array to hold 20 integers but you input only 5. Hence the first 15 elements will be 0 followed by the numbers you have inputted once the array is sorted.
To fix the issue you can initialize the array with n instead of MAX_SIZE as shown below:-
n = input.nextInt();
int[] array = new int[n];
Set the size of the array to match what your input should be, not to the maximum allowed size:
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, temp, count;
n = input.nextInt();
if (n > MAX_SIZE) {
//handle error somehow
}
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; ++i) {
System.out.print(array[i] + " ");
}
}
}
When you initialize an array in Java it gets default value of 0 for primitive int:
int[] array = new int[MAX_SIZE];
The fact that you are not seeing your desired input of 1,2,3,4 is a separate problem with your Scanner code.

I have to take integers in an array and output them in random order

This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[i] + " ");
}
}
}

Showing a null value instead of token value

I am creating this code where I am supposed to prompt the user for a maximum of 5 integer numbers. I should store the 5 integers in an array by asking the user to enter them until the array is full or the user exits by entering -99. Then I should print out all the values of the array and calculate the average. The problem is that when I scan and store the values it shows me a null value of 0 of the fifth number instead of the number itself and it does not count it with the sum. This is the piece of code I've been working with:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num==-99 || i==4){
for(int k=0; k<i+1; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/i);
cond = true;
}
number[i] = num;
i++;
}while(!cond);
}
This is the input : 1 2 3 4 5
Every number is on a separate line
This is the output:
run:
1
2
3
4
5
1
2
3
4
0
2.5
number[i] = num;
is what adds the number the user entered to the array. If they enter -99, it's in the correct place. If they've simply entered all 4 however, it is in the wrong place. Also, you have it so it is actually dividing by the wrong number. Something like this should work:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num!=-99){
number[i] = num;
i++;
}
if(num==-99 || i==5){
for(int k=0; k<i; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/(i));
cond = true;
}
}while(!cond);
}
Also, do while loops are really ugly, and you can do it much smoother with just two for loops:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] number = new int[5];
double sum = 0;
int num=0,i;
for(i=0;i<5&&num!=-99;i++){
num = scan.nextInt();
number[i] = num;
}
for(int k=0;k<i;k++){
System.out.println(number[k]);
sum+=number[k];
}
System.out.println(sum/(i+1));
}

Create multiple arrays using a for loop

I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
This is the code I was using, but it doesn't work:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs?
The problem is that each time you are creating the array.
try this:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (i) and then continues to fill the arrays.
To check whether two collections have no commons values, you can use
Collections.disjoint();
For other operations, you can look here
This should work (with bidimensionnal array)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++")
This should work and solve their first point
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}

Scanner input issue

How do I take in input from a user from a scanner, then put that input into a 2D Array. This is what I have but I dont think it is right:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
while (in.hasNextInt())
{
int a[][] = in.nextInt();
a [row][col] = temp;
temp = scan.nextInt();
}
Square.check(temp);
}
What I am trying to do is create a 2D array and create a magic Square. I have the boolean part figured out, I just need help with inputting users sequence of numbers into the array so the boolean methods can test the numbers. All help greatly appreciated
I don't believe your code will work how you want it to. If I'm understanding your question correctly, here's what I would do:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int [][] a = new int[row][col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
System.out.print("Enter integer for row " + i + " col " + j + ": ");
a[i][j] = in.nextInt();
}
}
// Create your square here with the array
}
In the loops, i is the current row number and j is the current column number. It will ask the user for every row/column combination.
You can use that in order to enter all number at the same time :
int [][] a = new int[3][3];
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers: ");
int row=0,col=0;
while (in.hasNextInt())
{
a [row][col++] = in.nextInt();
if(col>=3){
col=0;
row++;
}
if(row>=3)break;
}
Then you can enter :
1 2 3 4 5 6 7 8 9
to fill your array.

Categories