I need to create class that has a setter to assign values to an array, then in the main method take command line arguments and use the method to put that in an array. I have no clue how to do this. Any help would be appreciated.
import java.util.*;
public class Number{
private double [] number = new double[3];
private double value ;
private int i;
public double[] getNumber() {
return sweet;
}
public void printNumber() {
System.out.println("Array " + Arrays.toString(number));
}
public double getValue(int i) {
return this.i;
}
public void setMethod(int i, double value) {
this.value = value;
this.i = i;
}
public class Score {
public static void main (String [] args) {
Number score = new Number();
// code to get values from keyboard into the array
edit: Thank you for your help I managed to create the new array. Now I need to be able to change the array value. In my setMethod I am guessing I need to change it to something like this..,
public void setMethod(int i, double value { //
for ( i = 0; i < this.array.length; i ++){
this.array[this.i] =this. value;
}
this.mark = mark;
this.pos = pos;
}
If you look at main() method's list of arguments, you'll see String[] args - command line arguments are passed to the main() method as arguments. You can simply read them using a for loop:
String[] yourNewArray = new String[args.length]:
for(int i = 0; i< args.length; i++) {
yourNewArray[i] = args[i];
}
Now in yourNewArray you have stored command line arguments.
It is worth to mention that yourNewArray doesn't need to be an array containg Strings. Arguments passed as command line arguments can be parsed and used as, for example integers, doubles and other types of values.
Now, as you edited your question and have new thing to figure out, I will show you an example, how you could implement method to assign new array to an existing one and another method to change single value in this array:
import java.util.*;
// This is your class - there is String[] arr - you want to be able to change whole array or its single value:
class MyClass {
String[] arr;
// To change whole array:
public void setMethod(String[] array) {
this.arr = array;
}
// To change only one value in array:
public void changeSingleValue(int index, String value) {
arr[index] = value;
}
}
public class Test {
public static void main(String[] args) {
String[] arrayFromArgs = new String[args.length];
for(int i = 0; i < args.length; i++) {
arrayFromArgs[i] = args[i];
}
MyClass obj = new MyClass();
// In this method you assign array storing command line arguments to the array in MyClass:
obj.setMethod(arrayFromArgs);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is an example of assigning another array to obj.arr:
String[] anotherArray = { "A", "B", "C", "D"};
obj.setMethod(anotherArray);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is another way to assign new values to obj.arr:
obj.setMethod(new String[]{"x", "y", "z"});
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Simple example how to change single value in obj.arr by passing the index where and value that needs to be changed:
obj.changeSingleValue(1, "Changed");
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
}
}
And the output of the above program:
obj.arr: [] // in this array you will see values passed as the command line arguments
obj.arr: [A, B, C, D]
obj.arr: [x, y, z]
obj.arr: [x, Changed, z]
Try something like the following code to copy your array:
public static void main (String [] args) {
// code to get values from keyboard into the array
String[] myArgs = new String[args.length];
for (int i = 0; i < args.length; i++) {
myArgs[i] = args[i];
}
// ...
}
Related
How to create a constructor that takes an array parameter and initialize the values in an underlying array in Java?
The constructor should do so such that when I call it in main, passing it an array as a parameter, the initialized object that is output by the constructor is the same as the array parameter.
public class MyClass<E> {
protected E[] underlyingArray;
public MyClass(Object[] arr) {
underlyingArray = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++) {
this.underlyingArray[i] = (E) arr[i];
}
}
public void print() {
for (int i = 0; i < size; i++) {
System.out.println(i + ": " + underlyingArray[i]);
}
}
public static void main(String[] args) {
final String[] array = { "d", "e", "f" };
final MyClass myArray = new MyClass((Object[])array);
myArray.print();
Expected:
0: d
1: e
2: f
Actual:
I get an index out of bounds exception as myArray was never initialized after passing arr through myClass constructor.
I have tried several combinations in MyClass constructor but have not been able to initialize the underlying array myArray successfully.
The code works, but there is no need of generics in your case
class MyClass {
private Object[] underlyingArray;
MyClass(Object[] arr) {
underlyingArray = new Object[arr.length];
for (int index = 0; index < arr.length; index++) {
this.underlyingArray[index] = arr[index];
}
}
public void print() {
for (int index = 0; index < underlyingArray.length; index++) {
System.out.println(index + " : " + underlyingArray[index]);
}
}
public static void main(String[] args) {
final String[] array = { "d", "e", "f" };
final MyClass myArray = new MyClass(array);
myArray.print();
}}
The code works just fine. Check your print()method. This works for me.
public class MyClass<E> {
protected E[] underlyingArray;
public MyClass(Object[] arr) {
underlyingArray = (E[]) new Object[arr.length];
for (int i = 0; i < arr.length; i++) {
this.underlyingArray[i] = (E) arr[i];
}
}
public void print(){
for(int i=0;i<underlyingArray.length;i++){
System.out.println(i+": "+underlyingArray[i]);
}
}
}
public static void main(String[] args) {
final String[] array = { "d", "e", "f" };
final MyClass myArray = new MyClass((Object[])array);
myArray.print();
}
Thanks everyone, the reason why my code did not work was because of an additional size variable that I did not set (not included in snippet) as part of initialization of the constructor. That explains the indexOutOfBounds exception I got as the size was always 0.
Apologies for raising a question with incomplete information. The code does work fine in the snippet above. Deserved the downvote. Thanks again.
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;
}
public class test{
public static void main(String args[]){
int val = 10;
System.out.println(val);
Obj obj = new Obj();
obj.def(val);
System.out.println(val)
}
}
public class OBJ{
public void def(int val){
val = 1;
}
}
that result is same (10 , 10) however..
public class test{
public static void main(String args[]){
double val[] = {0, 1, 2, 3, 4, 5};
Obj obj = new Obj();
for(int i = 0; i < val.length; i++){
System.out.println(val[i];
}
obj.def(val);
for(int i = 0; i < val.length; i++){
System.out.println(val[i];
}
}
}
public class OBJ{
public void def(double[] val){
for(int i = 0; i < val.length; i++){
val[i] = 1;
}
}
that is different, first print is 0 ~ 5, however, second print is 1 , 1, 1....
I don't know what is different,
in java, Array ( it mean likes int []..) use address?? like pointer in C?
P.S : Sorry for indentation.. above code write in web,
In java primitives, like the int are directly passed by value. Object, which arrays belong to aswell, are passed by value aswell, just that in this case the reference is passed as value. This means that you are working on the same instance of the array in your case.
As you can see in your example passing the int[] and changing the values in it are also affecting the original int[] that was passed to it. The true meaning of what is written above, that the reference is passed as value is that changing the reference of the object wont reflect in a change in the original value.
Here is a tiny example with comments demonstrating this.
public class TestObj {
private int val;
public TestObj(int value) {
this.val = value;
}
public static void main(String[] args) {
int value = 1;
int [] values = {1,2,3,4};
TestObj obj = new TestObj(15);
System.out.print("Print single int: ");
print(value);
System.out.println("Print int array:");
print(values);
System.out.print("Print TestObj val: ");
print(obj);
System.out.print("Changing single int value: ");
changeValue(value); // no effect
print(value);
System.out.println("Changing array int values: ");
changeValues(values); // effected
print(values);
System.out.println("Changing array value of reference: ");
changeRefValues(values); // no effect
print(values);
//
System.out.println("Changing val of TestObj");
changeVal(obj); // effected
print(obj);
System.out.println("Changing TestObj value of reference");
changeRef(obj); // not effected
print(obj);
}
static void changeValue(int value){
value *= 2; // Primitives are directly passed as value, so this wont effect the passed value.
}
static void changeValues(int[] values){
for(int i = 0;i<values.length;++i) {
values[i] *= 2; //You are working on the value of the reference that is passed. The passed int[] is effected
}
}
static void changeRefValues(int[] values){
values = new int[]{0,0,0,0}; // you change the value of the reference that is passed. The passed int[] is not effected
}
static void changeVal(TestObj obj) {
obj.val *= 2; // You are working on the value of the reference that is passed. The passed TestObj is effected
}
static void changeRef(TestObj obj) {
obj = new TestObj(30); // You change the reference, but since it is passed as value it has no effect on the passed TestObj
}
// Only used to print values from here
static void print(int[] values) {
for (int i : values) {
print(i);
}
}
static void print(int i) {
System.out.println(i);
}
static void print(TestObj obj) {
System.out.println(obj.val);
}
}
output :/
Print single int: 1
Print int array:
1
2
3
4
Print TestObj val: 15
Changing single int value: 1
Changing array int values:
2
4
6
8
Changing array value of reference:
2
4
6
8
Changing val of TestObj
30
Changing TestObj value of reference
30
The answere is quite simple looking at the first code snippet:
public class test{
public static void main(String args[]){
int val = 10; //variable var in main method
System.out.println(val); // prints var of main method
Obj obj = new Obj();
obj.def(val);
System.out.println(val) // prints var of main method
}
}
public class OBJ{
public void def(int val){
val = 1; // variable val in OBJ method
}
}
As you might see. both variables are called "var" but only one is printed out. The var variable in your OBJ method is never used.
now the other Case:
public class test{
public static void main(String args[]){
double val[] = {0, 1, 2, 3, 4, 5}; //array is an object, variable var is a pointer to the location of that object in your heap
Obj obj = new Obj();
for(int i = 0; i < val.length; i++){
System.out.println(val[i]; // you print out every number located at the space in your heap your pointer is pointing at
}
obj.def(val);
for(int i = 0; i < val.length; i++){
System.out.println(val[i]; //prints out the overwritten values
}
}
}
public class OBJ{
public void def(double[] val){ //you give the method the pointer to the location of your numbers in heap
for(int i = 0; i < val.length; i++
val = 1; //you have the exact pointer to the exact objects in your heap therefore you overwrite them
}
}
Now to this part. Your var variable is a pointer to your var[] object in your heap (yeah arrays are objects). You give your def method the pointer to your object. Therefore the object can be accessed and overwritten.
To put it in a nutshell. In your first snippet you create two int variables with no connection to each other. In your second snipped you ceate an object and a variable that is pointing to it. In that case the object can be accessed via the pointer. You could also do something like this:
int[] sameArray = var;
In this case "sameArray" would NOT be another object, but a pointer to your var[] object.
I am sorry for my terrible english, I'll correct it as soon as possible
I am trying to take data from a text file containing Strings and Integers into an ArrayList, and then sort it (which will depend on the integer values).
The text in the file pattern looks like this "Höllviken;23642". Seperated by a ";" character.
So far I've gotten this:
public class SorteraOrter{
public static void main(String[] args)throws IOException{
// scans file orter
File stad = new File("C:\\Users\\Johan\\Desktop\\orter.txt");
Scanner n = new Scanner(stad);
ArrayList<Object> city = new ArrayList();
while(n.hasNext()){
String ln = n.nextLine();
String[] arr = ln.split(";");
Ort ort = new Ort(arr[0],Integer.valueOf(arr[1]));
city.add(ort);
}
System.out.println(city.toString());
}
}
For sorting i have declared some methods and made a compareTo method to use with sort.
:
package soter_orter;
public class Ort implements Comparable<Ort> {
// fields
private int postnr = 0;
private String ort = "";
// constructor
public Ort(String s, int p){s = ort; p = postnr;}
// method names
public int postnr() {
return postnr;
}
public String ort() {
return ort;
}
public int compareTo(Ort o){
return o.postnr - postnr;
}
public String toString(){
return ort + " " + postnr;
}
}
So to do this first i have to succeed in adding these Strings and Integers into my ArrayList. I also need to have them connected in some way since the number and the text file belong to eachother.
My current problem is the output im getting after trying to move the file-input to the ArrayList -
[ 0, 0, 0, 0, 0, 0, 0]
I've come a bit further and added the elemets of my ArrayList to an Object Array. I am able to sort this but unable to view it using my toString method.
Object[] arr = new Object[city.size()];
for (int i = 0; i<city.size(); i++){
arr[i] = city.get(i);
}
Arrays.sort(arr);
for (Ort o : arr){
}
I am unable to print this in the for loop. I get the message: "Type mismatch: cannot convert from element type Object to Ort"
So, so far I am unable to print the ArrayList neither the Object Array.
your constructor in Ort class should be
public Ort(String s, int p){ort=s; postnr=p;}
Your constructor ir wrong.
replace
public Ort(String s, int p){s = ort; p = postnr;}
for
public Ort(String s, int p){ort = s; postnr = p;}
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.