How to pass the scanner number to an ArrayList - java

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.

Related

Array not copying another array

I am trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do “myArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.

How to use an IF statement with arraylist object and calling the size() method on it. In Java

I want to solve the code query:
Create a program that uses a multidimensional array to store student grades. The first dimension should be a number for each student, and the second dimension should be for each student’s grades. Display the average of all the grades earned by each student and an overall average for every student.
Below is my code:
I created 3 grades for 2 students.
int [] [] students_grades = new int[2][3];
students_grades[0][0] = 13;
students_grades[0][1] = 23;
students_grades[0][2] = 34;
students_grades[1][0] = 31;
students_grades[1][1] = 32;
students_grades[1][2] = 43;
int rows = 2;
int columns = 3;
int i, j;
for (i = 0; i < columns; i++) {
for ( j = 0; j < rows; j++) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(students_grades[j][i]);
if (myList.size()==3) {
System.out.println("************************************************");
System.out.println("This is the grades for Students 1: "); System.out.println("-------------------------------------------------");
for (int element : myList) {
System.out.println(element);
}
}
}
System.out.println(" ");
}
But I am not getting an output from the for loop statement in the if brackets.
If you want to print only the grades of first student,try this:
int [] [] students_grades = new int[2][3];
students_grades[0][0] = 13;
students_grades[0][1] = 23;
students_grades[0][2] = 34;
students_grades[1][0] = 31;
students_grades[1][1] = 32;
students_grades[1][2] = 43;
int rows = 2;
int columns = 3;
int i, j;
List<Integer> myList = new ArrayList<Integer>();
for (i = 0; i < rows; i++) {
for ( j = 0; j < columns; j++) {
myList.add(students_grades[i][j]);
if (myList.size() == 3) {
System.out.println("************************************************");
System.out.println("This is the grades for Students 1: "); System.out.println("-------------------------------------------------");
for (int element : myList) {
System.out.println(element);
}
}
}
System.out.println(" ");
}
}
myList is being defined within the inner loop, this means every iteration in the loop is creating a new list, so the list length will never be 3.
To fix this, you need to assign a new ArrayList to myList within the outer loop, like so:
for (j = 0; j < rows; j++) {
List<Integer> myList = new ArrayList<Integer>();
for ( i = 0; i < columns; i++) {
myList.add(students_grades[j][i]);
if (myList.size()==3) {
System.out.println("************************************************");
System.out.println("This is the grades for Students 1: "); System.out.println("-------------------------------------------------");
for (int element : myList) {
System.out.println(element);
}
}
}
EDIT:
Since rows is set to 2, the if condition would never be satisfied. Swapping the for statements would satisfy the if condition.

How to Create Method for Finding Largest Element in Array

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numberOfRows, numberOfColumns;
double arrayElements[][] = null;
int index[] = null;
System.out.print("Enter number of rows in array: ");
numberOfRows = keyboard.nextInt();
System.out.print("Enter number of columns in array: ");
numberOfColumns = keyboard.nextInt();
arrayElements = new double[numberOfRows][numberOfColumns]; //this command allocates memory for the array arrayElements
for (int row = 0; row < numberOfRows; row++)
{
for (int column = 0; column < numberOfColumns; column++)
{
System.out.print("Enter the Value for Row [" + row + "], Column " + "[" + column + "]: ");
arrayElements[row][column] = keyboard.nextDouble();
}
}
System.out.printf("\n Two-Dimensional Array: %d rows x %d columns\n", numberOfRows, numberOfColumns);
for (int row = 0; row < numberOfRows; row++)
{
System.out.printf("Row %3d:", row);
for (int column = 0; column < numberOfColumns; column++)
{
System.out.printf("%7.1f", arrayElements[row][column] );
}
System.out.println();
index = locateLargest( arrayElements );
}
}
public static int[] locateLargest( double[][] arrayx2 ){
}
Hello all,
I am trying to write a method for finding the largest element in a two-dimensional array, and return the index of the element with the highest value to the single-dimensional array 'index'. I have the signature written, but can anyone please help me figure out how to actually write the method that will search each element of the two-dimensional array and find the index location of the largest number?
Thank you so much!
/*Finds max value in an Array*/
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
For 2 dimensional array use that:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Reference: https://stackoverflow.com/a/5877271/1848929
Firstly, if you want the returned array of your method to contain the largest element as well as the index, the return type should be double[] and not int[] since the type of the elements of the matrix is double. The method bellow will return an array containing three elements. the first element is the row index, the second is the column index, and the third is the element value. if you are going to use the code bellow, make sure to change the return type and also the type of index in your code to double[]. I hope this is helpful.
// first we assume the largest element is the one located at row 0, and
//column 0, then we compare it with the other elements in the matrix
public static double[] locateLargest( double[][] arrayx2 ){
double max = arrayx2[0][0];
int row = 0, col = 0;
double[] indexAndMaxVal = new double[3];
for (int i = 0; i < arrayx2.length; i++) {
for (int j = 0; j < arrayx2[i].length; j++) {
if (arraux2[i][j] > max) {
maxValue = arrayx2[i][j];
row = i;
col = j
}
}
}
indexAndMaxVal[0] = row;
indexAndMaxVal[1] = col;
indexAndMaxVal[2] = max;
return indexAndMaxVal;
}

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

Trying to get a For Loop to work

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

Categories

Resources