Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Program runs than terminates, why? Kind of confused because there are no syntax errors, Please explain why it terminates, thank you. fairly new to java and using arrays.
import java.text.*;
import java.util.*;
public class randomizer {
public void randomizer() throws InterruptedException
{
randomizer r = new randomizer();
int[] numbers = {3,7,2,62,1,53,16,563,12,13,75};
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
int minute = rightNow.get(Calendar.MINUTE);
int seconds = rightNow.get(Calendar.SECOND);
int[] numbers2 = {10,32,61,2,5};
int[] date = {hour,minute,seconds};
int RandomNumber = (r.getRandom(date) * r.getRandom(numbers)) + r.getRandom(numbers2);
while(true) // just for test case purposes
{
Thread.sleep(1000);
System.out.println(RandomNumber);
}
}
public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
public static void main(String[] args) {
randomizer r = new randomizer();
}
}
Your randomizer class has no constructor defined, so constructing it in your void main method does nothing.
Of note, your class does have a void randomizer() method defined - this is probably a bug. Note, classes should be Pascal case (Randomizer and methods should be camel case (randomizer).
the app is terminated and doing nothing because of this:
public static void main(String[] args) {
randomizer r = new randomizer();
}
here you create an object of the class randomizer so far so good..
but in the code you have this:
public void randomizer() throws InterruptedException
{....
....
}
and that is not a constructor, that is a method... so as long as you dont call it is not executed...
you need to either change that to a constructor by doing
randomizer() throws InterruptedException
{....
....
}
or calling it in the main method
public static void main(String[] args) {
randomizer r = new randomizer();
r.randomizer();
}
after that modify the method because in ther you have
public void randomizer() throws InterruptedException
{
randomizer r = new randomizer(); //this will recursive create objects until overflows....
int[] numbers = {3,7,2,62,1,53,16,563,12,13,75};
Calendar rightN
You ve created a randomizer object but didnt actually do anything else. The method you implement (randomizer()) is not constructor so you need to invoke it. So inside your main method you need to do those 2 things right now:
randomizer r = new randomizer();
r.randomizer();
in order for your logic inside class to start.
PS1 read the naming conventions in java
PS2 it looks like you want to implement a constructor. if your method 'public void randomizer() ' was supposed to be one then remove the keyword (returning type) 'void' and when you use the 'randomizer r = new randomizer();' inside main, then your logic will execute..
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
The code presented should count the objects created.
I expected it to create three objects and a count of 3 to be printed.
This only prints out 1. I think because the object name Number_Objects obj is the same in all three of the methods. How do I change the program so that it returns 3 (creation of three objects)?
public class Number_Objects {
static int count = 0;
Number_Objects() {
count++;
}
public void Number_Objectstest1() {
Number_Objects obj = new Number_Objects();
}
public void Number_Objectstest2() {
Number_Objects obj = new Number_Objects();
}
public void Number_Objectstest3() {
Number_Objects obj = new Number_Objects();
}
public static void main(String[] args) {
System.out.println(count);
}
}
The code you presented does basically nothing but printing text. Especially, it will not output 1, it outputs 0.
This is because you are updating the count variable in the constructor of your class (which is badly named, btw. Please review naming schemes in Java), yet, the constructor is never called, because you create no instances.
To receive the result three, you need to create three instances of the class:
public static void main(String[] args) {
Number_Objects one = new Number_Objects();
System.out.println( Number_Objects.count ); // --> 1
Number_Objects two = new Number_Objects();
System.out.println( Number_Objects.count ); // --> 2
Number_Objects three = new Number_Objects();
System.out.println( Number_Objects.count ); // --> 3
}
Each new will allocate memory for the instance of the class created and call the appropriate constructor, matching the parameters you give.
You are creating an object inside the method. But you are not executing that function which means the object has not been created yet. Call your methods in the main method.
P.S. Java != JavaScript
class NumberObjects {
static int count = 0;
NumberObjects() {
count++;
}
public static void NumberObjectstest1() {
NumberObjects obj = new NumberObjects();
}
public static void NumberObjectstest2() {
NumberObjects obj = new NumberObjects();
}
public static void NumberObjectstest3() {
NumberObjects obj = new NumberObjects();
}
public static void main(String[] args) {
NumberObjectstest1();
NumberObjectstest2();
NumberObjectstest3();
System.out.println(count);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have imported both ArrayList and Integer. In my code I use the symbols in multiple places but I only get an error on one line.
Here are the import statements:
import java.util.ArrayList;
import java.lang.Integer;
Here are the pieces of code that compile properly:
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
private static void addPrime(ArrayList<Integer> primes)
{
int newNumber;
int x;
}
This piece of code return the symbol errors listed above:
while (lastValue < half)
{
addPrime(ArrayList<Integer> primes);
lastValue = primes.get(primes.size()-1);
}
I have done research on the problem but the only answer I can find is that the symbols were not imported properly at the beginning of the program.
A little background if you are not aware of already:
private static void addPrime(ArrayList<Integer> primes)
{
int newNumber;
int x;
}
is the method definition, where we define what the method will do for us. To make it do something for us we call the method passing the arguments, eg. addPrime(argument). Here you got to pass actual argument variable of type which you have defined in method definition.
So addPrime(primes) will work for you.
You don't need to specify the value type when calling a function. So instead of addPrime(ArrayList<Integer> primes); just simply do addPrime(primes);
The addPrime(...) function you have does not do anything in the example you gave.
import java.util.ArrayList;
import java.lang.Integer;
public class test
{
private static ArrayList<Integer> addPrime(ArrayList<Integer> primes, int num)
{
//Seems like you are trying to add primes to the list?
primes.add(num);
return primes;
}
public static void main(String[] args)
{
ArrayList<Integer> primes = new ArrayList<Integer>();
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
//Usage looks like
primes = addPrime(primes, 13);
// This will return 13 as the number 13 is the 5th element
System.out.println(primes.get(4));
}
}
Coded a bit better would be creating an object class so you do not keep passing around an array list
import java.util.ArrayList;
import java.lang.Integer;
public class IntArrList
{
private ArrayList<Integer> primes;
public IntArrList() {
primes = new ArrayList<Integer>();
}
public void addPrime(int num)
{
primes.add(num);
}
public int getPrimeListValue(int index)
{
return primes.get(index);
}
public ArrayList<Integer> getPrimeList()
{
return primes;
}
}
public class test
{
public static void main(String[] args)
{
IntArrList arrL = new IntArrList();
arrL.addPrime(2);
arrL.addPrime(3);
arrL.addPrime(5);
arrL.addPrime(7);
// This will return 7 as the number 7 is the 4th element
System.out.println(arrL.getPrimeListValue(3));
}
}
I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}
package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static method in java
Ok, so I'm working on a project for a class I'm taking.. simple music library. Now I'm having some issues, the main issue is I'm getting "non-static method cannot be referenced from a static context"
Here is a function I have
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
Now thats in a class file called LibraryFunctions. So I can access it with LibraryFunctions.addSong();
Now I'm trying to run this in my main java file and its giving me the error, I know why the error is happening, but what do I do about it? If I make addSong() a static function then it throws errors at me with the Song temp = new Song() being static. Kind of ironic.
Much help is appreciated on this!
Follow these simple rules:
If it's a static method call it with ClassName.methodName()
If it's a non-static method call it with classInstance.methodName()
If you want to call it as LibraryFunctions.addSong(), it needs to have the signature public static void addSong().
More info:
Only static methods can be called without instantiating a class first.
You can also try:
LibraryFunctions lf = new LibraryFunctions();
lf.addSong();
Well you have two options really:
Change addSong() to static and reference Song through it's static members if possible.
Create a new instance of LibraryFunctions and then use the non-static method addSong()
I take that your class Song is a non static nested class? e.g.
class LibraryFunctions {
class Song {
// ...
}
}
If so you can either make it a static nested class, or lift the Song class into a separate class.
In terms of structure, may I suggest that the LibraryFunctions class file be turned into a MusicLibrary class? That way, in your main application code, you can instantiate a MusicLibrary every time the code runs. It will also make it easier to separate static functions and instance functions, which would probably solve your issue right now.
public class MusicManager {
public static void main(String[] args) {
MusicLibrary myMusic = new MusicLibrary();
myMusic.addSong();
// other stuff
}
}
Then MusicLibrary:
public class MusicLibrary {
public MusicLibrary() {
}
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
}
And finally, I would put the class Song outside of MusicLibrary so that you can reuse it later.
Another added benefit of this is that you can make MusicLibrary implement Serializable and save the library to a file. Plus you could place an array of MusicLibraries inside of a MusicLibrary and have playlists. All kinds of options.