I just learned the array function in Java and now I wanted to store numbers from 1-19 in an array but don't know the right way to do it without the userinput function. Here is what I got, can you tell me if it is the right way to store number in array?
public class ArrayQuestion1 {
public static void main(String[] args) {
int a=0;
int array[] = new int [20];
for ( array[a]=1; array[a]<=19; array[a]++){
System.out.println(array[a]);
}
}
}
You would do something like this to fill your array with consecutive numbers from 0-19
public class ArrayQuestion1 {
public static void main(String[] args) {
int array[] = new int [20];
for (int a = 0; a < array.length; a++){
array[a] = a;
}
}
}
To store userinputs to int array you can do
int array[] = new int [20];
Scanner scanner=new Scanner(System.in);
for ( i=0; i<array.length; i++){
array[i]=scanner.nextInt();
}
If you want to store number from 0 to 19 you can do
int array[] = new int [20];
for ( i=0; i<array.length; i++){
array[i]=i;
}
public static void main(String[] args) {
int array[] = new int[20];
for (int i = 1; i < array.length; i++){
array[i] = i;
}
//To print all the elements in the array.
for(int j=1; i< array.length; j++){
system.out.println(array[j]);
}
}
You can insert into the array using the above method and can view the contents of array also.
If you want to add consecutive numbers you can use a simple for loop and to see them on the screen you can just iterate your array. That is all. Hope this can help you!
class Main {
public static void main(String[] args) {
int a=0;
int array[] = new int [20];
for(int i = 0 ; i < array.length ; i++){
array[i] = i;
}
for(int x : array){
System.out.println(x);
}
}
}
If you don't want user input for array , you have to store numbers manually in the array like ,
int a=0;
int array[] = new int [20];
for ( a=1;a<=19; a++){
array[a]=a;
}
above code will store 0 to 19 in your array . than you can use below for loop to print it
for ( a=1; a<=19; a++){
System.out.println(array[a]);
}
To use an array you have to declare it.
int array[] = new int [19];
If you want 19 numbers, then use an array with 19 elements.
Then you have to populate each number in the array. To obtain it, just use an index in your array:
array[index] = value
For example:
for ( int i=0; i<array.lenght; i++){
array[i] = xx;
}
Pay attention. The first index in your array is 0 (not 1)
Related
I am trying to print only distinct integer values once even though they are repeated multiple times in an array with the introduced order. Firstly, I need to take array size from user but I cannot determine how to initialize that variable.Can I use n -inclueded in the code- as an array size variable? When I compiled I doesn't print anything. Where are my mistakes, and how to deal with them? Any idea?
public static void uniqueNumbers(int arr[], int n)
{
for (int i=0; i<n; i++)
{
for (int j =0; j<i;j++)
{
if (arr [i]==arr[j])
break;
if (i==j)
System.out.print(arr[i] + " ");
}
}
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr [] = new int [n];
uniqueNumbers(arr,n);
}
}
You need to fill the array,that is, you need to take input for the array elements.
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr [] = new int [n];
//Add the following lines.
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
uniqueNumbers(arr,n);
}
Print the array and try your logic again.
you need to first request for the size of the array as shown below:
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter array size");
int n =scan.nextInt();
// declaring and creating array objects
int[] arr = new int[n];
// displaying default values
System.out.println("Default values of array:");
for (int i=0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
// initializing array
System.out.println("\n\n***Initializing Array***");
System.out.println("Enter "+ arr.length
+ " integer values:");
for(int i=0; i < arr.length; i++) {
// read input
arr[i] = scan.nextInt();
}
uniqueNumbers(arr, n);
}
public static void uniqueNumbers(int[] arr, int n) {
int slow = 1;
for (int fast = 1; fast < n; fast++) {
if (arr[fast] != arr[slow - 1]) {
arr[slow++] = arr[fast];
}
}
arr = Arrays.copyOf(arr, slow);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
I want to create a program that reads int values from the user until a value that is not an int is introduced. Then i want to get how many numbers are equal.
I tried this code
import java.util.Scanner;
public class Equals {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Scanner input = keyboard;
int index = 0;
int equals = 0;
while(keyboard.hasNextInt()){
keyboard.nextInt();
index++;
}
int[] equals = new int[index];
for(int i = 0 ; i < index ; i++){
int aux = input.nextInt();
values[i] = aux;
for(int b = 0 ; b < index ; b++){
if(aux == values[b]){
equals++;
}
}
}
System.out.print(equals);
}
}
This code doesnt work because the keyboard scanner only gets the number of values introduced by the user and i use that for the array size but i cant get each individual value to compare. I cant use array lists.
If you can't use array lists, what can you use? Can you use this?
int[] values = new int[0];
while(keyboard.hasNextInt()){
values = Arrays.copyOf(values, values.length + 1);
values[values.length-1] = keyboard.nextInt();
index++;
}
And if you aren't allowed to do the arrays class, you can resize the array manually like this, and use this function instead of Arrays.copyOf:
private int[] resize(int[]s, int capacity) {
int[] copy = new int[capacity];
for (int i = 0; i < s.length; i++) {
copy[i] = s[i];
s = copy;
}
return copy;
}
In the following code, I have resized an array, increased in length by 5 elements. length is displaying correctly. But when I run a loop to display the elements of the array, only initialized elements are displayed. How can I show all the elements?
package arraychallenge;
import java.util.*;
public class ArrayChallenge {
public static void main(String[] args) {
Scanner CountScanner = new Scanner(System.in);
System.out.println("How many integers you have in your list? ");
int count = CountScanner.nextInt();
System.out.println("Enter the integers now - ");
int[] MyArray = getIntegers(count);
System.out.println("Unsorted Array is present here:");
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
sortArray(MyArray);
printArray(MyArray);
resizeArray(MyArray, MyArray.length, 5);
printArray(MyArray);
}
public static int[] getIntegers(int count) {
Scanner MyScanner = new Scanner(System.in);
int[] MyArray = new int[count];
for (int i = 0; i < MyArray.length; i++) {
MyArray[i] = MyScanner.nextInt();
}
return MyArray;
}
public static void sortArray(int[] MyArray) {
int temp;
for (int i = 0; i < MyArray.length; i++) {
for (int j = i+1; j < MyArray.length; j++) {
if (MyArray[i] > MyArray[j]) {
temp = MyArray[i];
MyArray[i] = MyArray[j];
MyArray[j] = temp;
}
}
}
}
public static void printArray(int[] MyArray) {
System.out.println("Sorted Array is present here:");
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
}
public static void resizeArray(int[] MyArray, int count, int increase){
int[] tempArray = MyArray;
MyArray = new int[count+increase];
System.out.println("length of MyArray is now " + MyArray.length);
for (int i = 0; i < count; i++) {
MyArray[i] = tempArray[i];
}
}
}
In your resizeArray method, you are passing in MyArray. Then you are creating a new array of size 5, and assigning it to the MyArray variable, but this is not the same as the one you passed in.
Read this answer: https://stackoverflow.com/a/40523/3887715
My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed. – dhackner Oct 20 '10 at 16:38
In short, you call the variable MyArray in resizeArray, but it's not the same MyArray you created in main. It's a new variable inside resizeArray that happens to have the same name. So by doing MyArray = new int[count+increase];, you are not changing your original MyArray, you are changing a new one.
If you run this:
public class ArrayTest {
public static void main(String[] args) {
int[] array1 = new int[]{1,2,3,4,5};
System.out.println("Print array in main 1:");
printArray(array1);
increaseArraySize(array1, 5);
System.out.println("Print array in main 2:");
printArray(array1);
}
private static void increaseArraySize(int[] array1, int size) {
int[] tempArray = array1;
array1 = new int[tempArray.length + size];
for (int i = 0; i < tempArray.length; i++) {
array1[i] = tempArray[i];
}
System.out.println("Print array in increaseArraySize:");
printArray(array1);
}
public static void printArray(int[] MyArray) {
for (int i = 0; i < MyArray.length; i++) {
System.out.println(MyArray[i]);
}
}
}
You get:
Print array in main 1:
1
2
3
4
5
Print array in increaseArraySize:
1
2
3
4
5
0
0
0
0
0
Print array in main 2:
1
2
3
4
5
So you can see the 0s are being printed the second time the printArray method is called.
If you change the name of MyArray in resizeArray, maybe that will help you understand.
As suggested by the comments, you can have resizeArray return an array, and then assign that back to MyArray in main().
So I need to create a new array that swaps the first and last values of my existing array. Here's what I have so far:
import java.util.Scanner;
import java.util.Arrays;
public class P9_ArrayManipulate
{ public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
int total = 0;
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
System.out.println("Your reversed array is "+reverseArray(array));
System.out.println("Your swapped array is "+swapArray(array));
System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println("The program has finished calling array methods.");
}
public static int []reverseArray(int []array)
{ int[] reversed = new int[array.length];
int i;
for(i=0; i < array.length; i++)
{
reversed[i] = array[(array.length - i -1)];
}
return reversed;
}
public static int []swapArray (int []array)
{
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
public static int []evenArray(int []array)
{ for (int i = 0; i < array.length;i++){
if (array[i]%2 !=0)
{array[i] = 0;}
i++;}
return array;
}
}
Everything compiles correctly (as far as I can tell), but I'm getting a weird run time error. After seven inputs, I get this as my output:
Your reversed array is [I#b4d079
Your swapped array is [I#3644d1
Your array without even numbers is [I#3644d1
The program has finished calling array methods.
It would be much easier to just swap the first and last values of the array passed in to the swapArray() function and return that instead of creating a new array.
Something like the following will work (and it doesn't create a new variable to facilitate swapping):
public static int[] swapArray(int[] array) {
array[0] += array[array.length-1];
array[array.length-1] = array[0] - array[array.length-1];
array[0] -= array[array.length-1];
return array;
}
You have to import Arrays from java.util.Arrays
You may use the following answer to merge the arrays in swapArray() method
How can I concatenate two arrays in Java?
Try something like this:
*Edit: If its a must to create new array, just create int newarray[] = method(); instead of array[]=method();
import java.util.Scanner;
public class Array
{
public static void main (String[] args)
{ Scanner in = new Scanner(System.in);
System.out.println("Please enter seven numbers for an Array.");
int []array = new int[7];
for (int i = 0; i < 7;i++){
array[i] = in.nextInt();
}
array = reverseArray(array);
System.out.println("Your reversed array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
System.out.println();
array = swapArray(array);
System.out.println("Your swapped array is :");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]+" ");
}
// System.out.println("Your array without even numbers is "+evenArray(array));
System.out.println();
System.out.println("The program has finished calling array methods.");
}
public static int[] reverseArray(int []array)
{ int left = 0;
int right = array.length-1;
while(left<right){
int reverse = array[left];
array[left]=array[right];
array[right] = reverse;
left++;
right--;
}
return array;
}
public static int []swapArray (int []array)
{
int help = 0;
help = array[0];
array[0] = array[6];
array[6] = help;
return array;
}
}
So basically I have an Array and I want to use the same IF-statement for all values without having to copy-paste the IF-statement so many times. E.g.
if(NewArray[] < 10){
NewArray[] = NewArray + 1;
}
Is this in any way possible?
Thanks in advance.
You have to use a for loop. This code will solve your problem.
public static void main(String[] args) {
int newArray[] = new int[10];
for(int i = 0; i < newArray.length ; i ++){
newArray[i] = i;
}
/* DISPLAY YOUR ARRAY */
for(int integer : newArray){
System.out.println(integer);
}
}