Hi I seem to have a problem calling a class in a main. Can somebody point it out?
KilometerTabel.java
package pratikum31d;
public static double mijlToKilometer() {
double mijl;
mijl = 0;
for (int i = 1; i < 11; i++) {
mijl = i;
}
double kilometer = 1.609 * mijl;
System.out.println(kilometer + " kilometer" + " dat is " + mijl + " mijl");
return kilometer;
}
Main.java
package pratikum31d;
public class Main {
public static void main(String[] args) {
kilometer = mijlToKilometer();
}
}
You never defined a variable called mijl in main. What value do you expect to get passed to mijlToKilometer?
===UPDATE ===
Your new code will have the following problems:
mijlToKilometer is still declared to expect an argument, so you won't be able to call it with no arguments. You must remove the double mijl from the definition of mijlToKilometer.
Your for loop doesn't do what you think it does, though I'm having a hard time identifying what it's supposed to do.
You must declare mijlToKilometer as public.
public static double mijlToKilometer(double mijl)
What are the packages for KilometerTabel and the main class? You haven't put any public/private/protected modifier before your static method. so by default, it will have default visibility. Which is visible within the package. make sure that you bave both classes in same package OR put a public keyword before methods.
secondly, can you please post exact exception?
Related
I am a beginner in java and i am trying to understand the concept of static from a book I bought to learn java. But, because of my experiments in the program, I am very confused. The book says that static could not refer to this keyword, which is fine until I started using normal functions instead of static. In this, I was able to access the static variable with the this keyword!! (see the displayMobileSpecs function in the code below)
import java.util.Random;
class Static {
public static void main(String[] com){
System.out.println("By default the mobile is having "
+ Mobile.RAM + "gigabytes of RAM and"
+ Mobile.CameraMP + " mega pixels of camera");
Mobile S4mini = new Mobile("S4 Mini" , 4 , 16);
S4mini.displayMobileSpecs(true);
Mobile mob2 = new Mobile("fdf" , 23 , 45);
mob2.displayMobileSpecs(true);
S4mini.displayMobileSpecs(false);
}
}
class Mobile{
static int RAM;
static int CameraMP;
Random rand = new Random();
double InternalMemorySpace;
double ExternalMemorySpace;
String modelNo;
Mobile(String modelName,double internalMem , double externalMem)
{
this.modelNo = modelName;
this.InternalMemorySpace = internalMem;
this.ExternalMemorySpace = externalMem;
}
static {
RAM = 4;
CameraMP = 12;
System.out.println("The Static part of the class is executed");
}
void displayMobileSpecs(boolean change){
if(change)
this.RAM = (int) rand.nextInt(8) + 2;
System.out.println(this.RAM + " , " + Mobile.RAM);
}
}
So is it that static variables could be accessed using this but not in the static functions or what?? I am really confused and this is a very silly question as I see it, but please answer me.
(Note: by the way, please don't mind the ridiculous example of mobile used in the program. thanks :) )
static variables could be accessed using this but not in the static
functions
In static block or a static method, there is no instance to refer to, and therefore the "this" keyword is not permitted.
Why am i able to use this keyword with static variables in java
But you can refer "this" in a non static method also you can use refer static variable with "this" keyword in the non static method.Here "this" points to current object.
This a very quick and i feel obvious mistake but i keep getting the CANNOT FIND SYMBOL
symbol : method print(int,int)
this would lead me to believe that i'm not giving the method the right data type parameters, however..
public class Test
{
public static void main(String[] args)
{
TestSrv srvObj = new TestSrv();
srvObj.print(0, 0);
srvObj.print(1, 1);
srvObj.print(2, 10);
}
}
and this method, what it's meant to do aside, i keep getting errors from the above code for all 3 calls to the print method? I am passing it integers on all 3 occasions?
public class TestSrv
{
public void print(int num, int count)
{
for (int i = 0; i <= count; ++i)
{
System.out.print(num + ". " + "*");
}
}
}
Your code should compile. Make sure that you declare both classes in the same package or that you import TestSrv in Test.java.
You almost certainly didn't compile TestSrv after making changes. Using an IDE such as Eclipse or IDEA will take care of much of that detail for you.
while renaming my method and class and such so that it wasn't what i originally named it(as to not confuse anyone) i actually fixed the problem that i had.. that is why this compiled for everyone xD i feel stupid! thanks again
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.
I'm very new to programming, and don't understand much. I've been trying to build a simple game where a user and computer compete by rolling dice to earn points. My method is posted below. The computer is only allowed to earn 20 points per turn.
My issue is that I need the value of variable computerTotal to be remembered after the method has been called and completed. I want to ensure that whenever the computerTurn method is finished, I can use that calculated variable computerTotal outside of that method.
I tried establishing a new int in the .java file class (but outside of the method), and then using that int within the method to hold the value, however I receive errors about the integer needing to be static?
This is all very confusing to me. Can anyone help me out?
public static void computerTurn()
{
System.out.println("Passed to Computer.");
Die computerDie1, computerDie2;
int computerRound, computerTotal;
computerRound = 0;
computerTotal = 0;
while (computerTotal < 21){
computerDie1 = new Die();
computerDie2 = new Die();
computerDie1.roll();
computerDie2.roll();
System.out.println("\n" + "CPU Die One: " + computerDie1 + ", CPU Die Two: " + computerDie2 + "\n");
computerRound = computerDie1.getFaceValue() + computerDie2.getFaceValue();
int cpuDie1Value;
int cpuDie2Value;
cpuDie1Value = computerDie1.getFaceValue();
cpuDie2Value = computerDie2.getFaceValue();
System.out.println ("Points rolled this round for the Computer: " + computerRound);
computerTotal = computerTotal + computerRound;
System.out.println ("Total points for the Computer: " + computerTotal + "\n");
}
Any variables created inside a method are "local variables" meaning they cannot be used outside the method. Put a static variable outside of a method to create "global variables" which can be used anywhere.
Add a method to your class
public static int getComputerTotal() { return ComputerTotal;}
Then you can get the value outside of the class by doing something like:
ComputerTurn();
ComputerTurn.getComputerTotal();
Putting the variable outside of the method is on the right track, but since this method is static (meaning it cannot access variables that depend on object instances), it can only access static variables. Declare computerTotal in the class, outside of methods, using the following:
private static int computerTotal;
You should probably do some research on object-oriented programming and what static means in Java.
Declare computerTotal as a member variable of your class, so that its value is available even outside the function.
class MyClass{
private int computerTotal ;
public void function myFunction()
{
........
......... // your calculations
computerTotal = computerTotal + computerRound;
}
public int getComputerTotal(){return computerTotal ;}
}
You have to declare the computertotal outside any methods to keep them. so like this:
public class name {
int computertotal = 0; //v=can just uuse int computertotal;
public void method() {
while(computertotal < 20) {
computertotal += 1;
}
}
}
And now he variable gets saved!
You may need to add some setters and getters to get that int from another class.
class NewClass {
private int yourInt = 1;
}
It is telling you to make it a static variable because you may be calling it in a statement like
NewClass.yourInt;
, a static variable is one that’s associated with a class, not objects of that class.
Setters and getters are methods which allows you to retrieve or set the value which is private from another class. You might want to add them in the NewClass, where your int is declared. Setters and getters looks like this.
Setter:
public void setYourInt(int newInt) {
this.yourInt = newInt;
}
Getter:
public int getYourInt() {
return this.yourInt;
}
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.