I'm new to programming and java, and I'm trying to write a simple bubble sorting algorithm. I might be in a bit over my head; I'm not too far along in Oracle's java tutorials. The trouble I'm having now isn't with the bubble sorting itself, but in creating the array and printing it before it is sorted.
Here is what I have so far:
public class BubbleSort {
public BubbleSort(int size) {
// creates array
int[] items = new int[size];
}
public void fillArray(int[] a) {
// fill array with random ints
for (int i=0; i<(a.length-1); i++) {
a[i] = java.util.Random.nextInt(50);
}
}
public void printArray(int[] a) {
for (int i=0; i<a.length; i++) {
System.out.print(a[i] + " ");
}
}
public void BubbleSortAlgorithm() {
// bubble sorting algorithm goes here
}
public static void main(String[] args) {
BubbleSort bubbleSort = new BubbleSort(20);
bubbleSort.fillArray(items);
bubbleSort.printArray(items);
// bubbleSort.BubbleSortAlgorithm(items);
// bubbleSort.printArray(items);
}
}
I'm getting 3 compiler errors:
non-static method nextInt(int) cannot be referenced from a static context
Is this because it is called in the main method? How do I get around that?
2.,3. the compiler can't find the symbol, items. Items is an array of ints that is created in the constructor for the class. Do I need to declare it in the main method?
I have a feeling that my class structure is completely off. Again, I'm very new. I'm also new to stackoverflow, so I'm also sorry if this question isn't presented well.
You call:
java.util.Random.nextInt(50);
It's preferred to import classes you're going to use. That would put this block at the top of the file:
import java.util.Random;
And change the existing code to:
Random.nextInt(50);
That fixes the style problem, but you're still going to get the same compiler error.
Static methods are things that belong to a class; they don't need you to create (instantiate) an object of that class before using them. Instead of every instantiation of a class having that method, all instantiated instances of the class share the same static methods and variables.
Specifically, .nextInt() in the Random class is not a static; it's a normal method. So it needs an instantiated Random to work on. Which means you should try:
Random random = new Random();
random.nextInt(50);
After you've instantiated a Random, you can then keep calling nextInt() on it, as many times as you'd like.
One example of static methods that are commonly used are in the Math class.
Math.min(10, 5);
Math.max(100, 100000);
And so on.
The reason Random needs to be instantiated is that it has state. It's not fully random, but pseudo-random, in that it needs a number to start with. If you don't give it a number, it takes the current time. Two Java Random objects initialized at exactly the same moment... will produce the same series of "random" numbers.
This is actually useful; you can give them Random object the number to start with, and you can use this behavior for testing purposes.
Random random = new Random(1);
That's seeding it with the number 1. Which means it'll produce the same random numbers for nextInt() every time you run your code. If you don't give it any number as a seed, it's doing this, instead:
Random random = new Random(System.currentTimeMillis());
But yeah; the problem is that Random.nextInt isn't a static method.
First thing is
NextInt method of non static
So you have to use instance of random class to use it
Second one
Item is local variable so you have to must declare it before use it
Related
I have a great doubt as to what this action is called and how it is administered in memory.
Inside the main() method I make these sentences or instructions.
public static void main(String[] args) {
int i = 0;
int j = new Random().nextInt(100); // As it is called this way of acting or as it is called.
}
I have clear that what it does is directly invoke the Random class constructor method, invoke the nextInt method and generate a random number that is stored inside the int j variable but I don't know how to define this type of action and I don't know if it is correct to do this kind of instructions.
I'm curious to know what this type of action is called.
Thank you for your attention.
P.D : Sorry .. I'm learning
int j = new Random().nextInt(100);
is almost the same as
Random r = new Random();
int j = r.nextInt(100);
i.e. both create an instance (object) of the Random class, and then call a method of that instance.
The difference is that in the first case, you don't keep a reference to the created instance, so you can't access that instance again, and since no reference to that instance exists, it can be immediately garbage collected.
As Andy suggested, you can look at it as if you created an instance of the Random class and assigned it to a variable, called the nextInt() method, and then exited the scope in which that variable was declared:
int j;
{
Random r = new Random();
j = r.nextInt(100);
}
// at this point you have no access to the Random instance
One important note: this code is a bit shorter, and it's OK if you will not need to call nextInt() again. If you will, you better store the instance on Random class in a variable because the process of creating multiple Random objects for multiple int values is TOO heavy.
Well technically there is an instance of the class, since you see the keyword new.
What you see here is called method chaining.
You first call the constructor with new Random() and then chain the nextInt() method to it.
if you are curious how can you call a method without an instance of a class, the simple answer is you need a static class :) a good reference on static classes
But a simple example would be the Math class in java, with it you can do this:
double floor = Math.floor(7.343);
notice how you dont use "new" when invoking Math
For some background, I'm currently on chapter 8 in my book, we finished talking about arraylists, arrays, if statements, loops etc. Now this part of the book talks about call by reference,value and some other pretty neat things that seem odd to me at first.I've read What situation to use static and some other SO questions, and learned quite a bit as well.
Consider the following example my book gave (among many examples)
There is another reason why static methods are sometimes necessary. If
a method manipulates a class that you do not own, you cannot add it to
that class. Consider a method that computes the area of a rectangle.
The Rectangle class in the standard library has no such feature, and
we cannot modify that class. A static method solves this problem:
public class Geometry
{
public static double area(Rectangle rect)
{
return rect.getWidth() * rect.getHeight();
}
// More geometry methods can be added here.
}
Now we can tell you why the main method is static. When the program
starts, there aren’t any objects. Therefore, the first method in the
program must be a static method.
Ok, thats pretty cool, up until now I've just been really blindly putting public in front of all my methods, so this is great to know. But the review small problem on the next page caught my attention
The following method computes the average of an array list of numbers:
public static double average(ArrayList<Double> values)
Why must it be a static method?
Here I was like wait a sec. I'm pretty sure I did this without using static before. So I tried doing this again and pretty easily came up with the following
import java.util.ArrayList;
class ArrList
{
private double sum;
public ArrList()
{
sum = 0;
}
public double average(ArrayList <Double> values)
{
for(int i = 0; i < values.size() ; i++)
{
sum+=values.get(i);
}
return sum / values.size();
}
}
public class Average
{
public static void main(String [] args)
{
ArrList arrListObj = new ArrList();
ArrayList<Double> testArrList = new ArrayList<Double>();
testArrList.add(10.0);
testArrList.add(50.0);
testArrList.add(20.0);
testArrList.add(20.0);
System.out.println(arrListObj.average(testArrList));
}
}
TLDR
Why does my book say that public static double average(ArrayList<Double> values) needs to be static?
ATTEMPT AT USING STATIC
public class Average
{
public static void main(String [] args)
{
ArrayList<Double> testArrList = new ArrayList<Double>();
ArrayList<Double> testArrListTwo = new ArrayList<Double>();
testArrList.add(10.0);
testArrList.add(50.0);
testArrList.add(20.0);
testArrList.add(20.0);
testArrListTwo.add(20.0);
testArrListTwo.add(20.0);
testArrListTwo.add(20.0);
System.out.println(ArrList.average(testArrList));
System.out.println(ArrList.average(testArrListTwo)); // we don't get 20, we get 53.3333!
}
}
It doesn't.
The only method which needs to be static is the initial main() method. Anything and everything else is up to you as the programmer to decide what makes sense in your design.
static has nothing to do with public accessors (as you allude to), and it has nothing to do with the technical operation being performed. It has everything to do with the semantics of the operation and the class which holds it.
An instance (non-static) method exists on a particular instance of a class. Semantically it should perform operations related to that specific instance. A static method exists on a class in general and is more conceptual. It doesn't do anything to a particular instance (unless it's provided an instance of something as a method argument of course).
So you really just need to ask yourself about the semantics of the operation. Should you need new instance of an object to perform an operation? Or should the operation be available without an instance? That depends on the operation, on what the objects represent, etc.
If it is not static, then any other class that wants to use this method must first create an instance of this object.
From some other class:
Average.average(new ArrayList<Double>()); // legal only if static
new Average().average(new ArrayList<Double>()); // necessary if not static
// and only makes sense if Average can be instantiated in the first place
It's legal to make it an instance (i.e. not static) variable, but the method is actually harder to understand. If it is static then whoever reads the code knows it does not use any member variables of the class.
// In the class body
int x = 0; // member variable
public static double average() {
x = x + 1; // illegal
}
The less something can do, the easier to understand what it does do.
Static methods like the area, average are usually utility functions. You don't need any object to use an utility function. For example consider Math.pow you don't need to instantiate any object to use the power function, just use Math.pow(10.0, 2.0) to get (10.0)^2
In short :
Static method means class method, that is no instance of that object is needed to invoke.
whereas your average method is an instance method, you need an object to invoke that method.
I consider myself an intermediate Java programmer having been at it for a year and a half and having some experience in other languages. However I have run into an issue that I feel I need an experts help on.
As I understand it arrays when created by java exist somewhat outside of where they were created i.e. if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
However this brings me to an interesting dilemma. What if one wanted to create a unique array on-demand for an infinite number of sets of user input. i.e. is it possible to have the user enter a string value for use as the array name or have a generic value that then gets a number or letter appended to it. This is more a theoretical issue (there being other ways to accomplish the same thing) but any insight would be greatly appreciated.
i.e. is it possible to have the user enter a string value for use as
the array name or have a generic value that then gets a number or
letter appended to it.
The user should not need to care about your array names. The name of an array should neither be visible to the user, nor should it affect your application in any way.
If you want to allow the user to create collections of elements that he can store under a FriendlyName you could use a (Hash)map for that:
Map<String, Integer[]> userDefinedArrays = new HashMap<>();
userDefinedArrays.put("NameTheUserSelectsForThisArray", new Integer[]{1,2,3});
The "Key" of this map will be the FriendlyName provided by the user - he still does not know, that the actual map is called userDefinedArrays - or even someMapThatHoldsSomeThingsTheUserWantToUse.
The name of a actual variable needs to be set during designtime and is fixed (at least in java)
if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
No! Each Variable declared exists inside it's own scope! You can change the value of an array inside it's scope, and also reuse the same name inside different scopes - it doesn't matter. If you try to redeclare a variable already existing withing the current scope your compiler will warn you! - you simple can not do that.
Example:
class MyApplication{
public static void Main(String[] args){
Integer[] arr1;
Integer[] arr1; //Compiler error!
}
}
but:
class MyApplication{
public static void Main(String[] args){
Integer[] arr1;
Integer[] arr2;
}
}
or
class MyApplication{
public static void Main(String[] args){
foo();
bar();
}
public static void foo(){
Integer[] arr1;
}
public static void bar(){
Integer[] arr1;
}
}
is fine. arr1 just exists within the scope of either foo() or bar().
As I understand it arrays when created by java exist somewhat outside of where they were created i.e. if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
I think maybe you are misunderstanding. This will not happen unless you do it intentionally like yshavit points out in your comments. A member of a class named S in the class Cat, will not point to a member named S in the Dog class. You would have to go out of your way to do this.
In short, this will not happen by accident most of the time if you are instantiating your classes without passing references between them when you do.
What if one wanted to create a unique array on-demand for an infinite number of sets of user input.
You may want to use an ArrayList
ArrayList<String[]> myList = new ArrayList<String[]>();
Or a hashmap
Map<Integer,String[]> myMap = new HashMap<Integer,String[]>();
Which one you use depends on what you are using it for. If you need faster access to arbitrary elements use a map. If you plan to access them iteratively, an ArrayList will work fine.
is it possible to have the user enter a string value for use as the array name or have a generic value that then gets a number or letter appended to it. This is more a theoretical issue (there being other ways to accomplish the same thing) but any insight would be greatly appreciated.
In this case you want to use the hashmap solution, You can choose the key type of a map in java quite easily.
You will want to read this
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
or this, to get started.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Two different class you're talking about is ClassOne & ClassTwo in my example. As you told, there is some kind of conflict while keeping the field name same. I've used arr for both classes. The reason to make MyArray super class is just code reuse. Why I used abstract MyArray class & why I used public static field isn't our matter of discussion. In TestApp, I've used arr of both classes ClassOne & ClassTwo without any problem.is it possible to have the user enter a string value for use as the array nameIMHO it may be possible using Reflection API or Dynamically Typed Language can do it. I'm not much sure about that.
class ClassOne extends MyArray {
public static int[] arr = new int[5];
}
class ClassTwo extends MyArray {
public static int[] arr = new int[5];
}
abstract class MyArray {
public static void setValue(int arr[], int index, int value) {
arr[index] = value;
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
public class TestApp {
public static void main(String[] args) {
ClassOne.setValue(ClassOne.arr, 1, 30);
ClassTwo.setValue(ClassTwo.arr, 1, 50);
ClassOne.printArray(ClassOne.arr);
ClassOne.printArray(ClassTwo.arr);
ClassTwo.printArray(ClassOne.arr);
ClassTwo.printArray(ClassTwo.arr);
}
}
I am an eighth grader with a tight deadline on a java project. I have my GUI all ready to go, except I need to take the two values from the two text fields, and send them to a method in a different class when I press a button. I am having trouble calling the method I need. All important code is below.
Code that is attempting to call the method:
private void GoButtonActionPerformed(java.awt.event.ActionEvent evt) {
String Ntextfield = NumberTextField.getText();
n = Integer.parseInt(Ntextfield);
String Rtextfield = RateTextField.getText();
r = Integer.parseInt(Rtextfield);
//call PermMath class
PermMath doTheMath = new PermMath();
doTheMath.permutations(int n, int r);
}
Method I am trying to call:
class PermMath {
static long factorial(int num){
//other code is here
}
static long permutations(int n, int r){
//code I want to call is here
}
}
The hint for you is the static keyword. Learn what it means and how it works.
Also, you're using the variables n and r even before declaring them.
n = Integer.parseInt(Ntextfield);
should come after you've done something like int n = 0;.
And while invoking a method, you don't declare the parameters. The below is wrong.
doTheMath.permutations(int n, int r);
Instead you do something like
doTheMath.permutations(n, r);
It seems to me you have two mistakes:
You are passing two temporary integers called n and r instead of passing the two integers you modified earlier in your GoButtonActionPerformed function.
The permutations function is static, so there is no need to actually create an instance of the PermMath class.
Changing the function call to this should do it:
PermMath.permutations(n, r);
Note that if PermMath is in another package than the class which defines GoButtonActionPerformed(...) it won't be visible due to the lack of a public access modifier on the methods and even the class.
Btw, in Java method names should start with a lower case latter. While your style is valid code adhering to the convention makes it easier for other Java developers to read your code.
Another thing: you don't use the return value of permutations(...). That might not be intented.
You've declared static methods in your PermMath class - these do not require an instantiation of the class to be called. You simply call them with:
PermMath.permutations(n,r);
Check out the track for this at: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
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.