Java program without main method - java

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.

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();
}

method returning average of double array

Im new with programming and have been trying to solve this problem for a while, been looking at similar questions but im not understanding whats wrong with my code.
So the assignment is to write a method that takes an array that has three doubles in it. Then return the average of the three doubles. Then write a main that should call and then type the method.
Thanks!
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double []arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(double arr[]);
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[]arr){
while(i<arr[].length()){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr[].length();
return genomsnitt;
}
}
PS. they are two different classes with 1 main and 1 class they are not in the same file!
The error:
Syntax error on token "double", new expected
Variable must provide either dimension expressions or an array initializer
arr cannot be resolved to a type
at Tenta131031upg1main.main(Tenta131031upg1main.java:7)
Please correct the two lines in the first file like this:
double[] arr ={3.15, 4.41, 7.64};
Tenta131031upg1.genomsnitt(arr);
You were creating a new, empty array in the second line.
Try this:
Main
public class Tenta131031upg1main {
public static void main (String[]args){
double[] arr ={3.15, 4.41, 7.64};
System.out.println(Tenta131031upg1.genomsnitt(arr));
}
}
Class
public class Tenta131031upg1 {
static int i =0;
static double sammanlagd=0;
static double genomsnitt=0;
public static double genomsnitt(double[] arr){
while(i<arr.length){
sammanlagd = sammanlagd + arr[i];
i++;
}
genomsnitt = sammanlagd/arr.length;
return genomsnitt;
}
}
Changes are:
change in method call
arr.length instead of arr[].length()

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.

New object instance not being recognized- 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.

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