Passing an array to another method and copying it - java

I am trying to pass an array from one method to another method and then copy the contents of that array into a new array. I am having trouble with the syntax to accomplish that task.
Does anyone have some reference material that I could read about this topic or maybe a helpful tip that I could apply?
I apologize if this is a noob question, but I have only been messing with Java for 3-4 weeks part time.
I know that Java uses pass by value, but what where I'm getting lost is...should I invoke the sourceArray before copying it to the targetArray?
My goal here is not to be just handed an answer, I need to understand WHY.
Thanks...in advance.
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the total number of dealers: ");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.printf("%nPlease enter the required data for each of your dealers:");
dataCalculation(numDealers);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: ");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
int[] dealerSales = new int[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
int sales = input.nextInt();
dealerSales[i] = sales;
}
for(int i = 0; i < data; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
}
//gather the required input data.
//Perform the appropriate data validation here.
}//data calculations
//METHOD 3
public static int commission(int data)
{
//Create array
int[] commissionRate = new int[dealerSales];
//Copy dealerSales array into commissionRate
System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);
//calculate the commission array.
//$1 - $5,000...8%
//$5,001 to $15,000...15%
//$15,001...20%
//
}//commission method
}//class

If you want to copy an array, you can use the Arrays.copyOf(origin, length) method. It takes 2 arguments, first one is the array from which the data is supposed to be copied and second is the length of the new array, and import java.util.Arrays.
-See the link for more info https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)

Related

passing an array as an argument; Setting up Array in Java with user input with Scanner Class

I am trying to take user input, place it into my array, display the array and then print all the values larger than the "n" values the user provides. I think I am close, but I can't get the user input to go to the array. I keep getting an error in eclipse when I call the method (main at very bottom) the "arrayValues" cannot be resolved to a variable:
import java.util.Arrays;
import java.util.Scanner;
public class LargerThanN {
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
public static void printGreaterThanN(int[] integerArray, int n) {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i]>n) {
System.out.println(integerArray[i]);
}
}
}
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
/**
* This method prints the array to the standard output
* #param array
*/
private static void displayArray( int[] integerArray) {
for (int i = `0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
int [] array ;
array = fillArrayWithUserInt();
Scanner sc = new Scanner(System.in);
fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
printGreaterThanN(array, n);
but now my output looks like:
How big will the array be?
4
Enter the 4 numbers now.
1 2 3 4
How big will the array be?
3
Enter the 3 numbers now.
1 2 3
1 2 3 4
To which number would you like to compare the rest? Your n value is:
2
3
4
Heads up, the following code does nothing in java...
public void set(int n, int value) {
n = value;
}
You seem to written code like this in many functions where a value should be returned.
For example, the function definition :
static void fillArrayWithUserInt(int[] integerArray, int arraySize, int arrayValues, int n)
Should really be written as :
static int[] fillArrayWithUserInt()
It could be implemented as follows
public static int[] fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
int[] integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
return integerArray;
}
The above function will ask the user for the array size. Create the array with the given size. Then prompt the user to fill the array with the correct number of values. The array created in this process is then returned.
All you must handle differently now is finding the value to compare. This must be done outside the fillArrayWithUserInt function.
Like so :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = fillArrayWithUserInt();
displayArray(array);
System.out.println("To which number would you like to compare the rest? Your n value is: ");
int n = sc.nextInt();
printGreaterThanN(array, n);
}
Lastly, you should not need to declare any static variables at the top of your class.
These lines can all be deleted :
//initialize n
static int n;
static int arraySize;
//setup the array
static int [] integerArray = new int [] {};
Here is my solution check it out.
import java.util.Scanner;
public class LargerThanN {
static int[] integerArray = null;
static int n ;
public static void printGreaterThanN() {
for (int i = 0; i < integerArray.length; i++) {
if (integerArray[i] > n) {
System.out.println(integerArray[i]);
}
}
}
public static void fillArrayWithUserInt() {
Scanner sc = new Scanner(System.in);
System.out.println("How big will the array be?");
int arraySize = sc.nextInt();
sc.nextLine(); // clears rest of input, including carriage return
integerArray = new int[arraySize];
System.out.println("Enter the " + arraySize + " numbers now.");
System.out.println("What are the numbers in your array?");
for (int i = 0; i < integerArray.length; i++) {
integerArray[i] = sc.nextInt();
}
System.out.println("To which number would you like to compare the rest? Your n value is: ");
n = sc.nextInt();
}
/**
* This method prints the array to the standard output
*
* #param array
*/
private static void displayArray() {
for (int i = 0; i < integerArray.length; i++) {
System.out.print(integerArray[i] + " ");
}
}
public static void main(String[] args) {
fillArrayWithUserInt();
displayArray();
printGreaterThanN();
}
}

How to define different required methods in this Java program of array manipulation?

package Exercises;
import java.util.Scanner;
public class ArrayPlusN {
public static void createArray(int indeces){
Scanner in = new Scanner(System.in);
int valueAdded, y = 0;
int[] arraySet = new int[indeces];
for(int i = 0; i < arraySet.length; i++){
System.out.printf("Enter element #%s: ",i+1);
arraySet[i] = in.nextInt();
}
System.out.println("These are the elements in your array: ");
for(int i:arraySet){
System.out.printf("%s ", i);
}
System.out.println("");
System.out.print("Enter a number to add in each of your Array's element: ");
valueAdded = in.nextInt();
System.out.println("These are the elements in your array when we added "+ valueAdded + " to each: ");
for(int i:arraySet){
arraySet[y]=i+valueAdded;
System.out.printf("%s ", i+valueAdded);
y++;
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int indeces;
System.out.print("Enter how many array index/indeces you want: ");
indeces = in.nextInt();
createArray(indeces);
}
}
Well to start things up, i'm trying to make a program where it will add a value on each element in the array, by getting user input of how many index that user wants to make, elements of the said array and the value to be added on the said array. There's no error in this code though you can copy paste it but im asking if i can do it as OOP. i don't think that this is OOP, anybody can help? I mean i wanted to seperate all those functions on each methods, is that possible? i tried it but i can't seem to know on how to call another variable from another method. i wanted to make createArray, fillArray and addElement methods to make it look more OOP rather than just making 1 createArray with all the functions in it.
Here's the code defining the main(), createArray(), fillArray() and addElement() methods; calls the methods in the order needed and accomplishes the task in the manner you want.
package Exercises;
import java.util.Scanner;
public class ArrayPlusN {
static int arraySet[];
public void createArray(int indeces){
Scanner in = new Scanner(System.in);
int valueAdded, y = 0;
arraySet = new int[indeces];
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayPlusN object=new ArrayPlusN();
int indeces;
System.out.print("Enter how many array index/indeces you want: ");
indeces = in.nextInt();
object.createArray(indeces);
object.fillArray();
object.addElement();
}
public void fillArray(){
Scanner in=new Scanner(System.in);
for(int i=0;i<arraySet.length;i++){
System.out.println("Enter element number "+(i+1));
arraySet[i]=in.nextInt();
}
System.out.println("The elements of your array are");
for(int i:arraySet)
System.out.print(i+" ");
System.out.println();
}
public void addElement(){
Scanner in=new Scanner(System.in);
System.out.println("Enter value to be added to each element");
int valueAdded = in.nextInt();
int y=0;
System.out.println("These are the elements in your array when we added "+ valueAdded + " to each: ");
for(int i:arraySet){
arraySet[y]=i+valueAdded;
System.out.printf("%s ", i+valueAdded);
y++;
}
}
}
The arraySet array is declared as a global static one. All the methods are declared as public void. The arrays are called in the main() method with the object object of class ArrayPlusN in order and gets the job done. Hope it helps you.

Java Array get digits and make number from array input

import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]

Create array for series of integers in Java?

I've been up for a few hours trying to find a solution.
My program asks the user to enter a list of integers (example: 5 2 5 6 6 1).
Then I would like to create an array and store each integer into its respective array index, consecutively.
Here is the part of my program i'm having trouble with (this program was meant to perform calculations via a method later on, but I didn't include that):
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int[] list1Array = new int[1];
System.out.println("Enter list1: ");
while (input.hasNext()){
list1Array[x] = input.nextInt();
x++;
}
As you can see, I am instantiating the array "list1Array" but the problem is I don't know how many integers the user would enter! If only there were a way of knowing how many integers have been input... Any help would be greatly appreciated!
Thanks,
Sebastian
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//int[] list1Array = new int[1];
List<Integer> list1Array = new ArrayList<>();
System.out.println("Enter list1: ");
while (input.hasNext()){
list1Array.add(input.nextInt());
}
}
}
An ArrayList, is like an array that does not have a predefined size and it dynamically changes its size; exactly what you are looking for. You can get its size by list1Array.size();
If you insist on having the final result as an array, then you can later call the toArray() method of ArrayList. This post will be helpful.
If you really want to use Arrays, do it like this:
import java.util.Scanner;
public class Assignment627 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int[] list1Array = new int[1];
System.out.println("Enter list1: ");
while (input.hasNext()) {
list1Array[x] = input.nextInt();
x++;
int[] temp = new int[list1Array.length + 1];
for (int i = 0; i < list1Array.length; i++) {
temp[i] = list1Array[i];
}
list1Array = temp;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter elemnt size ");
int size = input.nextInt();
int x = 0;
int[] list1Array = new int[size];
for (int y = 0 ; y < size ; y++) {
System.out.println("Enter number");
list1Array[x] = input.nextInt();
x++;
}
System.out.println(Arrays.toString(list1Array));
}
Output
Enter elemnt size
4
Enter number
2
Enter number
3
Enter number
4
Enter number
2
[2, 3, 4, 2]
Use List, in your case ArrayList will be fine:
List<Integer> list1Array = new ArrayList();
while (input.hasNext()){
list1Array.add(input.nextInt());
x++;
}
You should take the input as string and then use string.split(" "); and then obtain an array of Strings representing each number. Obtaining array by string can be done by string tokenizing.
UPDATE
But you should be careful not to put other chars as separators for numbers number

how to take user input in Array using java?

how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Categories

Resources