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)
Related
I just started with Java a few weeks ago and today I've tried to write a program which is able to calculate the average IQ of numbers the user can input. I've written two classes, IQ and IQTester (IQTester = Main only). Now my problem is, whenever I want to calculate something in method compute() (e.g. the average of the array) the whole array is empty. Does anybody know how I can "pass" the array from the constructor to the method compute()?
package IQProgramm;
public class IQ {
private int values[] = new int[10];
private double average;
public IQ(String numbers) {
this.values = values;
String[] values = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < values.length; ++i) {
System.out.print(values[i] + " ");
}
System.out.println("\n");
}
public void compute() {
for (int i = 0; i < values.length; ++i) {
System.out.println(values[i]);
}
}
}
package IQProgramm;
import java.util.Scanner;
public class IQTester {
public static void main(String[] args) {
Scanner readIQ = new Scanner(System.in);
System.out.println("Please enter your numbers: ");
String numbers = readIQ.nextLine();
IQ iq = new IQ(numbers);
iq.compute();
}
}
You have 2 different arrays named values, that's why it doesn't work well.
The first defined here String[] values = numbers.split(";"); is visible only in the constructor. If you want to set the value of the one that is available in the rest of the IQ class (private int values[] = new int[10];), you need to edit this one by using
this.values[i] = Integer.parseInt(values[i])
this refers to the variable values of the class IQ.
It is a good practice not to have 2 values with same name. You can change String[] values name to valuesStr for example.
Constructor with the fix:
public IQ(String numbers) {
String[] valuesStr = numbers.split(";");
System.out.println("Calculate: ");
System.out.println("You've input the following numbers: ");
for (int i = 0; i < valuesStr.length; ++i) {
this.values[i] = Integer.parseInt(valueStr[i])
System.println(this.values[i]+" ");
}
System.out.println("\n");
}
I'm not that new to programming, but I had a problem when storing the user input to the string array and store it into an int array. Does anybody know how to fix my code? Or is there any other way?
I want to store this input into a separate int array and a string array.
User input:
"T 3"
"V 4"
"Q 19"
Expected result:
num[0] = 3
num[1] = 4
num[2] = 19
store[0] = "T"
store[1] = "V"
store[2] = "Q"
This code creates an index out of bounds:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = input.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i = 0; i < k; i++)
{
String[] paint = input.next().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
]//end class
input.next() will only work if you took String data type but here you had taken int as the data type so it won't work here.
The problem is that you're calling input.next() which returns the next token, delimited by spaces. Therefore, the token itself can't contain any spaces. So the .split(" ") method call will always return a one-element array, so there is only a paint[0] and there is no paint[1]. It's not clear what you're trying to achieve in your code; if you expand the question, you may get some more answers.
Update: now that you've shown us your input and expected results, I think what you need to do is:
store[i] = input.next();
num[i] = input.nextInt();
Try this out
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int[] num = new int[k];
String[] store = new String[k];
for(int i=0; i<k; i++){
String s = sc.nextLine();
String str = sc.next();
int number = Integer.parseInt(sc.next());
num[i]=number;
store[i]=str;
}
for(int i=0; i<k; i++){
System.out.println(store[i] +" "+num[i]);
}
}
}
Check this. Minor changes done in your code.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
// Variable Declarations & Initializations
Scanner input = new Scanner(System.in);
int k = Integer.parseInt(input.next());
int[] num = new int[k];
String[] store = new String[k];
input.nextLine();
for(int i = 0; i < k; i++)
{
String paint[] = input.nextLine().split(" ");
store[i] = paint[0];
num[i] = Integer.parseInt(paint[1]);
}//end loop
}//end main
}//end class
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.
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
I can't seem to get past this error. My code:
import java.util.*;
public class Collector {
public static void Names () {
java.util.Scanner input = new java.util.Scanner(System.in);
// Prompt the user to enter the number of students
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
// Create arrays
String[] names = new String[numberOfStudents];
double[] scores = new double[numberOfStudents];
// Enter student name and score
for (int i = 0; i < scores.length; i++)
{
System.out.print("Enter student's name: ");
names[i] = input.next();
System.out.print("Enter student's exam score: ");
scores[i] = input.nextDouble();
System.out.println(" ");
}
}
void SortRoutine (String[] names, double[] scores) {
for (int i = scores.length - 1; i >= 1; i--)
{
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++)
{
if (currentMax < scores[j])
{
currentMax = scores[j];
currentMaxIndex = j;
}
}
//arrange values as necessary
if (currentMaxIndex != i)
{
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
}
// Print student data
System.out.println(" ");
System.out.println("***** Student Scores Sorted High to Low *****");
System.out.println(" ");
for (int i = scores.length - 1; i >= 0; i--)
{
System.out.println(names[i] + "\t" + scores[i] + "\t");
}
System.out.println(" ");
}
}
Main Method:
import java.util.*;
import java.util.Arrays;
public class NameCollector {
public static void main(String[] args) {
Collector collect = new Collector();
collect.Names();
collect.SortRoutine();
}
}
If I remove the arguments from line 28 of the Collector class I get cannot find symbol errors. Which I believe means that Jcreator can't find the array values. How would I go about making the array values defined in my first method visible to the second? If I leave the arguments in line 28 the error message is:
C:\Users\Dark Prince\Documents\JCreator LE\MyProjects\NameCollector\src\NameCollector.java:16: error: method SortRoutine in class Collector cannot be applied to given types;
collect.SortRoutine();
^
required: String[],double[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Process completed.
I'm thinking I should not use the arguments and make it so the array values can be seen by the sorting method, but really I just want the darn thing to work.
You asked: How would I go about making the array values defined in my first method visible to the second?
There's plenty of ways to do this. This is one way of doing it (probably not the best):
You can turn the arrays into static instance members in the Collector class like this:
public class Collector {
static String[] names;
static double[] scores;
public static void Names () {
And then when you create the arrays in the Names method you'd do this:
// Create arrays
names = new String[numberOfStudents];
scores = new double[numberOfStudents];
And finally you change the method signature for SortRoutine from:
void SortRoutine (String[] names, double[] scores)
to
void SortRoutine ()