Trying to get a For Loop to work - java

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

Related

How to print only distinct integer values once even though they are repeated multiple times

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]);
}
}

Storing output of a nested loop as new array - Java

I need to find the largest prime number of a given array when adding two numbers in an array,so I decided to add all possible sums first and displayed it. Now I want to take those output elements to a new array.Please help me solve this problem.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int noOfElem = scanner.nextInt();
int[] array = new int[noOfElem];
int[][] newArray = new int[5][4];
int i=0;
while(scanner.hasNextInt()){
array[i] = scanner.nextInt();
i++;
if(i == noOfElem){
break;
}
}
for (int a = 0; a < array.length; a++)
{
for (int b = a+1; b < array.length; b++) {
int m = array[a] + array[b];
newArray[a][b] =
}
}
}
}
Not quite sure what the problem is here, just do
newArray[a][b] = m;
This stores all sums of all 'a's and 'b's such that newArray[a][b] is the sum of array[a] + array[b]

Although not exceed index, I get error by the index

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++)
// ----------^

How to pass the scanner number to an ArrayList

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.

Java Sorting Array

I have this code and I do not know why the selection sort is not sorting all the way Does anyone know where to fix the program. The selection sort code I believe is right i just dont know what is wrong. The code is functioning
import java.util.Scanner;
public class selectionSort
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int temp;
int i,j,first;
System.out.println("How many numbers do you want to enter?");
int ammount = scanner.nextInt();
int[]array = new int[ammount];
for (i = 0 ; i < array.length; i++ )
{
System.out.println("Enter the numbers now.");
array[i] = scanner.nextInt();
}
System.out.println("\nThe array is:");
for(i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
for (i=array.length - 1; i>0;i--)
{
first=0;
for(j=1;j<=1;j++)
{
if(array[j]<array[first])
first = j;
}
temp = array[first];
array[first] = array[i];
array[i]=temp;
}
System.out.println("\nThe sorted array is:");
for( i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
}
}
You appear to have a typo. This line:
for(j=1;j<=1;j++)
should probably be:
for(j=1;j<=i;j++)
(The loop termination test should be j<=i, not j<=1.)

Categories

Resources