Scope of the array: - java

Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}

public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}

Related

How can I export matrix from user input to other class as a two-dimensional array?

So I wrote a method to make a matrix from user input like this:
public class matrix1 {
public static void getMatrix() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number of matrix rows. ");
int matrixRow;
do {
System.out.println("Please enter valid number.");
matrixRow = scan.nextInt() ;
} while (matrixRow>4);
System.out.println("Please enter the number of matrix columns.");
int matrixCol;
do {
System.out.println("Please enter valid number.");
matrixCol = scan.nextInt() ;
} while (matrixCol>4);
//defining 2D array to hold matrix data
int[][] matrix1 = new int[matrixRow][matrixCol];
enterMatrixData(scan, matrix1, matrixRow, matrixCol);
// Print Matrix Data
printMatrix(matrix1, matrixRow, matrixCol);
}
public static void enterMatrixData(Scanner scan, int[][] matrix, int matrixRow, int matrixCol){
System.out.println("Please enter data for your matrix.");
for (int i = 0; i < matrixRow; i++)
{
for (int j = 0; j < matrixCol; j++)
{
matrix[i][j] = scan.nextInt();
}
}
}
public static void printMatrix(int[][] matrix, int matrixRow, int matrixCol){
System.out.println("Your matrix is : ");
for (int i = 0; i < matrixRow; i++)
{
for (int j = 0; j < matrixCol; j++)
{
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
}
And it works like a charm, but I'm a total beginner and now I want to use this created array to multiply it by a scalar. In my main method I invoke
matrix1.getMatrix();
The multiplying method is in another class. Can I import this user-made array and use it in multiplying class?
Just change the return type to int[][] and add a return statement in the last line:
public int[][] getMatrix() {
// ... you already got all this
return matrix1;
}
Your main can then just call that:
public static void main(String[] args) {
int[][] matrix = getMatrix();
// now you can just pass it to your multiplier as a parameter, e.g.:
MatrixMultiplier.multiplyWithScalar(matrix, 2);
}
I would rename your getMatrix to something like readMatrix though, because there is a convention that methods named get[SomeFieldName] should be simple accessor functions that usually don't do a lot of work.
Better design, however, would be to wrap your primitive array as a member of your matrix class:
class Matrix {
private final int[][] data;
private Matrix(int[][] data) {
this.data = data;
}
public static Matrix fromUserInput() {
int[][] matrix1;
// code for reading from input here
return new Matrix(matrix1);
}
}
and make your Multiplier accept an instance of your Matrix class:
public static void main(String[] args) {
Matrix matrix = Matrix.fromUserInput();
MatrixMultiplier.multiplyWithScalar(matrix, 2);
}
Of course, now your matrix class needs to provide methods for getting and setting field values at specific indices.

Why is array giving a wrong value when using two classes?

I have this code here.
public class ArrayChallenge {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of integers: ");
int num = kb.nextInt();
int [] returnedArray = readIntegers(num);
System.out.println("Ascending Order: " + printAsc(returnedArray));
}
public static int [] readIntegers(int count){
int [] values = new int[count];
for(int i=0; i<count; i++){
System.out.print("Enter number: ");
values[i] = kb.nextInt();
}
return values;
}
public static int [] printAsc(int [] theArray){
Arrays.sort(theArray);
return theArray;
}
The code above works perfectly fine. I have only one class but several static methods and during calling the method printAsc(returnedArray), the program will return a set of arrays in a format just like using .toString
I took this code to a next level using two classes and making the static methods to instance methods. However when i print the arrays. It prints these values [I#643b1d11
Here is my code below:
Main Class
public class Main {
public static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the number of elements: ");
int num = kb.nextInt();
int numArrays [] = new int[num];
Minimum minimum = new Minimum();
int [] returnedArrays = minimum.readIntegers(numArrays);
int returnedMin = minimum.findMin(returnedArrays);
System.out.println("Minimum Value: " + returnedMin);
System.out.println("Ascending Arrays: " + minimum.arrayAsc(returnedArrays));
}
}
Minimum Class
public class Minimum {
public int [] readIntegers(int [] numArrays){
System.out.println("Enter " + numArrays.length + " integers:");
for(int i=0; i< numArrays.length; i++){
numArrays[i]=Main.kb.nextInt();
}
return numArrays;
}
public int findMin(int [] numArrays){
int max = Integer.MAX_VALUE;
for(int i=0;i<numArrays.length;i++){
if(max>numArrays[i]){
max = numArrays[i];
}
}
return max;
}
public int [] arrayAsc(int [] numArrays){
Arrays.sort(numArrays);
return numArrays;
}
}
How did the result of my arrays became like that? Can someone explain the process to me? Much appreciate.
Also, i used the debug method because im using Intellij, It didnt really show anything.
The way you are using printAsc, you need to change its definition to return a String.
public static String printAsc(int [] theArray){
Arrays.sort(theArray);
return Arrays.toString(theArray);
}
If you do not want to change the definition of printAsc, you need to call it as follows:
System.out.println("Ascending Order: " + Arrays.toString(printAsc(returnedArray)));
You can't just print an Array and expect it to read out all the values. When printing, Java casts the value into a String. By default, when dealing with Objects, Java will simply print the name of the Object's class and its Hash value. This is what you see. You can read more about it here.
If you want to parse the Array into a String that hold all the members of the Array, you might want to take a look at the Arrays.toString method (and how to use it).

arrayindexoutofboundexception: 0 with an initialized array

OK so in my class file I have
import java.util.Scanner;
public class PriceArray
{
int n;
Scanner sc = new Scanner(System.in);
double pArray[];
public PriceArray(int nBooks)
{
pArray = new double[n];
n = nBooks;
}
public void pEntry()
{
double p;
for(int i =0;i<n;i++)
{
p=-1;
while(p<0)
{
System.out.println("Please enter a positive price for item #" + i);
p = sc.nextDouble();
pArray[i] = p;
}
}
}
and in my test file I have
public class PriceArrayTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n;
do
{
System.out.println("Please enter a positive number of books in the store");
n = sc.nextInt();
}while(n<0);
PriceArray store = new PriceArray(n);
store.pEntry();
when the pEntry method is called I am getting arrayindexoutofboundexception: 0 for the line
pArray[i] = p;
in the entry method, my question is why am I getting this error when the array has been initialized?
You need to switch "n = nBooks;" to happen before "pArray = new double[n];"
Look closely at the value of n when you initialize pArray with new double[n]:
int n;
double pArray[];
public PriceArray(int nBooks) {
pArray = new double[n];
n = nBooks;
}
At that point in the code, n was not assigned a value yet.
Since it's an int, its value defaults to 0 in this case.
As a result, pArray effectively gets initialized with new double[0],
an empty array, so referencing index 0 will be out of bounds.
One way to fix:
public PriceArray(int nBooks) {
pArray = new double[nBooks];
n = nBooks;
}
Another way:
public PriceArray(int nBooks) {
n = nBooks;
pArray = new double[n];
}
You are hiding the value of n in your code, so you don't get the value you read in.
Hiding Fields
(Or as mentioned you may just be using two different n without hiding. The other n is simply uninitialized.)
This variable hides (or at least isn't the same as) the value you use in the other part of your code:
int n;
do
{
System.out.println("Please enter a positive number of books in the store");
n = sc.nextInt(); // <-- This 'n' hides the other n
And the other part of your code, which does not use the same value of n
public class PriceArray
{
int n; // <-- a *DIFFERENT* 'n'
Scanner sc = new Scanner(System.in);
double pArray[];
public PriceArray(int nBooks)
{
pArray = new double[n]; // <-- This 'n' is not the same as the other
n = nBooks;

Generate random integers with a range and place them into this array

I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}

How to make an Array Accessible from instantiation in main class? Accessible to all classes in same class

I want to run a method that returns an array. Code such as this:
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println(
"Please input the integer for position " + (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
I have researched that you can make a variable like so int[] data = getArray();
How would I make it so that data can be accessible to other methods in the same class so I could do something like
public static int linearSearch(data) {
}
without having to constantly be re-entering the values for the array?
You can try out to introduce private variable of int[] and provide a lazy initialization for it, something like this:
class aClass {
int[] data; // default to the null
private int[] getArray() {
if (data == null) {
// your console logic for initialization
}
return data;
}
public static int linearSearch() {
int[] localData = getArray();
}
}
But in this case you can change the contents of data field in your methods across the class.
This can be done two ways:
- Either declaring the variable as class-level variable
- Or declaring it as local variable inside main method
public class ReturnIntArraysSO {
/**
* #param args
*/
public static void main(String[] args) {
int[] data = getArray();
for(int i : data){
System.out.print(i+" ");
}
linearSearch(data);
}
/**
*
* #return
*/
public static int[] getArray() {
int square[] = new int[5];
int input = 0;
System.out.println("Input a valid integer from 1-49");
System.out.println("for array input please \\(^-^)/");
System.out.println("Remember (^_'), don't repeat numbers");
Scanner reader = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Please input the integer for position "
+ (i + 1) + " of the array");
input = reader.nextInt();
square[i] = input;
}
return square;
}
/**
*
* #param data
* #return
*/
public static void linearSearch(int[] data) {
for(int a : data){
if(a == 5){
System.out.println("\nFound 5!!");
}
}
}
}
You need to declare i your array like this:
public YourClass {
public static int[] square = new int[5];
}
This way you can access this array from any other class and it will remain with the exact array (that's what static for). Example:
From Class1 - YourClass.square
From Class2 - YourClass.square
Both are the same array instance

Categories

Resources