Passing array to a method (Java) - java

I have a program that accepts a number that represents an array index and a
String to replace the array element corresponding to the index.
Here is my code:
public static void main(String args[]){
String names[]={"Alvin", "Einstein", "Ace", "Vino", "Vince"};
for(int i=0; i<names.length;i++)
System.out.println(i + " - " + names[i]);
replaceArrayElement(names);
}
public static void replaceArrayElement(String name[]){
int index = 0;
String value = "";
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter the index to be replaced:");
index = scan.nextInt();
if(index<name.length){
System.out.print("Enter the new value:");
value = scan.nextLine();
name[index] = scan.nextLine();
System.out.println("\nThe new elements of the array are");
for(int j=0; j<name.length;j++)
System.out.println(name[j]);
}
else{
System.out.println("Error!");
}
}
What I need to do is to put the int index variable and String value variable inside the method replaceArrayElement as a parameters. But I don't know how to call a method with different data type parameters. Can somebody show me how?? Thank you.

Well it's not clear where you'd get the values to pass in from, but here's how you would declare the method:
public static void replaceArrayElement(String[] name, int index, String value)
You'd call it with:
// Get the values from elsewhere, obviously
replaceArrayElement(array, 5, "fred");
Note that I've used String[] name instead of String name[] - while the latter syntax is permitted, it's strongly discouraged as a matter of style.

Declare replaceArrayElement as follows -
public static void replaceArrayElement(int index, String value, String[] name)
and call it as -
replaceArrayElement(2, "Einstein2", names);

public static void main(String args[]){
String names[]={"Alvin", "Einstein", "Ace", "Vino", "Vince"};
for(int i=0; i<names.length;i++)
System.out.println(i + " - " + names[i]);
replaceArrayElement(3,"alpesh",names);
}
public static void replaceArrayElement(int index, String replacename, String names[]){
if(index<names.length){
names[index] = replacename;
System.out.println("\nThe new elements of the array are");
for(int j=0; j<names.length;j++)
System.out.println(names[j]);
}
else{
System.out.println("Error!");
}
}

Related

Can I search for values in two different type of arrays with just one type of variable?

I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!

How to call multiple arrays in a void method?

I am stuck on how to call my method.
I get a cannot find symbols (playerName,battingArray) error message.
-Am I not calling it correctly?
-Is the method set up to populate the arrays properly?
I am not even sure if this is the best way to go about doing this.
ANY HELP IS SO GREATLY APPRECIATED!!
//Import util to accept input
import java.util.Scanner;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//Assign number of players to variable and call method readNumPlayers
int numPlayers = readNumPlayers();
System.out.println(numPlayers);
//Call readData method
readData(playerName, numPlayers, battingArray);
}//end main
//readNumPlayers method
public static int readNumPlayers() {
System.out.println("Number of players: ");
int numPlayers = input.nextInt();
if (numPlayers <=0) {
System.out.println(" Error- Try again ");
System.out.println("Number of players: ");
numPlayers = input.nextInt();
}//end catch to ensure entry is positive integer
return numPlayers; //return
}//end readNumPlayers
//readData method
public static void readData(String[] playerName, int numPlayers,
double[] battingArray) {
playerName = new String[numPlayers];
System.out.println("Enter player's last name: ");
for (int i = 0; i < playerName.length; i++) {
playerName[i] = input.next();
} //end for loop
battingArray = new double[numPlayers];
System.out.println("Enter player's batting average: ");
for (int i = 0; i < battingArray.length; i++) {
battingArray[i] = input.nextDouble();
}// end for loop
}//end readData
}
When you pass the arrays as parameters the caller of readData is supplying references to the arrays to fill in, and, while you can affect the contents of the array referenced you can't change the reference itself — so you should not allocate arrays in your method - for example, your line:
battingArray = new double[numPlayers];
When you allocate a new array and fill that in, the caller has no access to that array, and you have not put anything in the array that the caller passed (and does have access to)
Just use the double[] battingArray parameter that the caller passed in.
Here are two versions of a very simple example; in the first the readData method allocates it's own array and fills it in. You'll see that when main prints the array content you get null because the array filled by readData is not the same array that was passed.
In the second, readData just puts values into the array that the caller passed.
First:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// allocating a new array
String[] playerNames2 = new String[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// putting the value into the newly allocated array
playerNames2[i] = line.trim();
}
System.out.println("playerNames2[0] in readData: " + playerNames2[0]);
}
}
Second:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int count = 2;
String[] names = new String[count];
double[] avgs = new double[count];
readData(names, avgs, count);
System.out.println("names[0] in main: " + names[0]);
}
public static void readData(
String[] playerNames,
double[] battingAvg,
int numPlayers
)
{
Scanner in = new Scanner(System.in);
// no array allocated this time
for (int i = 0; i < numPlayers; i++)
{
System.out.print("Players name: ");
String line = in.nextLine();
// put the value into the array that was passed
playerNames[i] = line.trim();
}
System.out.println("playerNames[0] in readData: " + playerNames[0]);
}
}
Since the caller is telling you how big the arrays are (numPlayers parameter), let's say "10", if the caller's arrays aren't actually big enough (say they did new String[5]) it's possible that you get an ArrayIndexOutOfBoundsException, so readData would probably want to catch that and return without finishing the loop.
(I've created a Java repl where you can see version 2)

Unable to scan the elements into array

I am beginner in Java. I wrote a few lines of code, and it is showing error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
import java.util.Scanner;
public class Issue {
public static Scanner scan = new Scanner(System.in);
int n;
int ID[]=new int[n];
String [] Name=new String[n];
public void get()
{
int ID[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + (i+1) + "st Employe ID :");
ID[i] = scan.nextInt();
System.out.println("Enter Employe Name:");
Name[i]=scan.nextLine();
}
}
public static void main(String[] args) {
Issue obj=new Issue();
System.out.println("Enter no.of Employes:");
obj.n=scan.nextInt();
obj.get();
}
}
It's a bit tricky, because although you set with obj.n=scan.nextInt(); a number to n, the array's size remains 0 since it has been initialized with the dafult n value 0.
The line:
obj.n=scan.nextInt();
Doesn't assure the reallocation of memory for the arrays ID and Name. I suggest you to avoid public variables and use the constructor for the total number encapsulation.
public static final Scanner scan = new Scanner(System.in);
private final int n;
private final int ID[];
private final String[] Name;
public Main(int number) {
this.n = number;
this.ID = new int[n];
this.Name = new String[n];
}
public void get() {
for (int i = 0; i < n; i++) {
System.out.println("Enter " + (i+1) + "st Employe ID :");
ID[i] = scan.nextInt();
scan.nextLine();
System.out.println("Enter Employe Name:");
Name[i] = scan.nextLine();
}
}
public static void main(String[] args) {
System.out.println("Enter no.of Employes:");
Main obj = new Main(scan.nextInt());
obj.get();
}
Moreover, you have to call scan.nextLine(); to consume the line itself, because Scanner::nextInt doesn't terminate the line the same Scanner::nextLine does.
At the time you have created the object of class Issue, the value of n was 0 and so you have created the arrays of ID and Name with size 0. Now after you have taken the input from user, you have only set n to the user input but the ID[] and Name[] arrays still have size 0. So inside the get method you are accessing out of box indexes in the 0-size arrays.
Here is the corrected code:
import java.util.Scanner;
public class Issue {
public static Scanner scan = new Scanner(System.in);
int n;
int ID[];
String [] Name;
public void get()
{
for (int i = 0; i < n; i++) {
System.out.println("Enter " + (i+1) + "st Employe ID :");
ID[i] = scan.nextInt();
System.out.println("Enter Employe Name:");
Name[i]=scan.nextLine();
}
}
public static void main(String[] args) {
Issue obj=new Issue();
System.out.println("Enter no.of Employes:");
obj.n=scan.nextInt();
obj.Name =new String[n];
obj.ID = new int[n];
obj.get();
}
}
In above code I have only made correction for ArrayIndexOutOfBound. However your code can be improved by following good programming practices like these:
Follow the naming conventions of methods and variables.
Make the non-final member objects of a class private and use getters and setters.
Follow separation of concern rule.
Use BufferedReader instead of Scanner for faster performance.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Occurs when you attempt to get element at an index greater than size of the
array.
For Example,
you have an array A of size 10 and you are accessing A[10] then you will get exception because
Array size is 10 so valid indexes are 0-9 to access array element
A[10] means accessing (10+1)th element that is greater than array size(10)
In your case you have initialized arrays ID and Name at time when variable n is having value 0. To resolve this error you should initialize these arrays after variable n is initialized.

Java for-loop is not executed

The first for-loop you see does not execute and I'm not sure why. It is completely ignored, I tried it in a separate method and I tried it in the main method but something seems to be ignoring but I'm not sure how to get it to run, it simply goes to the next method run in the main method.
package math;
import java.util.Scanner;
public class mathAverageValue {
static int numOfVals;
static double total;
static double average;
static double[] arr = new double[numOfVals];
static String boole;
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
public static void process() {
for (int i=0; i < arr.length; i++) {
total = total + arr[i];
}
average = total / arr.length;
}
public static void output() {
System.out.println("Your average is : " + average);
System.out.println("Would you like to average again? Y or N : ");
Scanner i = new Scanner(System.in);
boole = i.next();
if ("Y".equals(boole)) {
input();
output();
}
}
public static void main(String[] args) {
input();
output();
}
}
Assign some value to static int numOfVals. Java by default assign 0 to it. Hence your for loop will never run. Also modify your array declaration like below:-
static double arr = new double[numOfVals];
The problem is that you have assigned a value to numOfVals and then created the array in the wrong order.
public static void input() {
Scanner s = new Scanner(System.in);
System.out.println("How many values will be averaged ? : ");
numOfVals = s.nextInt();
arr = new double[numOfVals]; // <-- PUT THIS HERE
for(int i=0; i<arr.length; i++){
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
}
It is ignored because it is a zero length array:
static int numOfVals; // This implicitly equals 0.
static double total;
static double average;
static double[] arr = new double[numOfVals]; // so this has no elements.
hence
for(int i=0; i<arr.length; i++){ //arr.length is 0
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = s.nextDouble();
}
doesn't iterate
According to java primitive data types initialization, all types have a default value. In your case, static int numOfVals will be assigned with 0. This is the reason why the for loop is ignored. see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

String [][] Output issues

I am trying to write a program that i need to output a 2 dimensional array for a list of first and last names entered by the user. When I try running the program there is no errors, but it gives me this for output:
[[Ljava.lang.String;#b8f82d, [Ljava.lang.String;#1ad77a7,
[Ljava.lang.String;#18aaa1e, [Ljava.lang.String;#a6aeed,
[Ljava.lang.String;#126804e, [Ljava.lang.String;#b1b4c3,
[Ljava.lang.String;#d2906a, [Ljava.lang.String;#72ffb,
[Ljava.lang.String;#1df38fd, [Ljava.lang.String;#16a786,
[Ljava.lang.String;#1507fb2, [Ljava.lang.String;#1efb836,
[Ljava.lang.String;#126e85f, [Ljava.lang.String;#161f10f,
[Ljava.lang.String;#1193779, [Ljava.lang.String;#8916a2,
[Ljava.lang.String;#2ce908, [Ljava.lang.String;#77158a,
[Ljava.lang.String;#27391d, [Ljava.lang.String;#116ab4e,
[Ljava.lang.String;#148aa23, [Ljava.lang.String;#199f91c,
[Ljava.lang.String;#1b1aa65, [Ljava.lang.String;#129f3b5,
[Ljava.lang.String;#13f3045, [Ljava.lang.String;#17a29a1,
[Ljava.lang.String;#1434234, [Ljava.lang.String;#af8358,
[Ljava.lang.String;#d80be3, [Ljava.lang.String;#1f4689e,
[Ljava.lang.String;#1006d75, [Ljava.lang.String;#1125127,
[Ljava.lang.String;#18dfef8, [Ljava.lang.String;#15e83f9,
[Ljava.lang.String;#2a5330]
BUILD SUCCESSFUL (total time: 0 seconds)
This is my code:
package assignment_6_1;
import java.util.Scanner;
import java.util.Arrays;
public class Assignment_6_1 {
public static void main(String[] args) {
//Create a Scanner
Scanner input = new Scanner(System.in);
//Create int & string []
String[][]firstAndLastNames = new String[36][2];
int[]heightOfPerson = new int[36];
//Gather list of names and heights
for(int i=0; i<heightOfPerson.length; i++)
{
//Get first name
System.out.println("Enter Your First Name " + "Passenger #" + i+1 + ": ");
firstAndLastNames[1][i] = input.next();
//Get last name
System.out.println("Enter Your Last Name " + "Passenger #" + i+1 + ": ");
firstAndLastNames[2][i] = input.next();
//Get height in inches
System.out.println("Enter your height (Iches) " + "Passenger #" + i+1 + ": ");
heightOfPerson[i] = input.nextInt();
if(firstAndLastNames[36][2] != null){
System.out.println(Arrays.deepToString(firstAndLastNames));
break;}
}
}
}
I then have to output the height of the person but I have not gotten that far yet.
Don't use Arrays.toString(array). Use Arrays.deepToString(array). It will print multi-dimensional arrays.
String[][] array = new String[][] {
{ "Apple", "Pear", "Fruit" },
{ "Pi", "Rho", "Omega" },
{ "Jack", "Jill", "Joe" }
};
System.out.println(Arrays.deepToString(array));
//Prints: [[Apple, Pear, Fruit], [Pi, Rho, Omega], [Jack, Jill, Joe]]
Maybe you should not do
for(int i=0; i>35; i++)
but rather
for(int i=0; i<35; i++)
You are stringifying the outer array, but the inner arrays are not handled. What you need to do is to build the output by iterating over the outer array.
This should help:
for (String[] firstAndLastName : firstAndLastNames) {
System.out.println(firstAndLastName[0] + ", " + firstAndLastName[1]);
}
Alternatively you can store the user details in a User object. Then, if you define a toString method on that object thhe original Arrays.toString call will produce more legible output.
class User {
private String firstName, lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
...
public String toString() {
return firstName + ", " + lastName;
}
}
Also, as nielsen points out your for loop has the wrong loop test on it. You have an empty array at the moment so you need to address that as well.
Answer by matthew is perfect but if we do small change in concat operation then it will become more fluent for eg.
public static void main(String...args) {
String[][] firstAndLastName = {
{"Bob","Martin"},
{"Martin","Fowler"}
};
for(String[] name : firstAndLastName) {
System.out.println(toString(name));
}
}
private static String toString(String[] a) {
int iMax = a.length - 1;
StringBuilder b = new StringBuilder();
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.toString();
b.append(", ");
}
}
You are trying to store the last name in a place that does not exist in your array!
You are declaring your array like this:
String[][]firstAndLastNames = new String[35][1];
This means you have 35 rows, and 1 column. Arrays start at index zero. Not one.
When you are trying to store your last names:
firstAndLastNames[i][1] = input.next();
You are not calling the correct column index. Change the array delcaration line line to this:
String[][]firstAndLastNames = new String[35][2]; //now we have 2 columns
Once you store the data correctly, you need to iterate through the array to properly display your data.
try the following code:
public static void main(String[] args) {
String[][] array = new String [3][2]; //Notice how the column declaration is now '2'. This means available indexes are 0 and 1.
Scanner scn = new Scanner (System.in);
for (int i = 0; i < array.length; i++) {
System.out.println ("Enter data " + i + ")");
array[i][0] = scn.nextLine();
}
array[0][1] = "1"; //Understand why this works now?
array[1][1] = "2";
array[2][1] = "3";
for (int i = 0; i < array.length; i++) {
for (int k = 0; k < 2; k++) {
System.out.println((array[i][k]));
}
}
}

Categories