How to access array from constructor - java

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

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 determine why a Java program is not accepting 7 console inputs?

I have an application where you are supposed to enter 7 integers and then the application is supposed to tell you how many occurrences each number is put in.
Example: if I have 5 6 7 8 8 5 8, then it is supposed to come back that I have two 5's, one 6, one 7, and three 8's. All I'm getting out of it, however; is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
import java.util.Scanner;
public class U7A1_NumberCount {
public static void main(String[] args) {
final int MAX_INPUT_LENGTH = 7;
int[] inputArray = new int[MAX_INPUT_LENGTH];
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
int max = 0;
int nums = input.nextInt();
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
if(inputArray[n] > max) {
max = inputArray[n];
}
}
int[] count = new int[max + 1];
for(int n = 0; n < MAX_INPUT_LENGTH; n++) {
count[(inputArray[n])]++;
}
for(int n = 0; n < count.length; n++) {
if(count[n] > 0) {
System.out.println("The number " + nums + " occurs " + count[n] + " times.");
}
}
}
}
For input of the numbers, I would use something that can take many integers on a single line split by some delimiter. So basically, if the comma is the delimiter,
Scanner scan = new Scanner(System.in);
// some prompt here
List<Integer> intList = Stream.of(scan.nextLine().split(','))
.map(String::trim)
.map(Integer::new)
.collect(Collectors.toList());
Obviously, some more error handling could be useful (e.g. skipping things which cannot be parsed to an integer). You could also change your delimiter to be anything which is not a digit.
Then I would create a HashBag (for example, I will be using the implementation in Apache Commons Collections) and print the results with the bag's toString.
HashBag bag = new HashBag(intList);
System.out.println(bag.toString());
Or you could iterate through the HashBag to get and print the information you want.
Implementation of a HashBag-like object would be trivial: make a class backed with a HashMap<Object, Integer> and use some kind of adding method to call an Object#equals and if true, increment the value, and if false, create a new key with value 1.
Java is object oriented language, so use classess and objects to simplify your code. I would do it like that:
public class CountNumbers {
private Map<Integer,Integer> numbers = new HashMap<>();
public void addNumber(Integer number){
Integer howMany =numbers.get(number);
if( null != howMany){
howMany++;
}else{
howMany=1;
}
numbers.put(number,howMany);
}
public Map<Integer,Integer> getNumbers(){
return numbers;
}
}
public class Majn {
final static int MAX_INPUT_LENGTH = 7;
public static void main(String[] args) {
CountNumbers countNumbers = new CountNumbers();
System.out.print("Please, enter seven integers: ");
Scanner input = new Scanner(System.in);
for(int i = 0; i< MAX_INPUT_LENGTH; i++) {
int nums = input.nextInt();
countNumbers.addNumber(nums);
}
for(Integer number: countNumbers.getNumbers().keySet()){
System.out.format("The number %d occurs %d\n", number, countNumbers.getNumbers().get(number));
}
}
}
is the first number i put in, in this case 5, and then it occurs 7 times. How do I fix this problem?
You created an array to hold 7 integers, but you didn't utilise it. You only assigned value to another variable:
int nums = input.nextInt();
If you want to input all 7 inputs into the array, you can prompt the user n times:
for(int i=0; i<inputArray.length; i++)
inputArray[i] = input.nextInt(); //requires user to press enter 7 times
first at all, if you do not understand your code make it more readable ... this avoids a lot of problems simply in the beginning.
according to clean code of robert c. martin try to write down the code as you think about it. (https://de.wikipedia.org/wiki/Clean_Code)
here is one very reduced example to make it not to complicate
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class U7A1_NumberCount {
private static class NumberCount {
public NumberCount(final int number, final int amount) {
this.number = number;
this.amount = amount;
}
int amount;
int number;
}
public static void main(final String[] args) {
final int MAX_INPUT_LENGTH = 7;
final int[] userInput = readUserInput(MAX_INPUT_LENGTH);
final List<NumberCount> count = getNumberCount(userInput);
printResult(count);
}
private static NumberCount countSingleNumber(final int nr, final int[] userInput) {
int amount = 0;
for (int i = 0; i < userInput.length; i++) {
if (userInput[i] == nr) {
amount++;
}
}
return new NumberCount(nr, amount);
}
private static List<NumberCount> getNumberCount(final int[] userInput) {
final List<NumberCount> result = new LinkedList<>();
for (int i = 0; i < userInput.length; i++) {
final int nr = userInput[i];
if (isNumberNotConsideredYet(result, nr)) {
final NumberCount count = countSingleNumber(nr, userInput);
result.add(count);
}
}
return result;
}
private static int getUsersChoice(final Scanner scanner) {
System.out.print("Please, enter a number: ");
return scanner.nextInt();
}
private static boolean isNumberNotConsideredYet(final List<NumberCount> result, final int nr) {
return result.stream().noneMatch(count -> count.number == nr);
}
private static void printResult(final List<NumberCount> count) {
for (final NumberCount nr : count) {
System.out.println("The number " + nr.number + " occurs " + nr.amount + " times.");
}
}
private static int[] readUserInput(final int inputAmout) {
final Scanner scanner = new Scanner(System.in);
final int[] userInput = new int[inputAmout];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = getUsersChoice(scanner);
}
scanner.close();
return userInput;
}
}

Java - Storing userinput using Arrays and Methods

I am trying to ask the user to enter 10 names using arrays, and then return the method. Any help would be appreciated. Thanks in advance.
import java.util.Scanner;
public class methodbankinput
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
String[] names = {};
printarray(names);
}
public static void printarray(String[] names)
{
for (int i = 1; i < 11; i++)
{
System.out.println("Please enter 10 names" + i);
names = kb.nextLine();
}
}
}
This code won't compile. You've defined Scanner kb in your main and you can't see it inside printarray.
You've also declared a 0-length array. I don't think that's what you want.
And to store something in an array, you need to specify what index you want to store the value in. Arrays are also zero-indexed so i should start at 0, as so.
for (int i = 0; i < names.length; i++) // You could use i < 10 as well
{
System.out.println("Please enter 10 names" + i);
names[i] = kb.nextLine();
}

method cannot be applied to given types / cannot find symbol

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 ()

method in class cannot be applied to given types

I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)
When I compile the program I get the error:
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();
required: int[]
found:generateNumbers();
reason: actual and formal argument lists differ in length
I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [99];
//calls the generateNumbers method
generateNumbers();
//calls the displayCounts method
displayCounts();
}
//*****************************************************************
private static int generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
return randomNumber;
}
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int[] frequency = new int[10];
for(int i = 0, size = numbers.length; i < size; i++ ){
System.out.println((i) + " counts = " + frequency[i]);
}
}//end of displayCounts
}//end of class
generateNumbers() expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error
The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.
To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.
I think you want something like this. The formatting is off, but it should give the essential information you want.
import java.util.Scanner;
public class BookstoreCredit
{
public static void computeDiscount(String name, double gpa)
{
double credits;
credits = gpa * 10;
System.out.println(name + " your GPA is " +
gpa + " so your credit is $" + credits);
}
public static void main (String args[])
{
String studentName;
double gradeAverage;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter Student name: ");
studentName = inputDevice.nextLine();
System.out.println("Enter student GPA: ");
gradeAverage = inputDevice.nextDouble();
computeDiscount(studentName, gradeAverage);
}
}
pass the array as a parameter when call the function, like
(generateNumbers(parameter),displayCounts(parameter))
If you get this error with Dagger Android dependency injection, first just try and clean and rebuild project. If that doesn't work, maybe delete the project .gradle cache. Sometimes Dagger just fails to generate the needed factory classes on changes.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [100];
//calls the generateNumbers method
generateNumbers(numbers); //passing the empty array
//calls the displayCounts method
displayCounts(numbers); //passing the array filled with random numbers
}
//*****************************************************************
private static void generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
} // here the function doesn't need to return.Since array is non primitive data type the changes done in the function automatically gets save in original array.
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int count;
for(int i = 0, size = 10; i < size; i++ ){
count=0;
for(int j = 0; j < numbers.length ; j++ ){
if(i == numbers[j])
count++; //counts each occurence of digits ranging from 0 to 9
}
System.out.println((i) + " counts = " + count);
}
}//end of displayCounts
}//end of class

Categories