My question is
( - Write the following method that merges two sorted lists
into a new sorted list. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list. - )
When I run this code, Eclipse give error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at single_dimension_all_arrays.Merge_two_sorted_lists.getNumber(Merge_two_sorted_lists.java:60)
at single_dimension_all_arrays.Merge_two_sorted_lists.main(Merge_two_sorted_lists.java:77)
I can't understand why give the error. I can't exceed index.
private static void sort(int [] list3)
{
int temp=0;
for (int i = 0; i < list3.length; i++)
{
for (int j = 0; j < list3.length; j++)
{
if(list3[i]<list3[j])
{
temp=list3[i];
list3[i]=list3[j];
list3[j]=temp;
}
}
}
for (int i = 0; i < list3.length; i++)
{
System.out.println(list3[i]);
}
}
private static void getNumber(int [] list1,int [] list2)
{
Scanner scan = new Scanner(System.in);
int [] list3 = new int[list1.length+list2.length];
for (int i = 1; i < list1.length; i++)
{
System.out.println("Please, enter the number");
list1[i] = scan.nextInt();
}
for (int i = 1; i < list2.length; i++)
{
System.out.println("Please,enter the number");
list2[i]= scan.nextInt();
}
for (int i = 0; i <= list3.length; i++)
{
if(i<list1.length)
{
list3[i]=list1[i];
}
else if(i>list1.length)
{
list3[i] = list2[i];
}
}
sort(list3);
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please,enter the length of list1");
int l1 = scan.nextInt();
System.out.println("Please, enter the length of list2");
int l2 = scan.nextInt();
int [] list1 = new int[l1];
int [] list2 = new int[l2];
list1[0]=l1;
list2[0]=l2;
getNumber(list1,list2);
}
}
Thanks..:)
Although not exceed index...
Yes you do:
for (int i = 0; i <= list3.length; i++)
// ----------------^
The valid range of indexes is 0 to length - 1, so that should be < as it is in several other parts of your code.
Side note: You're also skipping the first element in arrays in a few places:
for (int i = 1; i < list1.length; i++)
// ----------^
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 have a question about stop array input limit then the result to show the output.
Below is my coding have already set new float[3][3]:
import java.util.Scanner;
public class Clone2Darray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The limit output is show me like below:
run:
Type float numbers in the two-dimensional array of similar type and size
with line breaks, end by -1:
5.33
9.33
63.33
6.36
3.55
7.25
2.33
3.66
The result is:
6.33 5.33 9.33
63.33 6.36 3.55
7.25 2.33 3.66
BUILD SUCCESSFUL (total time: 31 seconds)
My problem is want to stop limit float[3][3] and can unlimited key in the input until type -1 to stop the input. May I know how to remove the limit float[3][3] in the array? Hope anyone can guide me to solve my problem. Thanks.
At the point when you allocate memory for the two-dimensional array you have to tell the sizes of its elements, because memory will be allocated for that array and the amount of memory to be allocated must be known.
You can bypass this, by using some more dynamic types, like List and its popuplar implementation, ArrayList, even in a nested form. That's a nice thing to do, but then you will not have a "real" array.
The below code allows you to create the dynamic arrays.
import java.util.Scanner;
public class Clone2DArray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt( sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line breaks:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
I am trying to display the occurrence of how many times an integer occurs in an array but I get an infinite loop/logic error. For instance, if the user enters: 2, 5, 6, 5, 4, 3, 23, 43, 2, 0 then it should display:
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
Any help would really be appreciated. Note: This is not an assignment or homework, It is a exercise question from intro to Java book by Y.D. Lang
import java.util.*;
public class CountNumbers {
public static void main(String[] args) {
System.out.println("Enter the integers between 1 and 100: ");
int[] arrayRefVar = createList();
int[] countNum = countNumbers(arrayRefVar);
displayCount(countNum, arrayRefVar);
}
public static int[] createList() {
Scanner Input = new Scanner(System.in);
int[] List = new int[100];
int i = 0;
while (List[i] != 0) {
List[i] = Input.nextInt();
i++;
}
return List;
}
public static int[] countNumbers(int[] List) {
int[] count = new int[100];
for (int i = 0; i < count.length; i++) {
count[i] = i;
}
int[] countNum = new int[List.length];
for (int i = 0; i < countNum.length; i++) {
countNum[i] = 0;
}
for (int i = 0; i < List.length; i++) {
for (int j = 0; j < count.length; j++) {
if (List[i] == count[j]) {
countNum[i]++;
}
}
}
return countNum;
}
public static void displayCount(int[] countList, int[] arrayRefVar) {
for (int i = 0; i < arrayRefVar.length; i++) {
System.out.println(arrayRefVar[i] + " occurs " + countList[i] + " " + checkPlural(arrayRefVar[i]));
}
}
public static String checkPlural(int n) {
if (n > 1) {
return "times";
} else {
return "time";
}
}
}
If your input should end in 0, then you should check whether the currently read int is zero or not.
while(i < List.length) {
List[i] = Input.nextInt();
if(List[i] == 0)
break ;
++i;
}
Since you are checking for the condition after incrementing i, you are not checking the current value.
Note : nextInt() method from the Scanner class can throw exceptions namely : InputMismatchException, NoSuchElementException and IllegalStateException. So either handle it in a try catch block or make the caller handle it by throwing the exception.
So I finally got it after countless tries, if anybody has any suggestions to make the code more efficient the input would be greatly appreciated. Here it is:
import java.util.Random;
public class CountSingleDigits {
public static void main (String[] args) {
int[] arrayRefVar = createList();
int[] counts = new int[10];
for (int i = 0; i < 10; i++) {
counts[i] = i;
}
int[] tempCounts = new int[10];
for (int i = 0; i < arrayRefVar.length; i++) {
for (int j = 0; j < 10; j++) {
if (arrayRefVar[i] == counts[j]) {
tempCounts[j]++;
}
}
}
for (int i = 0; i < 10; i++) {
System.out.println(counts[i] + " appears " + tempCounts[i] + " times ");
}
for (int i = 0; i < arrayRefVar.length; i++) {
if (i % 10 == 0) {
System.out.println();
}
System.out.print(arrayRefVar[i] + " ");
}
}
public static int[] createList() {
Random f = new Random();
int[] List = new int[100];
for (int i = 0; i < List.length; i++) {
List[i] = f.nextInt(9);
}
return List;
}
}
One issue is that your while loop for user input is never entered. You use 0 as the sentinel value to exit user input, however, when you initialize an array of integers, they are all 0 by default.
int[] List = new int[100];
int i = 0;
//problem: while loop never entered
while (List[i] != 0) {
I'm trying to write a program where on the first line, you enter the number of times you want a for loop to iterate, on the second line, you enter the value of the array, and on the third line, you enter the numbers that you want in the array. My program either does not do what I want it to do, or it crashes on me. This is the code that I have for the program so far:
import java.util.*;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int n = input.nextInt();
for (int i=0; i<n; i++)
{
int value = input.nextInt();
int[] arr = new int[value];
arr[i] = input.nextInt();
}
}
What can I do? Please help. I've tried everything! Also, it would help if someone could help me with sorting the numbers in ascending order, followed by displaying the middle number in each line, but first thing's first. Thank you.
I believe this is more of what you are after. I output the entries individually but you could combine that easily enough.
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
try
{
System.out.println("Number of times to loop:");
int numEntries = input.nextInt();
int[][] valueArrays = new int[numEntries][];
for (int i=0; i<numEntries; i++)
{
System.out.println("Size of array #"+i+": ");
int arrayLen = input.nextInt();
int[] inputArray = new int[arrayLen];
for (int j = 0; j < arrayLen; j++)
{
System.out.println("Enter value at index "+j+": ");
inputArray[j] = input.nextInt();
}
Arrays.sort(inputArray);
valueArrays[i] = inputArray;
}
for (int l=0; l < valueArrays.length; l++)
{
int[] values = valueArrays[l];
for (int m=0; m < values.length; m++)
{
System.out.println("Value of array #"+l+" saved at index "+m +": " + values[m]);
}
if ((values.length % 2) == 0)
{
int start = values.length/2;
int end = start + 1;
System.out.println("Middle values in array #"+l+" saved at indices " + start + " and " + end);
}
else
{
int start = values.length/2;
System.out.println("Middle value in array #"+l+" saved at index " + start);
}
}
}
finally
{
input.close();
}
}
You're creating a new array on each iteration inside the loop.
You should get int[] arr = new int[value]; out of the loop:
int arraySize = input.nextInt();
int[] arr = new int[arraySize];
for (int i=0; i<arraySize; i++)
{
int value = input.nextInt();
arr[i] = value;
}
If you don't want to limit the user for a size, use an ArrayList instead.
Problem 1:My program either does not do what I want it to do.
Dont initialize array inside for loop as loop wiil create a new array every time you iterate it.
Scanner input = new Scanner (System.in);
System.out.println("Enter no. of elements in array");
int n = input.nextInt();
int[] arr = new int[n];
System.out.println("Array length set to "+n);
for (int i=0; i<n; i++)
{
System.out.println("Enter value for index "+i);
arr[i] = input.nextInt();
System.out.println(arr[i]+" Value saved at index "+i);
}
DEMO1
Problem 2(described in comments below):Sorting arrays and displaying the middle number
class Ideone
{
static int[] countingSort(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max)
max = numbers[i];
}
int[] sortedNumbers = new int[max+1];
for (int i = 0; i < numbers.length; i++) {
sortedNumbers[numbers[i]]++;
}
int insertPosition = 0;
for (int i = 0; i <= max; i++) {
for (int j = 0; j < sortedNumbers[i]; j++) {
numbers[insertPosition] = i;
insertPosition++;
}
}
return numbers;
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner (System.in);
System.out.println("Number of times to loop:");
int n = input.nextInt();
// int[] arr = new int[n];
// System.out.println("Array length set to "+n);
for (int i=1; i<=3; i++)
{
System.out.println("Size of array #"+i+": ");
int alen = input.nextInt();
int[] arr = new int[alen];
System.out.println("Value in array #"+i+": ");
for (int j=0; j<alen; j++){
System.out.println("Enter value at index "+j+": ");
arr[j] = input.nextInt();
}
arr=Ideone.countingSort(arr);
for (int l=0; l<alen; l++)
System.out.println(arr[l]+" Value of array #"+i+" saved at index "+l);
System.out.println("Middle value in array #"+i+" saved at index "+arr[alen/2]);
}
}
}
DEMO2
My method is working fine !! I am trying to get the information from the user instead of putting the numbers myself as i did in my code.. is there a way that i can get pass the numbers without storing them in different variables! thanks.
import java.util.*;
public class Interleave {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Welcome to Interleave program! ");
System.out.println();
System.out.print("how many number for array 1:= ");
int array1 = console.nextInt();
for (int i = 0; i < array1; i++) {
System.out.print("please enter nubmers := ");
int num = console.nextInt();
}
ArrayList<Integer> a1 = new ArrayList<Integer>();
a1.add(10);
a1.add(20);
a1.add(30);
System.out.println();
System.out.print("how many number for array 2:= ");
int array2 = console.nextInt();
for (int i = 0; i < array2; i++) {
System.out.print("please enter nubmers := ");
int num2 = console.nextInt();
}
ArrayList<Integer> a2 = new ArrayList<Integer>();
a2.add(4);
a2.add(5);
a2.add(6);
a2.add(7);
a2.add(8);
System.out.println();
System.out.println(a1);
System.out.println(a2);
interleave(a1, a2); //parameters
System.out.println(a1);
}//end of main
public static void interleave(ArrayList<Integer> list1, ArrayList<Integer> list2) {
int sizeList1 = list1.size();//size of array
int sizeList2 = list2.size();//size of array
ArrayList<Integer> temp = new ArrayList<Integer>(); //
for (int index = 0; index < list1.size(); index++)// copy elements ferom list 1
temp.add(index, list1.get(index));
for (int index = 0; index < list2.size(); index++)// copy elements ferom list 2
temp.add(index, list2.get(index));
int tempSize = temp.size(); //get temporary array size
temp.clear(); //clear tepm array
if (list1.size() > list2.size()) {
for (int index = 0, list1Index = 0, list2Index = 0;
index < sizeList1;
index = index + 2, list1Index++, list2Index++ )
{
temp.add(index, list1.get(list1Index));
temp.add(index + 1, list2.get(list2Index));
}
for (int index = 2 * list2.size(),
list2Count = list2.size();
index < tempSize; list2Count++, index++ )
temp.add(index, list1.get(list2Count));
list1.clear(); // clear list 1
for (int index = 0; index < temp.size(); index++)
list1.add(index, temp.get(index));
} else {
for (int index = 0, list1Index = 0, list2Index = 0;
index < sizeList2;
index = index + 2, list1Index++, list2Index++ )
{
temp.add(index, list1.get(list1Index));
temp.add(index + 1, list2.get(list2Index));
}
for (int index = 2 * list1.size(),
list1Count = list1.size(); index < tempSize;
list1Count++, index++ )
temp.add(index, list2.get(list1Count));
list1.clear();
for (int index = 0; index < temp.size(); index++)
list1.add(index, temp.get(index));
}
}//end of interleave
}//end of class
Create an ArrayList of integers
every time you need to add a number, call mylist.add(console.nextInt())
Call mylist.clear() when you're done, or set it to a new ArrayList.
Just be careful of the various exceptions that may be thrown and try catching them so that the user has to retype the number until it is valid.