I hava a question about array initialization in java.
The code is as below:
public class Sentence {
int size;
int[] words=new int[size];
public Sentence(int size) {
this.size=size;
}
public static void main(String[] args) {
Sentence falseOne = new Sentence(6);
falseOne.words[0] = new int[6];
}
}
The problem shows: Type provided "int[]", but required "int"
Could anyone tell me where is wrong?
The field words for an object of class Sentence is of type int[] i.e. it is an array whose elements must be of integer type. In the second line within the main function, you are trying to initialize the first element of the words array with an integer array, instead of an integer.
Also, you should also create the array itself within the constructor.
The code should look like this:
public class Sentence {
int size;
int[] words;
public Sentence(int size) {
this.size = size;
this.words = new int[size];
}
public static void main(String[] args) {
Sentence falseOne = new Sentence(6);
falseOne.words[0] = 7; //just picked an arbitrary integer to demonstrate what should be initialized
}
}
Related
I'm new to this site so let me know if this sort of question is welcome here.
I'm currently coding a class in java to store a set of integers in an array stored in an object and i'm having trouble reassigning the array variable store in the objects created. its not compiling as is(I'm a new programmer so i'm pretty sure i'm missing something simple here).
public class Set
{
// constructor
Set()
{
int array[] = {};
}
//adds a value to the set
public static void addValue(int [] array, int element)
{
int i;
int n = array.length;
int newArray[] = new int[n + 1];
//copy original array into new array
for (i = 0; i < n; i++)
newArray[i] = array[i];
//add element to the new array
newArray[n] = element;
//the issue is this line here
this.array = newArray;
}
//print the set
public static void printSet(int [] array)
{
int i;
int n = array.length;
System.out.print("{");
for (i = 0; i < n; i++)
{
System.out.print(array[i]);
}
System.out.println("}");
}
}
edit - error message returned is:
Set.java:23: error: non-static variable this cannot be referenced from a static context
this.array = newArray;
^
Set.java:23: error: cannot find symbol
this.array = newArray;
^
symbol: variable array
2 errors
First of all, you forgot to put the array inside the class, you can handle it privately like this before the constructor in this way:
private int [] array;
Constructor is used to initialize objects. If you create an empty constructor, you won't be able to pass it any parameters to initialize the array. You can create the constructor this way:
Set (int [] array){
this.array = array;
}
At line you indicated the compiler tells you that you cannot handle the method statically because you are working on an instance method. The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method. So, you have to remove the static handling from the method. Also, since you want to return the array with the entered value, your method cannot be of type void. So, your method will be:
//adds a value to the set
public int [] addValue(int [] array, int element){
int newArray[] = new int[array.length + 1];
for (int i = 0; i < array.length; i++)
newArray[i] = array[i];
newArray[array.length] = element;
return newArray;
}
Since the length of the array was already available (array.length), it was not necessary to create the variable n, so I took the liberty of making some improvements to your code, to make it less redundant. Similarly, the method you created to print the array would be:
//print the set
public void printSet(int [] array){
System.out.print("{ ");
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println("} ");
}
However, once you've made these small changes your code should work fine. You can try to create a testing class like this, to check that everything works right:
public class TestingSet {
public static void main (String [] args){
//creating array
int [] array = {1, 2, 3};
//creating an instance of Set class
Set s = new Set(array);
//printing array
s.printSet(array);
//printing array with new value
s.printSet(s.addValue(array,4));
}
}
It looks like you are trying to access array however it cannot be seen by the addValue method.
You need to declare the array outside of the Set constructor:
public class Set
{
//New location to declear the array
int array[];
// constructor
Set()
{
//We can still initialize the array here
array[] = {};
}
Secondly, the reason for the error is that you cannot use this inside a static method. Static methods are not tied to an object (The Set class) so you need removed static from the method:
//static removed from this line
public void addValue(int [] array, int element)
{
Then to use the method you would create the Set object and use addValue something like this:
Set exampleSet = new Set();
exampleSet.addValue(yourArray, index);
The other option is to make the array a static value (it will no longer be specific to the object but shared with everything), but this is proberbly not the behaviour you want:
public class Set
{
//New location to declear the array
static int array[];
//And to access the object you could use
Set.array = newArray;
This question already has answers here:
Are arrays passed by value or passed by reference in Java? [duplicate]
(7 answers)
Closed 3 years ago.
The result you are suppose to get is 0, but I don't understand why? The array is changed when its passed through other method.
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
return arr[0];
}
public static int[] function2 (int [] arr) {
arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}
I expected 4 from the printed answer.
You are creating a completely new array in function2. That's why by default it is storing 0 at every index. When you are returning, the new array is returning only. For every index it will print 0 only.
Why are you creating new array in function 2? If you have to print 4 then simply pass the existing array only and print the arr[3].
Here is the code :-
public class Tester {
public static int function1 (int [] arr) {
arr= function2(arr);
//return arr[0];
return arr[3];
}
public static int[] function2 (int [] arr) {
//arr = new int[4];
return arr;
}
public static void main(String[] args) {
int arr[] = {1,2,3,4};
System.out.print(Tester.function1(arr));
}
}
I am practising dynamic coding so I want to create a list for class. I hereby Initialized a list for class and want to create an array with different length for each iteration in list. But It doesnt initialize it like I expected instead its length says 0.
import java.io.*;
import java.util.*;
class testcase
{
int N;
int play []= new int [N];
int villain[]=new int [N];
String status;
}
public class Main {
public static void main(String args[] ) throws Exception {
List<testcase> caseno=new ArrayList<testcase>();
Scanner sc=new Scanner(System.in);
int n1=1;
//int n1=sc.nextInt();
int i,j;
testcase t;
for(i=0;i<n1;i++)
{
int n=6;
//int n=sc.nextInt();
t=new testcase();
t.N=n;
System.out.println(t.N+" "+t.play.length);
}
}
}
The array length should print 6 instead it shows 0
You have to create a parametrized constructor in which you'll pass the value of N and then initilaze the arrays. Like
class testcase // Name should be in PASCAL
{
int N;
int [] play;
int [] villain;
String status;
public testcase (int n) { // Constructor
this.N=n;
play = new int [N];
villain=new int [N];
}
}
And in the main methos you create object like this
int n= . . .;//taking input from user
testcase t=new testcase(n);
You need to write a constructor which does these assignment based on the value passed.
// Implement your constructor something like this
public Testcase(int value) {
this.N = value;
play = new int [value];
// Some more assignment based on the need
}
And after that, you need to create the object instance
int N = 6;
Testcase newTestcase = Testcase(N);
NOTE: Clase name should always start with a capital letter.
Try declaring these variable like N, status, play e.t.c as private. After that assign and access them using getter() and setter().
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];
}
// ...
}
Create a class WrapperDemo that includes a function convert2ObjAndStore that convertsan integer into an Integer object and stores the Integer object in a Vector object namedintVector.Store ānā such converted objects in intVector.Iterate the vector and receive theobject as an integer value and display it.Also include a function that swaps one Integerobject with the other and display the swapped value in the calling routine (main function enclosed in a class named WrapperMain)
I tried this but i am getting an error for converting the interger to Integer object
import java.util.*;
class WrapperDemo {
static void Convert(Integer []ob,int n) {
Vector<Integer> store=new Vector<Integer>();
for(int i=0;i<n;i++) {
store.add(ob[i]);
System.out.println(store.get(i));
}
}
}
class WrapperMain {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
int[] x=new int [20];
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n);
}
}
}
As far as I can see your error is that you declare x as int[] but pass it to a method that is expecting Integer[]. This will not be autoboxed!
EDIT : To make it clearer ...
class WrapperDemo {
static void Convert(Integer []ob,int n) { // <-- type Integer[]
versus
int[] x=new int [20]; // <-- type int[] which is NOT equal to Integer[]
// and will NOT be autoboxed to Integer[]
// ...
WrapperDemo.Convert(x,n); // You give type int[] to a method that is expecting Integer[]
And as a side-note:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n); // <- You call the convertion in each iteration.
}
You call the convertion in each iteration of the filling loop. So most of the entries will be null. You might want to change that to:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
}
WrapperDemo.Convert(x,n);