Writing a code that should read two already sorted arrays from a user of the user's defined length, then sort them into one still-sorted list. For some reason I can't get it to sort past the first three digits? It looks like it might be something really simple that I'm missing but I've been fiddling with it for a while and not finding anything. Any ideas?
Sample Run:
How long are the lists?: 3
Enter list A:
1: 1.0
2: 2.0
3: 3.0
Enter list B:
1: 2.0
2: 3.0
3: 4.0
Merged List: 1.0, 2.0, 2.0, 3.0, 3.0, 4.0
code:
import java.util.Scanner; //import scanner
public class project2 {
public static void main (String[] args){
Scanner input = new Scanner(System.in); //scanner for input
int a = 0;
System.out.println("How long are the lists? ");
System.out.print("(The lists should be the same length): ");
a = input.nextInt();
double [] lista = new double [a]; //create array
double [] listb = new double [a]; //create array
int count=1;
System.out.println("Enter numbers for list A:");
for(int j = 0; j < a ; j++){ //user input numbers loop into array "list"
System.out.print(count + ": ");
lista[j] = input.nextDouble();
count++;
}
int acount = 1;
System.out.println("Enter numbers for list B:");
for(int j = 0; j < a ; j++){ //user input numbers loop into array "list"
System.out.print(acount + ": ");
listb[j] = input.nextDouble();
acount++;
}
System.out.println(); // print the original lista inputed by user
System.out.print("Your list A: ");
for(int j=0; j<a; j++){
System.out.print(lista[j] + " ");
}
System.out.println(); // print the original listb inputed by user
System.out.print("Your list B: ");
for(int j=0; j<a; j++){
System.out.print(listb[j] + " ");
}
project2.merge(lista, listb);
System.out.println(); // print the new merged listc
System.out.print("Merged List: ");
for(int j=0; j<a; j++){
System.out.print(project2.merge(lista, listb)[j] + ", ");
}
}
public static double [] merge ( double [] list1, double [] list2){
double [] listc = new double [list1.length + list2.length]; //create array
int i = 0, j = 0, k = 0;
while (i < list1.length && j < list2.length)
{
if (list1[i] < list2[j])
{
listc[k] = list1[i];
i++;
}
else
{
listc[k] = list2[j];
j++;
}
k++;
}
while (i < list1.length)
{
listc[k] = list1[i];
i++;
k++;
}
while (j < list2.length)
{
listc[k] = list2[j];
j++;
k++;
}
return listc;
}
}
You are merging two arrays of length a, into an array of length 2 * a, but you only print out the first a numbers. Modify your for loop condition that prints out the merged array:
for(int j=0; j< 2*a; j++){
Also, every time you call merge, you merge the arrays again. Just merge it once, then refer to the array when printing the contents. This version uses the new merged array's length to stop the loop.
double[] listc = project2.merge(lista, listb);
System.out.println(); // print the new merged listc
System.out.print("Merged List: ");
for(int j=0; j < listc.length; j++){
System.out.print(merged[j] + ", ");
}
Hint: Since you are merging two sorted lists into one (output) sorted list, consider a loop that you execute for the size of the output list .. and put into the next output slot the next appropriate value from each of the two input lists.
Inside that loop, what would you want to compare to see which value you get next?
How would you handle exhausting one list before the other?
How can you generalize your program so the two input lists do not need to be the same length?
(no code for homework)
Why do you not just use the JDK-method java.util.Arrays#sort(double[]) instead of reinventing the wheel?
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 a newbie here. I wanted to print out the duplicate elements in an array.
This code will print out the duplicate elements.
Suppose I'm taking an array of size 5 with elements [1,2,5,5,5]
This code will print:
Duplicate elements: 5,5,5 //(since 5 is being repeated thrice.)
But I want the output something like this
Duplicate Elements: 5 //( instead of printing 5 thrice)
import java.util.*;
import java.util.Scanner;
public class duplicateArray{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x =sc.nextInt();
int arr[]=new int[x];
int i,count=0;
for(i=0;i<x;i++){
arr[i]=sc.nextInt();
}
System.out.print("Array: ");
for(i=0;i<x;i++){
System.out.print(arr[i]+" ");
}
System.out.println(" ");
System.out.print("Duplicate elements: ");
for(i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
System.out.print(arr[j]+" ");
}
}
}
}
}
The following code does it without creating any additional data structure. For each element, it counts the number of duplicates previously encountered and only prints the first duplicate.
If I were doing this in the real world, I would use a Set but I'm assuming you haven't learnt about them yet, so I'm only using the array that you've already created.
import java.util.Scanner;
public class DuplicateArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int x = sc.nextInt();
int[] arr = new int[x];
System.out.print("Enter " + x + " values: ");
for (int i = 0; i < x; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Array: ");
for (int i = 0; i < x; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Duplicate elements:");
for (int i = 0; i < arr.length; i++) {
int numDups = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
numDups++;
}
}
if (numDups == 1) {
System.out.print(" " + arr[i]);
}
}
System.out.println();
}
}
One solution is to create a separate List to store any duplicates found.
That, in addition to using the .contains() method of the List, you can ensure only one entry per int is made.
public static void main(String[] args) {
// Sample array of ints
int[] ints = {1, 1, 4, 5, 2, 34, 7, 5, 3};
// Create a separate List to hold duplicated values
List<Integer> duplicates = new ArrayList<>();
// Find duplicates
for (int i = 0; i < ints.length; i++) {
for (int j = 0; j < ints.length; j++) {
if (ints[i] == ints[j] && // Are the ints the same value?
i != j && // Ignore if we're looking at the same index
!duplicates.contains(ints[i])) { // Check if our List of duplicates already has this entry
duplicates.add(ints[i]); // Add to list of duplicates
}
}
}
System.out.println("Duplicates: " + duplicates);
}
Output:
Duplicates: [1, 5]
This is pretty simple however you need to sort array before. All you need to know if duplicate for an element exists or not and do the printing in the outside for loop. Rest is described in comments
Arrays.sort(arr); // Sort Array
for (int i = 0; i < arr.length; i++) {
boolean hasDuplicate = false; // Assume that arr[i] is not repeating
for (int j = i + 1; j < arr.length; j++) {
// Check if it is repeating
if (arr[i] == arr[j]) {
// If it repeats
hasDuplicate = true;
}
// Since array is sorted we know that there is no value of arr[i] after this
if (arr[i] != arr[j]) {
// Set i to the last occurrence of arr[i] value
i = j - 1;
break; // Since there no occurrence of arr[i] value there is no need to continue
}
}
// Print the element at i
if (hasDuplicate)
System.out.print(arr[i] + " ");
// In next iteration loop will start from the index next to the last occurrence of value of arr[i]
}
System.out.println("Duplicate Elements : ");
for(int i = 0; i<arr.length; i++){
boolean isDuplicate = false;
for(int k=0;k<i;k++){
if(arr[i]== arr[k]){
isDuplicate = true;
break;
}
}
if(isDuplicate){
continue;
}
int count = 0;
for(int j=0; j<arr.length; j++){
if(arr[i] == arr[j]){
count++;
}
if(count >1){
System.out.println(arr[i]);
break;
}
}
}
Without using Hashmaps, I think your best option would be to first sort the array and then count the duplicates. Since the array is now in order you can print the duplicates after each number switch!
If this is for an assignment go ahead and google bubble sort and implement it as a method.
I am trying to create a method that will accept the users input for the amount of elements they would like in an array, and the numbers to input for the array.
So far I have the main method which accepts the input from the console using the following code, after that I am not 100% sure if the method I need to create should return an int array or should just print out the results.
import java.util.Scanner;
public class Lab {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Input amount desired in Array 1");`
int a = input.nextInt();
int [] array1 = new int[a];
for (int i = 0; i < array1.length; i++) {
System.out.println("Input a number");
array1[i] = input.nextInt();}
System.out.println();}
public int swapPairs(int [] array)
Ok, so You just do this:
public void swapPairs(int [] array){
for(int i = 0; i < array.length(); i += 2){
if(i != array.length - 1)
System.out.print(array[i] + " " + array[i+1]);
}
if(array.length % 2 == 1) System.out.print(" " + array[array.length - 1]);
It really depends on what you want to achieve. If you need only to see the results the print is enough but if you return the array you can operate on the one that is changed as you wanted
What I need to do is ask the user to input values for two arrays and then output them separately and also output a merged array that is in ascending order.
For example, if the user inputs 2,5,8,0 for the first array and 6,7,0 for the second array, then the merged array should output 2,5,6,7,8.
The output for my first two arrays work perfectly but the merged array always outputs a zero. I also added a restart boolean to see if the user wants to try it again. Please help me as I am stuck.
I understand the though process but not sure how to implement this into my code. Here is my code:
//import packages
import java.util.Scanner;
import java.lang.Math;
import java.util.Arrays;
public class Main4{
public static void main(String[] args){
boolean doItAgain = true;//add boolean value to use when restarting progam
Scanner scan = new Scanner (System.in);//initialize new scanner
while(doItAgain){
//initialize variables
int first [] = new int[10000];//initialize to maximum of 10,000 integers
int second [] = new int[10000];//initialize to maximum of 10,000 integers
int input1;
int input2;
int counter1 = 0;//counter variable for first string
int counter2 = 0;//counter variable for second string
System.out.println("");
System.out.println("Welcome To my Merge Array Program 2.0!");
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit"); //asks user for first array input
//loop to go through each index
for (int a = 0; a<10000; a++)
{
input1 = scan.nextInt();//stores input as input1
first [a] = input1;
counter1++;
if (input1<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int first2 []= new int [counter1-1];
for(int b = 0; b<first2.length; b++) {
first2 [b] = first[b];
}
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit"); //asks user for second array input
for (int j = 0; j<10000; j++)
{
input2 = scan.nextInt();//stores input as input2
second [j] = input2;
counter2++;
if (input2<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int second2 []= new int [counter2-1];
for(int c = 0; c<second2.length; c++) {
second2 [c] = second[c];
}
System.out.println("First Array:");//output first array values in the order of their input
for (int p=0; p<first2.length; p++) {
System.out.print(first2[p] + " ");
}
System.out.println("\nSecond Array:");//output second array values in the order of their input
for (int p2=0; p2<second2.length;p2++) {
System.out.print(second2[p2] + " ");
}
boolean valid = true;
for (int e = 0; e<first2.length-1; e++) {
if(first2[e]>first2[e+1]) {
valid = false;
}
}
for (int e2 = 0; e2<second2.length-1;e2++) {
if(second2[e2]>second2[e2+1]) {
valid = false;
}
}
int[] array = new int[first2.length + second2.length];
//fill array 3 with arrays 1 & 2
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length; l++){
array[first2.length + l] = second2[l];
}
//sort array 3
for (int i = 0; i<first2.length + 1; i++){
for (int j = i+1; j<first2.length + 1; j++){
if(array[i] > array[j]){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
}
//Asks user if they want to restart program. Used boolean value to initialize doItAgain variable
System.out.println("");
System.out.println("");
System.out.println("Thanks for using this program! Do you want to do it again? (Y or N)");
if(scan.next().toLowerCase().equals("y")){
doItAgain = true;
break;
}
else{
doItAgain = false;
System.out.println("If you change your mind and want to run it again, type runMain.");//output closing statement if user says N to restart
break;
}
}
}
}
You are not merging your arrays. Your 1st array is, for instance [1 2] and your second array is, for instance [3 4]. Your final array is going to be initialized with size 4 (first2.length + second2.length), but all it's elements will be zero.
In this line here, I suggest you use arraycopy() to fill your final array:
int[] array = new int[first2.length + second2.length];
System.arraycopy(first2, 0, array, 0, first2.length);
System.arraycopy(second2, 0, array, first2.length, second2.length);
This will copy the first2 array to the starting position of your final array and then copy your second2 array to the position of your final array where first2 ended. You will end up with [1 2 3 4] and can then sort the elements (though in this case, they're already sorted.
For more information on arraycopy() consult this page here:
https://www.tutorialspoint.com/java/lang/system_arraycopy.htm
EDIT: BTW, you have an error right here, which is what is preventing you from printing the full sorted array:
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
} //right here, you need to close this curly bracket
EDIT2: Since you can't use arraycopy(), you can use for loops to fill in the final array:
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length;l++){
array[first2.length + l] = second2[l];
}
The problem:
a program that updates a list of students’ grades after the end of drop period. The program should reads from the user number of students who dropped and their indexes, and then the program should copies the remaining student’s grades to new array. In addition, the program should display both the original and the updated list. [Hint: the new array must have suitable length equivalents to number of remaining students]
my code:
public class Q5{
static Scanner scan = new Scanner (System.in);
public static void main (String args[]){
double [] list={1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
System.out.println("enter number of students who dropped:");
int num=scan.nextInt();
double [] list2 = new double [num];
System.out.println("Enter index Of the student who dropped ");
for (int j=1 ; j<=num ; j++)
{
System.out.println("student" + j + ":");
int index=scan.nextInt();
list[index]=0;
}
int j=0;
for(int i=0; i<list.length ; i++)
if (list[i]!=0)
{
list2[j]=list[i];
j++;
}
System.out.print("The original list : " );
for(int i=0; i<list.length ; i++)
System.out.print(list[i] + " " );
System.out.print("remaining students " );
for(int i=0; i<list2.length ; i++)
System.out.print(list2[i] + " " );
}
}
what is the problem ? it is not working !!!
in Line 16 it says :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q5.main(Q5.java:23)
how I can correct this
That's because of the size of your list2.
You shouldn't set its size to num, but rather to the size of the original list. Because the list2 is going to contain just as many elements as the original list. You need the num only to fetch that many inputs from the user and assign those indexes with the value 0.
double[] list2 = new double[list.length]; // This should be the size of your list2
If you don't need to keep the original size, then you need to subtract the num from the original size, as suggested by #Joetjah.
double[] list2 = new double[list.length - num]; // This should be the size of your list2
Pseudo-code:
You start of with 10 students. Say you want to drop 2 students. That means you set the list2 size to 2.
Next thing you do, is trying to add all the students (10) from list to list2. But, list2 is too small for this. Thus you get your Exception.
What you want, is this:
double [] list2 = new double [list.length - num];
Guess that problem with predefined array 'list'.
Step 1: Created the list with one of the initializing ways. Here the size is fixed.
Step 2: Took input from user : lets assume it is 11.
list doesn't need to contain the size given as input.
You initialize list2 with wrong size.
You get from the user number of dropped students and then try to put in list2 all the remaining students.
double [] list2 = new double [list.length - num];
Your code will fail if the value entered by user is out of bounds for the array :
int index=scan.nextInt();
list[index]=0; // This may fail. Value entered by the user may exceed the array length
Its working fine
import java.util.Scanner;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[num - 1]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < num; i++) {
if (list[i] != 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}
output is
enter number of students who dropped:
2
Enter index Of the student who dropped
student0:
1
student1:
2
The original list : 1.0 0.0 0.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 remaining students 1.0
This will remove the exception you got. From next time you don't use static values.
Edit:
It is not a good practice to assign values to any variable by yourself. As the array is having size of 10. If user enters more than 10 students dropped then it will cause a problem.
import java.util.*;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[list.length-num]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < list.length; i++) {
System.err.println(""+list[i]);
if (list[i] > 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}