I am building a method which takes as argument, an array of decimal numbers, and a decimal threshold. The method should output all numbers from the list that are greater than the threshold.
My plan is to execute a for loop and examine each number in the array, and if that number (i) is greater than the threshold (x), to append to my result list. My problem is that I'm unable to add/append to the result list.
I have System.out.println("Nothing here"); just to help me see if it's actually going through the for loop or not, but my IDE is saying that calling list.add(a[i]); is wrong. I am a beginning programmer and not sure on how to fix this. Here is my code:
public class a10 {
public static void main(String[] args) {
double a[] = {42, 956, 3,4};
threshold(a, 2);
}
public static void threshold(double[] a, double x){
double list[] = {};
for (double i:a){
if (i<22){
list.add(a[i]);
}else{
System.out.println("Nothing here");
}
}
}
Your list is actually an array (double[]), which is NOT an object with the method add. You should treat it as a regular array (which in your case between, you have initialized to be an empty array, which means you can't set any elements in it).
What you should do is use an actual implementation of Lis instead (e.g an ArrayList) and then you can actually use the add method:
List<Double> result = new ArrayList<Double>();
for (double i:a){
if (i>x){
list.add(a[i]);
}else{
System.out.println("Nothing here");
}
}
Notice also that you had the number '22' hard coded (you should use x)
There's no method add for arrays in Java. You should declare list as:
List<Double> list = new ArrayList<Double>(); //or some other type of list
Related
I am writing a program piece by piece. I continue to receive compile errors. Can you look at my code to determine my issue?
So here, I am saying that array can store 1000 elements of the double type. Now I want to pass the array to my main method and place 1000 random numbers into the array. So I will create a new method.
public class Practice{
public static void main(String[] args){
double[]array=new double[1000];
}
}
Here, I have created a new method named passArray. I am trying to say that for each array element at its respective index (based on the count) assign a random integer until we reach 1000.
public static void passArray(double[]x){
for(int counter=0; counter<x.length; counter++){
x[counter]=(int)(Math.random()*1000);
}
Okay, so now I want to print my results to determine if my code does what I want it to do. In my main method, I will use an enhanced for loop:
for(double k: array)
System.out.println(k);
}//End of main Method
The problem I continue to encounter is a compile error. However, the output displays 999 values as a double value at random. What in the world am I missing here?
I think you have a typo ( remove the '}' from the for loop )
and you need to pass the array to the method to make it work.
This compiles and runs :
public class Practice{
public static void main(String[] args){
double[]array=new double[1000];
// calling the method
passArray(array);
// print the array
for(double k: array)
System.out.println(k);
//End of main Method
}
public static void passArray(double[]x){
for(int counter=0; counter<x.length; counter++){
// compiles ... but why cast to int if you have double[] ?
x[counter]=(int)(Math.random()*1000);
}
}
}
Not sure about the compile error, but your int to double problem is at the start of your code.
You declared an array of type double:
double[] array = new double[1000];
You're trying to type cast your random values to type int, which the compiler should accept.
x[counter] = (int) (Math.random() * 1000);
However since this is an array of type double, then you're storing the values as doubles. i.e. the values get cast back to double immediately. All that java is really doing is, changing from a double, eg. 567.97, to an int 567, and stroing it as a double again 567.0. Notice that it has now lost all its floating point information from being cast to an int. Or in geekier terms, the mantissa has been set to all 0's.
Either you will have to declare your array as type integer. Or cast back to int every time you access a value.
eg.
int[] array = new int[1000];
public static void passArray(int[] x) {
// code
}
or
System.out.println((int)k);
Edit: Are you getting a compiler error, or warning? There's a big difference. A warning will allow it to run, which your posts suggests is happening, an error will not compile, and thus not run. You may just be getting a warning about the type cast from int to double.
new to Java. Trying to understand the point of declaring my ArrayList as an <Integer>. I still have to cast my .get() result as an int in my methods for it to work, else it still returns an Object. eg: (int) deliv.get(j) int the Sort method's for loop. Is there a way to avoid this or is my code the correct approach?
Problem: Assume the array can change size, hence not just using primitive array. All numbers should be pairs, looking for the unique one missing it's pair value. I sort the array, then cycle through the pairs to look for a mismatch. Thanks.
import java.util.*;
class StolenDrone{
public static void main(String[] args){
ArrayList<Integer> deliv_id = new ArrayList<>();
deliv_id.add(99);
deliv_id.add(13);
deliv_id.add(4);
deliv_id.add(5);
deliv_id.add(8);
deliv_id.add(99);
deliv_id.add(8);
deliv_id.add(5);
deliv_id.add(4);
System.out.println("Array is: " + deliv_id);
sort(deliv_id);
System.out.println("Array is: " + deliv_id);
int unique = findUnique(deliv_id);
System.out.println("Unique ID is: " + unique);
}
//Sort ArrayList into increasing order
static void sort(ArrayList deliv){
int temp;
for(int i = 0; i<deliv.size();i++){
for (int j=0; j<deliv.size()-1;j++){
if((int) deliv.get(j)> (int) deliv.get(j+1)){
temp = (int) deliv.get(j+1);
deliv.set(j+1, deliv.get(j));
deliv.set(j, temp);
}
}
}
}
//check pairs in ArrayList to find unique entry
static int findUnique(ArrayList deliv){
for(int i = 0; i<deliv.size()-1;i+=2){
if(deliv.get(i) == null){
return -1; //no unique
}
if((int) deliv.get(i) != (int) deliv.get(i+1)){
return (int) deliv.get(i);
}
}
return -1;
}
}
When you type parameterize ArrayList<Integer> the compiler knows that everything inside the ArrayList is of type Integer and will only allow you to add Integers to the list, and thus get() returns Integer. Without parameterizing the compiler will allow you to add any Object to the ArrayList, and thus calling get() will return an Object and requiring the cast to int.
To remove the need for casts you need to change parameters with type ArrayList to ArrayList<Integer> in the function declaration.
static void sort(ArrayList deliv)
Your method signature requests an untyped ArrayList.
The compiler cannot know what will be inside the ArrayList so it requires you to cast the result.
Change it to this:
static void sort(ArrayList<Integer> deliv)
Now the compiler knows it is an ArrayList of Integers.
So you wont need to add the cast to get()
In Java Integet is wrapper-class of int. You cannot set int as a type of ArrayList to work, but you can put there int type and it will be automatticly casted to Integer. To meke work it good you should do like this :
static void sort(ArrayList deliv){
int temp;
for(int i = 0; i<deliv.size();i++){
for (int j=0; j<deliv.size()-1;j++){
if(deliv.get(j)> deliv.get(j+1)){ // You should not cast, Integer is Comparable
temp = deliv.get(j+1).intValue();//Changes here
deliv.set(j+1, deliv.get(j).intValue());//And here
deliv.set(j, temp);
}
}
}
}
Good luck
public class Whatever {
static double d;
static char c;
static String[] s;
static char[] b;
static double[] dd;
static Whatever w;
static Whatever[] ww;
public static void main(String[] args) {
System.out.println(Whatever.d); //prints out 0.0
System.out.println("hi"+Whatever.c+"hi"); //prints out hi hi
System.out.println(s); //prints out null
System.out.println(b); //null pointer exception!
System.out.println(Whatever.dd);
System.out.println(Whatever.w);
System.out.println(Whatever.ww);
}
}
Why do I get a null pointer exception?
Please explain in terms of memory if you can, however I have a basic understanding of memory so don't get too in depth either.
Okay, now that you've posted your full code its easier to help! This is normally what happens when you invoke PrintStream.println with a primitive array:
String s = String.valueOf(x);
Which eventually does this:
return (obj == null) ? "null" : obj.toString();
As you can see, the possibility of the supplied object being null is explicitly handled. However, there is a specific overload on the PrintStream class, just for char arrays. Here is a rough trace of the logic:
write(cbuf, 0, cbuf.length);
Where cbuf is the given char array. As you can see, it tries to reference the character arrays length, which will blow up with an NPE if the array is not initialized. It's an odd and unfortunate inconsistency in the implementation.
So now you understand why the NPE is occurring - to fix it simply initialize the char array before trying to print it out.
There's a few problems here:
1. You're not allocating any space for `int x`
2. If you want to print the contents of `x`, it should be `x.toString()`
3. What did you expect the output to be from your sample code?
I'm guessing #3 isn't what you're actually working with, I would suggest you show your real code to get a real answer :)
Hopefully this can clear it up a bit for you.
$ cat Whatever.java
public class Whatever {
static final int MAX = 5;
int[] x = new int[MAX]; // allocate array to sizeof '5'
public Whatever() {
// do stuff
}
public void addStuff() {
for(int i=0; i<MAX; i++)
x[i] = i + 2;
}
public void printX() {
for(int i=0; i<MAX; i++)
System.out.println(i + ": " + x[i]);
}
public static void main(String[] args){
Whatever w = new Whatever(); // new instance of 'Whatever'
w.addStuff(); // add some ints to the array
w.printX(); // print out the array
// print the Array 'x'
System.out.println("Array: " + w.x);
}
}
$ java Whatever
0: 2
1: 3
2: 4
3: 5
4: 6
Array: [I#870114c
The problem is basically rooted in how PrintStream.println(...) is implemented. Except for char[], a primitive array is treated as a java.lang.Object. So the println overload used is println(Object). Underneath, printing an object involves calling the object's toString(). Hence the NPE.
If you want to be defensive of nulls, you should consider using String.valueOf(Object).
I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.
I am trying to test whether my method to find the number of odd numbers in an array works with a System.out.println() call. I know there are no issues with the array itself, as I've printed it successfully with the toString() call. Here is my method:
public static int ODD(int[] oddnumbers)
{
int countOdds = 0;
for(int i = 0; i < oddnumbers.length; i++)
{
if(oddnumbers[i] % 2 == 1) // check if it's odd
countOdds++; // keep counting
}
return countOdds;
}
And then earlier on in the main method, I called ODD and tested it with System.out.println:
public static void main(String args[])
{
ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}
Basically the question I have is, how do I get the return countOdds into a variable that I can pass to be printed in System.out.println() in the main method?
Either use a temporary variable to store the returned value and print that, or include the method call in the print statement. For more information, see Returning a Value from a Method.
Just do :
System.out.println("And here are how many odd numbers there are in that array: " + ODD(randomThirty));
Use int countOdds = ODD(randomThirty); in your main method.
Your countOdds variable in your function is local to that function. Variables defined in functions in java are local not global.
You just need to assign the result of the ODD method call to a variable:
public static void main(String args[])
{
int result = ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + result);
}
You will need to store the return result of your call to ODD in a variable, like so:
public static void main(String args[])
{
int countOdds = ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}
Just save the result like any other variable:
int countOdds = ODD(randomThirty);
public static void main(String args[]) {
int countOdds = ODD(randomThirty);
...
}
To get the returned value you have to pass the argument into the method and call it.
int ans = ODD(randomThirty);
System.out.println(ans);
This is really all you need to do. You can call methods while passing an argument and assign a variable to the returned answer.