I've tried couple of things to make this code work, but it didn't.
my goal is to instantiate nums[] with numbers {0, 1, 2, .... n-1}. nums has no size, so I used list that instantiate nums with zeros. Keep in mind that the result must be an array (nums).
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
//nums = listNum.toArray(nums);
for (int i =0; i < n; i++){
nums[i] = i;
}
When you're writing this :
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
listnum has a size of 0, so nums won't be initialized as you want.
Why not just do :
nums = new int[n];
?
Array's are fixed in size.
nums = new int[listNum.size()];
That never works. You are initializing your array with zero elements. Once you declare the array size, you can't change that back.
What you are looking for is
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
nums = new int[n];//instantiate nums with entered size
for (int i =0; i < n; i++){
nums[i] = i;
}
Just get rid of that ArrayList since you are know the size n
You don't need an ArrayList - if you take the input of n from the command line, you could just use it to initialize the array:
nums = new int[n];
for (int i =0; i < n; i++){
nums[i] = i;
}
Related
I'm still new to java and been trying to write code that takes two different arrays of common values and outputs the common values of both arrays but I keep getting the following error message:
Exception in thread "main" Your common values are: 0 Your common
values are: 0 Your common values are: 0 Your common values are: 0
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for
length 5 at HomworkTestingQ.main(HomworkTestingQ.java:18)
Scanner sc = new Scanner(System.in);{
int n = 5;
int m = 5;
int[] array1 = new int[m];
int[] array2 = new int[n];
System.out.println("Enter the first array: ");
n=sc.nextInt();
System.out.println("Enter the second array");
m=sc.nextInt();
for(int i = 0; i < array1.length; i++) {
for(int j = 0; i < array2.length; j++) {
if(array1[i] == array2[j]) {
System.out.println("Your common values are: " + array1[i+j] );
}
}
}
}
}
}
I fix your codes:
Scanner sc = new Scanner(System.in);
int n = 5;
int m = 5;
int[] array1 = new int[m];
int[] array2 = new int[n];
System.out.println("Enter the first array: ");
for (int i = 0; i < n; i++) {
array1[i] = sc.nextInt();
}
System.out.println("Enter the second array");
for (int i = 0; i < n; i++) {
array2[i] = sc.nextInt();
}
for (int item : array1) {
for (int value : array2) {
if (item == value) {
System.out.println("Your common values are: " + item);
}
}
}
I believe the issue is that you're adding the array iterators here:
array1[i+j]
The i+j is adding to be more than the length of array1.
An aside, your arrays aren't being populated as I think you expect based on:
System.out.println("Enter the first array: ");
n=sc.nextInt();
System.out.println("Enter the second array");
m=sc.nextInt();
I'm just speculating there perhaps you have more to do there down the line.
You don't need to add up the indices..
Since array1[i] is equal to array2[j], print any one of them:
for(int i=0;i<array1.length;i++){
for(int j=i+1;j<array2.length;j++){
if(array1[i]==array2[j]) int commonValue = array1[i];
return commonValue; // or print it
}
}
FIRST PROBLEM
The size of the array won't change when you scan the value of m and n because java is pass by value and the size of the array is the value, not the variable.
So you should do something like-
int m = scanner.nextInt();
int[] arr = new int[m];
SECOND PROBLEM
System.out.println("Your common values are: " + array1[i+j] );
This will go out of bounds, perhaps you should do-
System.out.println("Your common values are: " + array1[i] );
I am trying to read an input like this:
5 3 3
1 2 3 4 5
5 4 3 2 1
When I use the scanner and try something like this:
Scanner sc = new Scanner(System.in);
int n, x, y;
String[] temp = sc.nextLine().split(" ");
n = Integer.parseInt(temp[0]);
x = Integer.parseInt(temp[1]);
y = Integer.parseInt(temp[2]);
int[] a, b;
a = b = new int[n];
String[] t = sc.nextLine().split(" ");
for(int i = 0; i < n; i++){
a[i] = Integer.parseInt(t[i]);
}
String[] f = sc.nextLine().split(" ");
for(int i = 0; i < n; i++){
b[i] = Integer.parseInt(f[i]);
}
This just prints that the arrays 'a' and 'b' are same;
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
12
How can I read this input?
The problem with your code is not how you read the input, but this line here:
a = b = new int[n];
In this line, you set a and b to the same new int array. You did create a new array here, but you only created one. Both a and b refer to that same one. So when you are doing b[i] = ..., you are in fact overwriting the values you've just written to it in the first loop.
You should create two arrays:
a = new int[n];
b = new int[n];
Note that another way to read the input is to use nextInt, but your way is okay too.
Scanner sc = new Scanner(System.in);
int n, x, y;
n = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
int[] a, b;
a = new int[n];
b = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
}
for(int i = 0; i < n; i++){
b[i] = sc.nextInt();
}
This is causing the problem.
a = b = new int[n];
Both a, b are referencing the same array object. Hence, the later input is overriding the previous input. Change this to:
a = new int[n];
b = new int[n];
I'm very new to java and have been playing around with sorting algorithms. I have the following code working for a set array. I was just wondering what I'd need to change to get it to sort arrays of randoms lengths and integers. I guess the answer is pretty obvious any help is appreciated!
public static void main(String[] args) {
int number[]={8,5,3,2,9};
int temp;
boolean fixed=false;
while(fixed==false){
fixed=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;
fixed=false;
}
}
}
for(int i=0; i<number.length; i++)
System.out.println(number[i]);
}
}
I mean, your algorithm would work regardless of the array's length. About how to generate such arrays, you could do this:
int n = Math.random()*10000 + 1; //so its never 0.
int number[] = new int[n];
for(int i=0;i<n;i++) number[i]=Math.random()*10000;
Everything else stays the same :).
EDIT: You commented on the question that you'd rather generate the array by taking an input from the keyboard. You can do that by using a scanner.
Scanner scanIn = new Scanner(System.in);
do{
int n = scanIn.nextInt();
} while (n<1);
int number[] = new int[n];
for(int i=0;i<n;i++) number[i] = scanIn.nextInt();
scanIn.close();
What you are looking for is probably a method to extract your bubblesort to. Please note that this method changes the input array and does not return a new array.
private static void bubblesort(int[] array) {
int temp;
boolean fixed = false;
while (!fixed) {
fixed = true;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
fixed = false;
}
}
}
}
You can then call it using different approaches.
Fixed size array:
// fixed size array
int number[] = {8, 5, 3, 2, 9};
bubblesort(number);
System.out.println(Arrays.toString(number));
Read numbers from System.in.
// read from sys.in like "2 6 4"
Scanner s = new Scanner(System.in);
String line = s.nextLine();
int[] parsedInts = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
bubblesort(parsedInts);
System.out.println(Arrays.toString(parsedInts));
You can the use Scanner Class in java and need to import java.util.Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array length :");
int n = sc.nextInt();
int number[] = new int[n];
System.out.println("Enter the numbers :");
for(int i = 0; i < number.length; i++) {
number[i] = sc.nextInt();
}
I would like to fill an array using consecutive integers. I have created an array that contains as much indexes as the user enters:
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int [] array = new int[numOfValues];
How do i fill this array with consecutive numbers starting from 1?
All help is appreciated!!!
Since Java 8
// v end, exclusive
int[] array = IntStream.range(1, numOfValues + 1).toArray();
// ^ start, inclusive
The range is in increments of 1. The javadoc is here.
Or use rangeClosed
// v end, inclusive
int[] array = IntStream.rangeClosed(1, numOfValues).toArray();
// ^ start, inclusive
The simple way is:
int[] array = new int[NumOfValues];
for(int k = 0; k < array.length; k++)
array[k] = k + 1;
for(int i=0; i<array.length; i++)
{
array[i] = i+1;
}
You now have an empty array
So you need to iterate over each position (0 to size-1) placing the next number into the array.
for(int x=0; x<NumOfValues; x++){ // this will iterate over each position
array[x] = x+1; // this will put each integer value into the array starting with 1
}
One more thing. If I want to do the same with reverse:
int[] array = new int[5];
for(int i = 5; i>0;i--) {
array[i-1]= i;
}
System.out.println(Arrays.toString(array));
}
I got the normal order again..
Scanner in = new Scanner(System.in);
int numOfValues = in.nextInt();
int[] array = new int[numOfValues];
int add = 0;
for (int i = 0; i < array.length; i++) {
array[i] = 1 + add;
add++;
System.out.println(array[i]);
}
As far as my knowledge goes, this program is done correctly. However, given the exception it appears not. I am to make 2 arrays of length x (user inputted) and the user is to input the elements. Done. Next multiply each element by its corresponding element in the other array and add the sum total.
Ex, array1[0]*array2[0] + array1[1]*array2[1]...
Precise error is : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
I have done many different loops, the last loop below that I have spaced extra to identify is what I think is closest to correct but not. I would much appreciate some advice, thank you in advance.
System.out.println("This program will multiply 2 one dimension arrays of any length. \n The length and contents of the array is entered from the keyboard.");
System.out.println("Enther the data for the first array. ");
System.out.println("Enther the length of the array (remember arrays being counting at 0, not 1:");
int a = 0;
Scanner keyboard = new Scanner(System.in);
a = keyboard.nextInt();
int[] firstArrayLength = new int[a];
System.out.println("Enter the elements of the first array(remember arrays begin counting at 0, not 1");
double arrayElements = 0;
for (int elements = 0; elements <= firstArrayLength.length; elements++) {
arrayElements = keyboard.nextInt();
}
System.out.println("Enter the data for the second array. ");
System.out.println("Enter the elements of the second array(remember arrays begin counting at 0, not 1");
int[] secondArrayLength = new int[a];
double secondArrayElements = 0;
for (int elements = 0; elements <= secondArrayLength.length; elements++) {
secondArrayElements = keyboard.nextInt();
}
double [] thirdArray = new double [a];
for (int i =0; i <=firstArrayLength.length; i++)
{
thirdArray[a] = firstArrayLength[i]*secondArrayLength[i];
}
System.out.println(thirdArray);
}
Change your <= symbols to < when you are accessing de array. For instance:
for (int elements = 0; elements < firstArrayLength.length; elements++)
...
Remember if the length is 4, you can access elements as:
array[0], array[1], array[2], array[3] // 4 elements
array[4] doesn't exist, that cause the IndexOutOfBounds exception.
Edit
The strange output [I#756a7c99 (for instance) is because you are printing an array as:
int a[] = new int[4];
System.out.println(a);
Instead, you may want to print elements of that array:
int a[] = new int[4];
for (int i = 0; i < 4; i++) {
System.out.println(a[i]);
}
Edit 2
public static void main(String[] args) {
System.out
.println("This program will multiply 2 one dimension arrays of any length. \n The length and contents of the array is entered from the keyboard.");
System.out.println("Enther the data for the first array. ");
System.out
.println("Enther the length of the array (remember arrays being counting at 0, not 1:");
int a = 0;
Scanner keyboard = new Scanner(System.in);
a = keyboard.nextInt();
int[] firstArray = new int[a];
System.out
.println("Enter the elements of the first array(remember arrays begin counting at 0, not 1");
for (int elements = 0; elements < firstArray.length; elements++) {
firstArray[elements] = keyboard.nextInt();
}
System.out.println("Enter the data for the second array. ");
System.out
.println("Enter the elements of the second array(remember arrays begin counting at 0, not 1");
int[] secondArray = new int[a];
for (int elements = 0; elements < secondArray.length; elements++) {
secondArray[elements] = keyboard.nextInt();
}
double[] thirdArray = new double[a];
for (int i = 0; i < firstArray.length; i++) {
thirdArray[i] = firstArray[i]*secondArray[i];
}
for (int i = 0; i < thirdArray.length; i++)
System.out.println(thirdArray[i]);
}
elements <= firstArrayLength.length ==> elements < firstArrayLength.length
arrayElements = keyboard.nextInt(); ==>> firstArrayLength[elements] = keyboard.nextInt();
secondArrayElements = keyboard.nextInt(); ==>> secondArrayLength[elements] = keyboard.nextInt();