Java Arrays - How to create an array using a static method - java

I am searching for the lines of code to create a new array using a method called insertRow(int[] row). With this method, users can insert 5 numbers to form an array. Then this array should be named row2. Please help.
public class App
{
public static void main(String[] args)
{
int[] row = new int[5];
int[] row1 = {2,7,1,9,4};
//int[] row2 = insertRow(row); this is wrong
}
public static void insertRow(int[] row)
{
for (int i = 0; i < row.length; i++)
{
int number;
do
number = Integer.parseInt(JOptionPane.showInputDialog("Insert the " + (i+1) + "th positif number"));
while (getal < 0);
row[i] = number;
}
}
}

You were on the right track: change the signature of your method to return int[], allocate the row inside, and put your code in place of ... below:
public static int[] insertRow() {
int[] row = new int[5];
...
return row;
}
Now this will work:
int[] row2 = insertRow(); // this is no longer wrong :)

Related

Modify the java program so that it works for the numbers in range between -25 and 25

I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.
Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)
Here's the original code:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 15;
final int MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
And here's my solution to it:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 51;
final int MULTIPLE = 1;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = (index - 25) * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
Yes, basically it's really simple exercise.
Regarding to your solution we actually don't need MULTIPLE in code.
public class BasicArray {
public static void main(String[] args) {
final int LIMIT = 51;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++) {
list[index] = (index - 25);
}
list[5] = 999; // change one array value
// Print the array values
for(int value : list) {
System.out.println(value + "");
}
}
}
If you are ready for a bit of advanced java, you can try following:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(System.out::println);
}
}
Or this if you need to replace one value:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(i -> {
if (i == -20) { // change one array value
System.out.println(999);
} else {
System.out.println(i);
}
});
}
}

Conflicting method parameters

This is a portion of the client provided by my prof and I'm not allowed to make changes to it.
public static void print (String title, int [] anArray) {
System.out.print(title + ": ");
for (int i = 0; i < anArray.length; i++) {
System.out.print(anArray[i] + " ");
}
System.out.println();
}
public static void main (String [] args) {
System.out.println("\nTesting constructor");
ScoreList list1 = new ScoreList(13);
System.out.println("\nTesting accessor (getter)");
int[] list1_array = list1.getScores();
System.out.println("\nTesting toString");
System.out.print("list1: " + list1);
System.out.println("\nTesting our print method");
print("list1's array", list1_array);
ScoreList list2 = new ScoreList(list1_array);
System.out.println("\nTesting list1 and list2");
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("\nTesting equals");
System.out.println("It is " + list1.equals(list2)
+ " that list1 is equal to list2");
if (!list1.equals(list2)) {
System.out.println("Error. The equals method does not work correctly");
System.exit(1);
}
This is a portion of my code that I wrote that will be tested by this client:
int [] scores;
public ScoreList(int size) {
if (size >= 1) {
this.scores = new int [size];
for(int i = 0; i < this.scores.length; i++) {
this.scores[i] = random(100);
}
}
else {
System.out.println("Length of array must be greater than or equal to 1.");
}
}
public ScoreList(int [] size) {
if (size.length >= 1) {
this.scores = new int [size.length];
for(int i = 0; i < this.scores.length; i++) {
this.scores[i] = random(100);
}
}
}
private int random(int randomAmount) {
Random rand = new Random();
int randomNumber = rand.nextInt(randomAmount);
return randomNumber;
}
public int [] getScores() {
int [] temp = new int [scores.length];
for(int i = 0; i < scores.length; i++) {
temp[i] = this.scores[i];
}
return temp;
}
The error here is that list1 and list2 will never be equal because I have 2 constructors, one that accepts int as a parameter and one that accepts int []. They both call random() simultaneously to provide the elements for list1 and list2. To make them equal, I think there should only be one constructor, so random() will only be called once. However, the parameters conflict. You see, according to the client, list1's parameter is 13, an int; list2's parameter is an int[].
This is the instruction I got from my prof on how to create the constructor for this class:
A constructor with just one parameter, the size of this object’s scores array, which must
be ≥ 1. It creates an array of the supplied size and the then fills that array with random
integers between 0 and 100, inclusive.
I don't know exactly what you want, but I think you just create the function creating new array from the other.
The second constructor could be like below.
public ScoreList(int[] array) {
// If you have to check array size, do it in here.
this.scores = new int[array.length];
for(int i=0;i<array.length;i++) {
this.scores[i] = array[i];
}
}
or If there should be only one constructor, please make it as a function.

How to increase size of array [a][b] every time I call a method?

public static int arraysize=1;
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][]=new String[arraysize][3];
public static int a=0;
public void isiData(String kategori, String buku, String penulis){
this.buku[a][0]=kategori;
this.buku[a][1]=buku;
this.buku[a][2]=penulis;
arraysize++;
a++;
}
Hi guys I tried to increase my array length every time I call a method named "isiData", but it didn't work. I already checked the increment, but nothing wrong with it. Is there any way to increase its length every time I use the method? I want to make a simple way to input book, category, and its author using array.
You cannot increase the size of array.
There are 3 approaches to solve this problem:
Use ArrayList as suggested by others.
You can create another temp array of size one greater than the previous array and then copy the temp array to already created array.
You can use the copyOf(array, size) function of Arrays in Java
For example:
previousArray = Arrays.copyOf(previousArray , arraysize + 1);
arraysize += 1
Just try this Approach:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
/**
*
* #author Maverick
*/
public class Buku {
public static int arraysize;
public String namabuku;
public String penulis;
public String Kategori;
public List<List<String>> bukuList = new ArrayList<List<String>>();
public static void main(String[] args) {
Buku n = new Buku();
for (int i = 0; i < 5; i++) {
n.isiData("ab" + i, "cd" + i, "ef" + i);
}
n.arraysize = n.bukuList.size();
for (int i = 0; i < n.bukuList.size(); i++) {
System.out.println(n.bukuList.get(i).toString());
}
}
public void isiData(String kategori, String buku, String penulis) {
bukuList.add(Arrays.asList(kategori, buku, penulis));
}
}
Output:
[ab0, cd0, ef0]
[ab1, cd1, ef1]
[ab2, cd2, ef2]
[ab3, cd3, ef3]
[ab4, cd4, ef4]
You have to call new array to change the size of an array. I assume this is an exercise to practice using an array, so I'm going to avoid the classes like Arrays and System in the isiData method. You should look at those classes though.
So something like this:
public class BukuTest
{
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][] = new String[ 0 ][ 3 ];
public void isiData( String kategori, String buku, String penulis )
{
String[][] temp = this.buku;
final int len = temp.length;
this.buku = new String[ len + 1 ][];
for( int i = 0; i < len; i++ )
this.buku[i] = temp[i];
this.buku[len] = new String[ 3 ];
this.buku[len][0] = kategori;
this.buku[len][1] = buku;
this.buku[len][2] = penulis;
// not needed
// arraysize++;
// a++;
}
public static void main(String[] args) {
BukuTest b = new BukuTest();
b.isiData( "test1", "test2", "test3" );
b.isiData( "test4", "test5", "test6" );
b.isiData( "test7", "test8", "test9" );
System.out.println(b);
}
#Override
public String toString()
{
return "BukuTest{" + "namabuku=" + namabuku + ", penulis=" + penulis +
", Kategori=" + Kategori + ", buku=" +
Arrays.deepToString(buku) + '}';
}
}
Using an ArrayList is definitely the way to go here as others have commented and displayed but, if you are absolutely bent on using a Two Dimensional String Array then this can be done with a custom method conveniently named redimPreserve() as I have shown below.
As #Jdman1699 had mentioned in his comment under your post, this is a very inefficient way of doing this sort of thing especially for larger arrays but since you asked, here is how it can be done:
// YOUR METHOD:
public int arraysize = 1;
public String[][] buku = new String[arraysize][3];
public void isiData(String kategori, String buka, String penulis){
// I have renamed the buku argument for this method to buka
// since you can not have a parameter variable named the
// same as a Class Global variable.
buku = redimPreserve(buku, arraysize, 3);
buku[arraysize-1][0] = kategori;
buku[arraysize-1][1] = buka;
buku[arraysize-1][2] = penulis;
arraysize++;
}
// THE redimPreserve() METHOD:
public static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
int newCol = 0;
if (newColSize.length != 0) { newCol = newColSize[0]; }
// The first row of your supplied 2D array will always establish
// the number of columns that will be contained within the entire
// scope of the array. Any column value passed to this method
// after the first row has been established is simply ignored.
if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
if (newCol == 0 && newRowSize <= 1) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Column dimension provided for 2D Array!\n");
}
if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Row dimension provided for 2D Array!\n");
}
String[][] tmp = new String[newRowSize][newCol];
if (yourArray.length != 0) {
for(int i = 0; i < yourArray.length; i++) {
System.arraycopy(yourArray[i], 0, tmp[i], 0, yourArray[i].length);
}
}
return tmp;
}

Possible to create two different sized arrays/matrices from a file?

Basically, I'm trying to create two different sized 2D arrays from a text file that looks like this:
2
add
3 4
2 1 7 -10
0 5 -3 12
1 7 -2 -5
0 1 2 3
4 5 6 7
8 9 0 1
subtract
2 2
2 12
10 0
4 6
9 1
The 2 is the number of problems (add and subtract), the 3 and 4 are the number of rows and columns, and the numbers below it are the two separate matrices being filled into the 2D arrays. If I just stop there, this program works correctly:
class Matrices {
private Scanner fileReader;
private int rows;
private int columns;
int problems;
String method;
public Matrices(String file) throws FileNotFoundException {
this.fileReader = new Scanner(new FileInputStream(file));
problems = fileReader.nextInt();
method = fileReader.next();
if(method.equals("add")) {
rows = fileReader.nextInt();
columns = fileReader.nextInt();
}
}
public int[][] readMatrix() throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return result;
}
public int[][] add(int[][] a, int[][] b) {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return result;
}
public void printMatrix(int[][] matrix) {
for ( int[] anArray : matrix ) {
for ( int anInt : anArray ) {
System.out.print(anInt+ " ");
}
System.out.println();
}
}
}
With this driver:
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
Matrices matrixReader = new Matrices(filename);
int[][] a = matrixReader.readMatrix();
int[][] b = matrixReader.readMatrix();
System.out.println("Matrix 1: ");
matrixReader.printMatrix(a);
System.out.println();
System.out.println("Matrix 2: ");
matrixReader.printMatrix(b);
System.out.println();
System.out.println("Addition: ");
int[][] addition = matrixReader.add(a,b);
matrixReader.printMatrix(addition);
}
}
It creates and prints the matrices just fine, with no problems. However, whenever I try to create and print the next two matrices (the 2x2 arrays below subtract in the text file), it returns the following error:
Enter name of file:
data/Matrices.txt
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at baker.Matrices.readMatrix(Matrices.java:27)
at baker.MatricesDriver.main(MatricesDriver.java:15
My question is, what adjustments should I make so that the program recognizes that two of the 2D arrays are to be 3x4, and the two following are to be 2x2?
I would recommend decomposing your implementation into the following parts:
class Matrix - holds the values of one matrix from problem definition
class Problem - holds the operation and the two matrices from problem definition
The Matrix class could look like:
class Matrix {
private int[][] values;
public Matrix(int[][] values) {
this.values = values;
}
public int[][] getValues() {
return values;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Matrix [values=\n");
for (int i = 0; i < values.length; i++) {
sb.append("\t" + Arrays.toString(values[i]) + "\n");
}
sb.append("]");
return sb.toString();
}
}
The Problem class could be:
class Problem {
private String operation;
private Matrix first;
private Matrix second;
public Problem(String operation, Matrix firstMatrix, Matrix secondMatrix) {
this.operation = operation;
first = firstMatrix;
second = secondMatrix;
}
public String getOperation() {
return operation;
}
public Matrix getFirst() {
return first;
}
public Matrix getSecond() {
return second;
}
#Override
public String toString() {
return "Problem [\noperation=" + operation + ", \nfirst=" + first + ", \nsecond=" + second + "\n]";
}
}
Based on this, your "driver" class does the following:
Get the filename from user input
Read from file the number of problems and construct a list with this initial size
For the number of problems (i.e. 2) get the operation, rows, and colums and construct a new Problem object containing these information and put the Problem into the list ...
Here is one simple solution - still room for improvement here :-)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MatricesDriver {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter name of file: ");
String filename = keyboard.next();
List<Problem> problems = readProblems(filename);
System.out.println(problems);
keyboard.close();
}
private static List<Problem> readProblems(final String filename) throws FileNotFoundException {
Scanner fileReader = new Scanner(new FileInputStream(filename));
int numberOfProblems = fileReader.nextInt();
List<Problem> problems = new ArrayList<>(numberOfProblems);
for (int i = 1; i <= numberOfProblems; i++) {
problems.add(readProblem(fileReader));
}
fileReader.close();
return problems;
}
private static Problem readProblem(Scanner fileReader) throws FileNotFoundException {
fileReader.nextLine(); // go to next line
String operation = fileReader.nextLine(); // read problem operation
int rows = fileReader.nextInt(); // read number of rows
int columns = fileReader.nextInt(); // read number of columns
Matrix firstMatrix = readMatrix(rows, columns, fileReader);
Matrix secondMatrix = readMatrix(rows, columns, fileReader);
return new Problem(operation, firstMatrix, secondMatrix);
}
private static Matrix readMatrix(final int rows, final int columns, final Scanner fileReader) throws FileNotFoundException {
int[][] result = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
result[i][j] = fileReader.nextInt();
}
}
return new Matrix(result);
}
}
Tested with your input file.
HTH
You tried to structure your data?
you can use that:
properties-file
For create array or vector without a fixed size use arrayList, you can make a arrayList from a arrayList

trouble defining array locally and passing parameters to other methods

My assignment was to write a Java class that creates an array of integers, fills it with values, prints the unsorted values, sorts the values into ascending order, and finally prints the sorted values.
For the most part I have done that and my output is fine. However I have not been able to define the array locally within the main(), and pass it as a parameter to the other methods.
I try to define it as a static member of the class which cannot be done.
Can anyone help me out? I need to define the array in the main() and pass it as a parameter to the methods. But I just cannot figure it out despite tireless research.
Here is what I have so far.
public class ArraySort {
private static Object sc;
int[] array;
// creates question and int for user input
/**
*
*/
public void fillArray() {
Scanner keyboardScanner = new Scanner(System.in);
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
array = new int[n];
// creates new question by including int
System.out.println("Enter " + n + " values" );
// creates for loop for repeating question based on array size
for (int i=0; i<n; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg) {
System.out.println(msg);
for (int i=0; i<array.length; i++) {
System.out.println(array[i]);
}
}
// defines method
public void sortArray() {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
ArraySort arraySort = new ArraySort();
arraySort.fillArray();
System.out.println();
arraySort.printArray("The unsorted values... ");
arraySort.sortArray();
System.out.println();
arraySort.printArray("The sorted values... ");
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
I have no errors, I just need help on how to define the array locally in the main()
Thanks.
Remove the int[] array; declaration from the class. Add it to the main method:
int[] array = new int[n];
And add an argument int[] array to each method which needs to access it. For example:
public void printArray(String msg, int[] array) {
...
}
You can declare your array locally in your main method. And pass it as a parameter to the method you are calling.
Since when you pass array as parameter to another method, its reference will be copied to the parameter. So any change you make to passed array in your method, will get reflected back in your main() method in your original array. Try using this. I don't think you will face any problem.
UPDATE: - Ok, here's the modified code: -
import java.util.Scanner;
public class ArraySort {
private static Object sc;
private static Scanner keyboardScanner = new Scanner(System.in);
// creates question and int for user input
/**
*
*/
public void fillArray(int[] array) {
// creates for loop for repeating question based on array size
for (int i=0; i<array.length; i++) {
System.out.println("Enter value for element " + i + ": ");
array[i] = keyboardScanner.nextInt();
}
}
// prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] array) {
// sets up to output in ascending order
for (int i=0; i<array.length; i++) {
for (int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
// main output and visual layout
public static void main(String[] args) {
System.out.println("Enter the size of the array (3 to 10): ");
int n = keyboardScanner.nextInt();
int[] array = new int[n];
ArraySort arraySort = new ArraySort();
arraySort.fillArray(array);
System.out.println();
//I still get an error saying " cannot find symbol"
arraySort.printArray("The unsorted values... ", array);
//same here
arraySort.sortArray(array);
System.out.println();
//and here
arraySort.printArray("The sorted values... ", array);
// Keep console window alive until 'enter' pressed (if needed).
System.out.println();
System.out.println("Done - press enter key to end program");
}
}
Update public void printArray(String msg) { and public void sortArray() { to accept int [] as
/ prints i in the for loop
public void printArray(String msg, int[] argsArray) {
System.out.println(msg);
for (int i=0; i<argsArray.length; i++) {
System.out.println(argsArray[i]);
}
}
// defines method
public void sortArray(int[] argsArray) {
// sets up to output in ascending order
for (int i=0; i<argsArray.length; i++) {
for (int j=i+1; j<argsArray.length; j++) {
if (argsArray[i] > argsArray[j]) {
int temp = argsArray[i];
argsArray[i] = argsArray[j];
argsArray[j] = temp;
}
}
}
}
And you may want to leave array = new int[n]; in fillArray as local as:
int[] array = new int[n];
and remove it from class variable declaration.
You've said that you need to define the array in the main() and pass it as a parameter to the methods. If so, then you'll need to change those methods, e.g.:
public void printArray(String msg, int[] argsArray)
public void sortArray(int[] array)
fillArray is different, because you create the array in the method based on a size which is input by the user, so you can't simply pass the array as an argument. You can return the new array:
public int[] fillArray()
{
int[] array;
// ...
return array;
}
But if you're only trying to test your class then note that you have access to the ArraySort.array field from main: you can set the field to an array that you create in main.
So in main:
ArraySort arraySort = new ArraySort();
arraySort.array = new int[]{ 5, 4, 3, 6, 7};
// and remove the fillArray call
// ...
Note that if you want to set the array like this, then you should also remove the fillArray call, which tries to set the array from user-entered values.

Categories

Resources