I want to have an array which randomly gives me one of the given answers. But Java says "array[hallo] not possible; you use String but int is expected"
Is there a possibility to solve this problem or am I all wrong?
import java.util.Random;
public class ZufallsAntworten
{
private Random ran;
public ZufallsAntworten()
{
ran = new Random();
}
public int richtigeAntwort()
{
String[]array = new String[100];
array[0]="a";
array[1]="b";
array[2]="c";
array[3]="d";
int hallo = ran.nextInt(array.length+1);
return array[hallo];
}
}
Your method richtigeAntwort() returns an int, but you are returning a String, since your array is an array of Strings. This line:
return array[hallo];
will fetches one of the Strings from your array at that index and return it.
I cannot read the name of your method so I cannot advice you much beyond simply changing the return type of the richtigeAntwort() method to String.
Related
I know how to create a method,
which takes an array
public void x(int [] arr){}
but I do not know how to set a given length to that array.
If you are trying to make a method that accepts an array, you can structure it like this:
public void x (int[] arr) {
// Code
}
If you want to restrict the length of array the method can accept, you could do something similar to this:
public void x (int[] arr) {
//Check to see if arr is a satisfactory length
if (arr.length > 10) {
//Throw an exception, break, print to the console etc...
}
}
There are some areas where I can't make this explanation as detailed because I don't know what language you're programming in.
public class Ship
{
public static int[] size = {3, 2, 3, 5, 4};
public static String[] shipNames = {"Destroyer", "Cruiser", "Submarine",
"Aircraft Carrier", "Battleship"};
public Ship(String shipNames[], int size[])
{
this.shipNames[] = shipNames[];
this.size[] = size[];
}
}
Okay so basically what I'm trying to do is make it so my constructor repeats two static variables...
In another class, I'm calling this object Ship...
newShip = new Ship(Ship.shipNames[i],Ship.size[i]);
But when it sends I get these error messages:
Error: illegal start of expression
Error: '.class' expected
Error: illegal start of expression
Error: '.class' expected
Working with arrays is quite confusing for a beginner such as myself. :(
There are many things wrong here.
When you write something like String shipNames[], the [] is not part of the variable name. It is part of the variable type. So when you are just using the variable, you are not supposed to write them.
You declared the constructor to accept arrays, but you are trying to pass single values to it. Which do you actually want to happen?
When you refer to this.shipNames, presumably you mean to set some field of the object you're constructing. But you have not defined such a field. You already have a thing named shipNames in the class, but it's static - it's part of the class, not the instances.
You have several problems with your code.
First is that your are passing the constructor a string and an int, not an array of strings or array of ints here:
newShip = new Ship(Ship.shipNames[i],Ship.size[i]);
Secondly, you need to receive a string and an int in the constructor, as follows:
public String shipName;
public int size;
public Ship(String shipName, int size)
{
this.shipName = shipName;
this.size = size;
}
There might be other syntax and semantic errors too, but those seem to be the most obvious ones to me.
I'm wrote this code a long time ago and thought I understood it at that time but now I'm trying to wrap my head around how it works...
// Main.as
package {
public class Main {
public function Main() {
var fruit:Array = [];
UpdateClass.update(fruit);
trace(fruit); // Traces out the string pushed into it? How??? I think the data would've got lost...
}
}
}
// UpdateClass.as
package {
public class UpdateClass {
public static function update(array:Array):void {
array.push("haha, this is not a fruit!");
}
}
}
I just don't understand how the UpdateClass manages to update Main's fruit array? I'm thinking the data would get lost because it is not returning the new array?... When I try this with Strings and Numbers the data does get lost like expected.
I don't know what I was on when I wrote this but I would like to try and understand the logic behind this.
Thank you.
String and Number are "primitive" data types in AS3, while Array and other objects like MovieClip are "complex" or "reference" data types.
When you pass a primitive, its value is copied, so modifying that doesn't affect the original. When you pass a complex object, it's actually a reference to the object's address in memory, so your function is modifying the original object.
I'm assuming something like following when you say that the value was lost with String and Number:
// UpdateClass.as
package {
public class UpdateClass {
public static function update(num:Number):void {
num = 1;
}
}
}
The reason it was lost was because you got a reference to the original object as num. But the function update changed that reference to another Number object which contained the value '1'. This would be true for array too, if you assign another array to the passed reference like:
// UpdateClass.as
package {
public class UpdateClass {
public static function update(array:Array):void {
array = new Array();
array.push("haha, this is not a fruit!");
}
}
}
But, since you are just calling a method on the passed reference (push), 'array' still refers to the original Array and updates it.
EDIT:
I am trying to add elements read from a txt document line by line into an array list then convert that array list into an array. Although I am getting errors with my code. It doesnt like the int[] a = lines.toArray(new int[lines.size()]);.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
List<Integer> lines = new ArrayList<Integer>();
File file = new File("10_Random.txt");
try {
Scanner sc = new Scanner(file);
//int line = null;
while (sc.hasNextLine()) {
int i = sc.nextInt();
lines.add(i);
//System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
int[] a = lines.toArray(new int[lines.size()]);
}
}
Edit2: Thanks chaitanya10! all fixed.
int line= null; is wrong,
"null is a special literal that can be of any object reference type".you cant assign null to primitive variables in java like (int, byte, float...). null can only be assigned to objects . remember thatnullis the default vale forobjects` when you don't initialize them.
if you wanna access int as an object use Integer.
Integer line= null;//nowthis would compile
and to convert an list onto array do this.
List.toArray(T[] t) method returns an Object.
do like below.
Integer[] array = lines.toArray(new Integer[lines.size()])
and also your List accepts int[] array and you are tryig to add an int into the list .
change your List declaration like this
List<Integer> lines = new ArrayLis<Integer>();
To print the elements in the array you have to iterate over it
for(int i=0; i<a.length;i++){
system.out.println(a[i])
}
you seem to be a beginner in java. strongly recommend you tohereread about java basic
Two main problems.
You can't assign null to an int. null is a pointer value, and ints in Java are always handled by value, not by reference. Objects can be null, primitive values like int and double can't.
The type declaration of your ArrayList is wrong. The way you're assigning it, each element of the list is expected to be an array of ints. I don't think that's really what you want - the each element is just one int value, so that the list as a whole is analogous to an array.
The second bullet is the reason behind your second and third errors, which I think you'd probably see if you read the error messages all the way through (it's a TypeMismatch error, right?). With your list parameterized to int[], the add method is expecting everything that's added to be of the type int[]. But line is only an int. Similarly, the toArray() method returns an array of whatever type the list is parameterized with. Since you have a list of arrays, toArray() will return an array of arrays. Its return type in this case is int[][], which can't be assigned to int[] a because the type doesn't match.
This should get your code to compile, but it doesn't get into the other issues of validation and whatnot that you have to worry about any time you have input... but for now I'm just going to assume that you've already vetted the input file.
You can use IntStream:
int[] arr = {15, 13, 7, 4, 1, 10, 0, 7, 7, 12, 15};
List<Integer> arrayList = IntStream.of(arr).boxed().collect(Collectors.toList());
System.out.println(arrayList);
Maybe the solution is very simple. It must be, but maybe I am overlooking something
I have:
public class Object {
public int pos_x;
public int pos_y;
}
Object testObject[] = new object[10]
and then somewhere in a function
testObject[1].pos_x = 1;
It force closes my app.. how? and why? What can be the cause of this.
Furthermore. Ideally I would need something like this
testObject[].add_new_object();
testobject[].remove_item(3);
can this be done?
Thank you for helping
You have allocated an array that can hold 10 objects.
You also need to allocate the objects.
I'm not sure about the language you are using - if C# you cannot use 'Object' as the class name.
First creating a custom object (the 'object' data type):
public class MyObject {
public int pos_x;
public int pos_y;
}
...fair enough, a very basic class that holds coordinates. Next you want to create an array of MyObject. To do that, you declare your array type as MyObject[] and provide an optional size:
MyObject[] myObjArray = new MyObject[10]; // this gives a zero-based array of 10 elements, from 0-9
Now, you have the task of filling the array. The most common method would be to use a counter variable that counts from 0 to 9, the same elements we have in our array:
for (int i=0; i<=9; i++)
{
myObjArray[i] = new MyObject();
// you can also assign the variables' values here
myObjArray[i].pos_x = GetNextXVal(); // get the X value from somewhere
myObjArray[i].pos_y = GetNextYVal(); // get the y value from somewhere
}
Depending on your language, I'm sure we can point you to some good tutorials, books, or other references to help you get started.
Happy coding!