New object instance not being recognized- Java - java

I am having trouble getting a random generator instance from being recognized as an object and it won't allow for use within another .class file. The base code for the random integer generator is this:
package RandomInstanceGenerator;
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 10 random integers in range 0..99.");
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}
log("Done.");
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
I am trying to have the code below run what is above as a new instance. I have tried several methods that were apparent to me from other learnings, but they have failed me and so I request the knowledge of others for help in understanding. I say that in understanding that i literally copied and pasted the base code from another source that has it run as it's own little .class. Here is the code that tries to create a new instance:
package RandomInstanceGenerator;
import java.util.Random;
class Inst {
public static void main (String args[]) {
RandomInteger rig=new RandomInteger();
rig.main(args);
}
}
I am certain both need editing, hope I can fix this out so it works for me.
List of attempted changes:
1) Tried importing RandomInteger.class. The error given back says it cannot find symbol "Random Integer".
I used the code import RandomInstanceGenerator.RandomInteger;.
2) Working on the next attempt later..

When Java executes a program it looks for a main function; in this case in your second class. That class then instantiates your first class (via new RandomInteger()). You then attempt to call into that first class's main method.
Note, though, that the method is labeled static. Static methods are executable only on the class, not on a specific instantiated object. If you were to use RandomInteger.main() you could expect a different result:
class Inst {
public static void main (String args[]) {
RandomInteger.main(args);
}
}
But note that this is equivalent to just running RandomInteger as it's own program. If, as you say, you want to run your program as a method on an object, this is what you want:
public final class RandomInteger {
private Random randomGenerator = new Random(); //A single object can reuse this component
//function prints out x random numbers between low and high
//Note that your function should do ONE thing, therefore do not make it also interpret
//your program arguments!
public void logXRandomNumbers(int x, int low, int high){
log("Generating " + x + " random integers in range " + low ".." + high);
int range = high - low;
//you really should do a sanity check here to ensure the range is valid.
//note a single Random object is reused here
for (int idx = 1; idx <= x; ++idx){
int nextResult = this.randomGenerator.nextInt(range) + low;
log("Generated : " + nextResult);
}
log("Done.");
}
//This function is probably overkill
private static void log(String aMessage){
System.out.println(aMessage);
}
}
Now all you have to do is call this from your main function:
public static void main (String args[]) {
RandomInteger generator = new RandomInteger();
generator.logXRandomNumbers(10, 0, 100);
}
As for your imports, both classes should have the same package. Lets say its Generator for simplicity:
package Generator;
Only your second class (the not very-well-named Inst) needs to import your generator/logging class:
import Generator.*;
or
import Generator.RandomInteger;
Be sure that both of these files are in the same directory named 'Generator' and that you are running javac from the directory above that.

Related

Find the minimum of a set of data input from the keyboard

I have an algorithm in my textbook written in pseudocode which is then supposed to be "implemented to a Java method". It goes like this:
read min;
while not eoln do
read x
if x < min then
min <- x
end if
end while
print min;
Then I'm given this code:
import java.util.Scanner;
int min() {
Scanner input = new Scanner(System.in);
System.out.println("x=? (999 to end)");
int x = input.nextInt();
int min = x;
while (x!=999) {
System.out.println("x=? (999 to end)");
x = input.nextInt();
if (x < min) {
min = x;
}
}
return min;
}
I put everything below import.Scanner inside of the main method and inside of a class like this:
public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
But then I get this error message in Terminal:
MyAlgorithm.java:7: error: ';' expected
int min() {
^
1 error
Am I missing something? If I put the semicolon there, the whole thing just won't work.
It seems like you put your min method inside of main, this is defining methods from within other methods which will not work properly and cannot compile. The main method is the commands you want to run as soon as you start your program, any other functions in the class should be declared outside of it, and if you want them to run in main you do a method call.
it should look something like this:
import java.util.Scanner;
public class MyAlgorithm {
int min() {
//(min code)
}
public static void main(String[] args) {
// code here
//corrected according to Uli's comment
MyAlgorithm m = new MyAlgorithm();
int result = m.min();
}
}
I suggest reading up on how java programs are structured. Here's an article on methods.
Don't put your method min() inside the main() method. In Java, you can not define a method inside a method. In Java, you need an object to call its methods (Except you make the methods static). So your final Code looks something like this.
import java.util.Scanner;
public class MyAlgorithm {
public static void main(String[] args) {
MyAlgorithm m = new MyAlgorithm ();
m.min();
}
int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
}
If you are allowed to use static methods, (which I don't think) you can use the following alternative:
static int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
public static void main(String[] args) {
int result = MyAlgorithm.min();
}

Setting up my Hangman methods and calling them in my main method

Having difficulty calling the methods in my Game class to my main method for my hangman game.
We're supposed to spin a wheel to get a jackpot amount for 100,250 or 500 bucks then play the game as you'd expect... But methods are a necessity. Im nowhere near done I just want to be able to call my methods at this point to see how its working.
Here's my code:
import java.util.Scanner;
import java.util.Random;
public class GameDemo {
public static void main(String[] args) {
String[] songs = {"asdnj", "satisfaction", "mr jones",
"uptown funk"}; //note this is a very short list as an example
Random rand = new Random();
int i = rand.nextInt(songs.length);
String secretword = songs[i];
System.out.print("Welcome to The Guessing Game. The topic is song titles. \nYou have 6 guesses. Your puzzle has the following letters: ");
System.out.print("After spinning the wheel, you got " + spinWheel());
//continue the code here.
}
}
class Game {
Random rand = new Random();
String[] songs = {"asdnj", "satisfaction", "mr jones",
"uptown funk"};
int i = rand.nextInt(songs.length);
private String secretword = songs[i];
private char [] charSongs = secretword.toCharArray();
private char [] guessed = new char [charSongs.length];
private int guesses;
private int misses;
private char letter;
private char [] jackpotAmount = {100,250,500};
public Game (){}
public int spinWheel(int[] jackpotAmount){
int rand = new Random().nextInt(jackpotAmount.length);
return jackpotAmount[rand];
}
public char guessLetter(char charSongs [], char letter){
int timesFound = 0;
for (int i = 0; i < charSongs.length; i++){
if (charSongs[i] == letter){
timesFound++;
guessed[i] = letter;
}
}
return letter;
}
}
And the return error is
GameDemo.java:11: error: cannot find symbol System.out.print("After
spinning the wheel, you got " + spinWheel()); ^
To call methods from another class you need to make the method public. Once that is done, make them static if you will call the same method many times and you want it do the same function each time (the parameters can still be different).
To call the method do the following (this is a general form for most classes and methods, you should be able to use this to call all your methods):
yourClassWithMethod.methodName();
There are several issues in your spinWheelmethod call:
You haven't instantiated any any Game object to call this method. Either you have to make it static or just instantiate a Game and call it from that objet. I personally prefer the second (non-static) option because, especially because a static method cannot access directly non-static method or variables (... you need an instance or to make them static).
In main, you can do this (non-static solution):
Game game = new Game();
System.out.print("After spinning the wheel, you got " + game.spinWheel());
spinWheel requires an argument of type int[]. It seems that it is not useful since there is an instance variable jackpotAmount that seems to have been created on that purpose. jackpotAmount (see also second point) should be static in you example.
spinWheel becomes :
//you can have "public static int spinWheel(){"
//if you chose the static solution
//Note that jackpotAmount should also be static in that case
public int spinWheel(){
int rand = new Random().nextInt(jackpotAmount.length);
return jackpotAmount[rand];
}
Note that jackpotAmount should better be an int[]than a char[]

Java program without main method

For my class I need to write code that adds up the numbers 1-100 which will produce the number 5050. He told us not to use a main method and use a for loop. Is a main method 'public static void main (String[] args)' or something else. I am just still very confused on what exactly the main method is. Here is the code I have so far that works
public class SumAndAverageForLoop{
public static void main (String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
From what I read more and after talking to some other kids in the class they said I need to make another class with a main method that calls this class but how do you call one class from another?
How to call one class from another that has a main method?
Yes the public static void main(String[] args) signature is the main method.
It sounds like you're writing library style code. So just create a method with a meaningful name for what your code does. Like AddOnetoOneHundred or similar.
You can create a method like this:
public static int CountUp() {
// code that was in your main method before
}
Double check your assignment, your teaching might have specified a class and method name and already has a program that will test your code.
A main method is fundamental to any given program as the Java compiler searches for the method as a starting point of execution. However, you are trying to make a utility class so:
class SumAndAverageForLoop {
// no main method
public static int sum() {
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
System.out.println("The sum is " + sum);
}
}
class MainClassProgram {
// main in another class
public static void main() {
SumAndAverageForLoop.sum();
}
}
Try to create a method to do the calculation. The idea is create code that is unit testable.
public class SumAndAverageForLoop{
public static void main (String[] args) {
int returned = SumUp(1, 100);
System.Out.Println("sum is " + returned);
}
public int SumUp(int startInt, int endInt) {
int sum = 0;
if (endInt > startInt) {
for (int i = startInt; i <= endInt; i++) sum += i;
}
return sum;
}
}
Short Answer:
Yes, that (public static void main (String[] args)) is the main method.
Long Answer:
The main method is the entry point for an application. Without it, you may have code, but that code must somehow link to a main method or it cannot be ran. Counter-intuitively, the main method doesn't actually have to be a method. In C, you can create an integer array called main and execute it. It will translate the integers into hexadecimal and execute a corresponding Assembly command for each one, iteratively.
If you do what the professor says, you will not be able to test the program as an executable. He probably has a program made to run your code and test it for him, which is why he doesn't want a main method.
I'm not sure by what your teacher means by, "not using a main method". But you can declare a method outside of you main method and call it from there;
public class SumAndAverageForLoop{
public static void main (String[] args) {
makeSum();
}
public static void makeSum() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
}
}
Also, since one of your comments asked "How to create a method?".
I suggest you read up on some books for beginners. I'd recommend the book Head First Java.

How to pass information through a method and returning a value

I'm new to Java, and need help. I have been asked to write a program that rolls dice and determines the chance of the player to get two "1s" on the top face of the dice. I have different functions such as role(), getTopFace() etc. I want to be get what the number on the dice is using these functions, but don't know how to call them in my main function. Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class SnakeEyes {
private final int sides;
private int topFace;
public static void main(String[]args)
{
String numberSides;
int n;
numberSides=JOptionPane.showInputDialog("Please enter the number of sides on the dice:");
n = Integer.parseInt ( numberSides);
int[]die=new int[n];
for (int index=0; index<n;index++)
{
die[index]=index+1;
}
//Here is where I want to get information from my functions and calculate the ods of getting two 1's.
}
public void Die(int n)
{
if(n>0)
{
int sides=n;
topFace=(int)(Math.random()*sides)+1;
}
else{
JOptionPane.showMessageDialog(null, " Die : precondition voliated");
}
}
public int getTopFace(int topFace)
{
return topFace;
}
public int role(int[] die)
{
topFace=(int)(Math.random()*sides)+1;
return topFace;
}
}
Make an object of your class SnakeEyes in your main method, and call the required functions using that object.
Example:
SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);
If you want to call this functions from main this functions must be "static", because main its a static function and static function can only call other static functions.
But... this is a very ugly design for a java program, before jumping to write java code you need to understand at least a little about object orientation. For example, why you can't call a non-static function from a static function?, the answer of this question requires knowledge about object orientation and its a knowledge you need if you want to write serious java code.

Getting value to display for Java CurrentAccount class

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.

Categories