Why does my program immediately crash, displaying "java.lang.NoSuchMethodError: main"? - java

Exercise 1: Write an application that prints the hundreds digit in two integers read from the keyboard. For example, if the data values are 1456 and 254 respectively, your program should print 4 and 2. You may choose the integers yourself. Your output should include the original number followed by the digit in the hundreds position. Label your output appropriately.
That was my question; here's the code I attempted to write using Eclipse.
public class Hundreds
{
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
I'm sure there would be a better method to naming the numbers; that's just what I came up with… but Eclipse shows an error reading:
java.lang.NoSuchMethodError: main
Exception in thread "main"
when I attempt to run it. Any ideas on what I've done incorrectly here?

You need a main() method. The error message you see is because the JVM wants to run main(), but it cannot find it.
A canonical Java example (taken from http://en.wikipedia.org/wiki/Java_(programming_language)#Hello_world) is:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}

You need to put your logic in a main method:
public class Hundreds {
public static void main(String[] args) {
int first1 = 1523;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 589;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}

You need to have a main method as in the Java programming language, every application must contain a main method (entry point) whose signature is:
public static void main(String[] args)
So your code should look like:
public class Hundreds
{
public static void main(String[] args) {
int first1 = 1523;
int first2,first3,second2;
first2 = first1 % 1000;
first3 = first2 / 100;
System.out.println("Original number equals: " + first1);
System.out.println("Hundreds digit equals: " + first3);
int second1 = 289;
second2 = 589 / 100;
System.out.println("Original number equals: " + second1);
System.out.println("Hundreds digit equals: " + second2);
}
}
You could see The Method main; it's a short explanation of its usages.

You need a main method.
public class Hundreds {
public static void main(String[] args) {
// put code here
}
}

Dude...
Where is your main method?
public static void main.....
The rest of your code should go inside it...
BTW, this is the part where you hit your forehead and say "duh..." ;-)
Good luck

Related

Declaring variable in do-while loop and outside as random numbers

I have been trying to write code, which makes the machine guess a random number from 1 to 1000.
Because I know how to write it in pascal and python, I tried to write it in java, but I'm stuck now.
Here is the code:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
do {
int answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}
}
The problem is, that in this line
} while (random != answer);
answer is not defined.
I am trying to do the loop, until random equals answer.
The question is, how do I define the answer variable as a random changing number, while the variable random stays the same?
Thanks in advance!
You have to define int answer outside of the do{}while(...):
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
int answer;
do {
answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}

call a method from another class

I'm in an intro programming class, in the lab that I'm currently working on we have to have two classes and pull the methods from one class, "Energy" and have them run in "Energy Driver."
I'm having trouble calling the methods (testOne, testTwo, testThree) over into "EnergyDriver"
public class EnergyDriver
{
public static void main(String [] args)
{
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + kineticE1);
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + kineticE2);
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + kineticE3);
}
}
public class Energy
{
public static void main(String [] args)
{
public double testOne;
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
}
public double testTwo;
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
}
public double testThree;
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
}
}
You must have only one main method in any one of class. To call a method from another class you can create an object of that class a call their respective method. Another way is by keeping the calling method to be static so you can access that method via Classname.Methodname.
public class EnergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + energy.testOne());
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + energy.testTwo());
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + energy.testThree());
}
}
class Energy
{
public double testOne()
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
public double testTwo()
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
return kineticE2;
}
public double testThree()
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
return kineticE3;
}
}
You can get the value of Kinetic Engergy 1,2,3 by using this code.
You can also use the below code which will use only one method to calculate different values by giving different arguments.
public class EngergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
double mass=25;
double velocity=70;
System.out.println(mass+ " kiolograms, "+velocity+"meters per second: Expected 61250," + " Actual " + energy.testOne(mass,velocity));
}
}
class Energy
{
public double testOne(double mass, double velocity)
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
}
Java programs have SINGLE point of entry and that is through the main method.
Therefore in a single project only one class should have the main method and when compiler will look for that when you run it.
Remember that static methods cannot access non static methods hence main is static therefore it can not access testone two nor three UNLESS you create and object of that type. Meaning in the main method you can have Energy e = new Energy() then access those methods that were not declared with keyword static like e.testone() .
However take note that non static methods can access static methods through Classname.Method name because keyword static entails that only a single copy of that method/variable exists therefore we do not need an object to access it since only one copy exists.
I recommend watching the Java videos from Lynda.com or reading the books Java Head First and Java How To Program (Deitel,Deitel) to give you a boost on your Java knowledge they come with alot of exercises to enhance your knowledge.
Also there are plenty of other questions like this on SO search for them

Towers Of Hanoi Java

This is a homework that I was working on. I have created 2 classes to play Towers of Hanoi. The first one is the basically a runner to run the actual game class.
import java.util.Scanner;
class TowersRunner {
public static void main(String[] args) {
TowersOfHanoi towers = new TowersOfHanoi();
towers.TowersOfHanoi()
}
}
public class TowersOfHanoi {
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
solve(num_of_discs, 'A', 'B', 'C');
}
public static void solve(int first_disc, char aTower, char bTower, char cTower) {
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower);
}
}
}
What I need help with is to make the TowersOfHanoi class to run from my TowersRunner class. I also need to implement a counter display how many times it took for the game to run until the game is finished in my TowersOfHanoi class. Basically I need line that is System.out.println("It took" + counter + "turns to finish.");
I don't know how to implement the counter correctly. Also, can't make the runner class to run the TowersOfHanoi. The TowersOfHanoi class runs fine by itself but the requirment for the homework is we need at least 2 classes min.
Help would be much appreciated!!! Please I am a novice in Java and programming in general please don't go too advanced on me. :D
You don't need the main-Function in the TowersOfHanoi class.
Instead, replace your TowersRunner main(String args[]) method with
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
TowersOfHanoi.solve(num_of_discs, 'A', 'B', 'C');
}
You can just pass the counter in the function and have it be incremented. For example:
public static void solve(int first_disc, char aTower, char bTower, char cTower, int counter) {
System.out.println("Currently on turn #" + counter);
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower, counter + 1);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower, counter + 1);
}
}
In the first call of solve, you would pass in 1. As you can see, each time solve is called recursively, the counter is incremented.
I'll leave you to adapt this to return the final value of counter :) If you just need the final value, you don't need to add a parameter at all. Just make the function return int instead of void then try and figure out how you would make it return the value you want.

Method returns zero

It is suppose to return a value of 19 full seats and 68 students remaining!
please help, with my understanding I am returning the right values and assigning them to the correct variables!
public class JetCalculator
{
public static void main(String[] args)
{
int totalStudents = 3013;
int jetCapacity = 155;
int jets;
int students;
jets = calculateJets(jetCapacity, totalStudents);
students = calculateStudents(jetCapacity, totalStudents, jets);
System.out.println("A total of "+ totalStudents + " student require "+ jets + " full seated jets.");
System.out.println("There will be " + students + " students remaining");
System.out.println("_____________________________________________");
System.out.println(jets);
System.out.println(jetCapacity);
System.out.println(students);
}
public static int calculateJets(int totalStudents, int jetCapacity)
{
int fullJets;
fullJets = totalStudents / jetCapacity;
return fullJets;
}
public static int calculateStudents( int jetCapacity, int totalStudents, int jets)
{
int remainingStudents;
remainingStudents = jetCapacity * jets;
return remainingStudents;
}
}
You call calculateJets this way
jets = calculateJets(jetCapacity, totalStudents);
But the argument names for this method imply that you've switched their order in the call
public static int calculateJets(int totalStudents, int jetCapacity)
This means you're actually doing 155 / 3013 which is 0 using integer arithmetic.
You're passing in your parameters back to front.
You call calculateJets by passing capacity then students: calculateJets(jetCapacity, totalStudents); but the method asks for students then capacity: calculateJets(int totalStudents, int jetCapacity).
This is a good argument for consistency in parameter order throughout a class interface.
To help debug this in future, try throwing in a println at the start of methods to see what is happening:
System.out.println("Called calculateJets with totalStudents of " + totalStudents + " and jetCapacity of " + jetCapacity);
Based purely on method names: did you mean to say remainingStudents = totalStudents - (jetCapacity * jets); ?

What's wrong with my code and/or logic?

I having some trouble with an APCS assignment. The program is supposed to read strings with a length of two from a text file - test1.txt - and print out percentages of: a) girl-girl, boy-boy, boy-girl or girl-boy combinations, and b) the total number of individual groups.
I've been trying for an hour to figure this out! Although I'm suspicious of the String declaration in line 25, I don't have a way to confirm that. Furthermore, I'm worried that I messed up my if-else-if-else loop without prompting a compiler error.
The source code is attached for your reference. If you need any additional information, please don't hesitate to ask.
Since I'm a new user with a reputation < 10, please see the attached image:
For elaboration on what isn't working. I took a screenshot and wrote relevant comments on it!
/**
* Family takes user input of sets of boys, girls, and boys + girls. Results are then
* tabulated and displayed in a percentage form to the user. The total number of
* individuals are also displayed.
*
* #E. Chu
* #Alpha
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family {
public static void main (String[] args) throws IOException {
int boyCount = 0;
int girlCount = 0;
double boyGroupCount = 0.0;
double girlGroupCount = 0.0;
int mixedGroupCount = 0;
int totalPersonCount = 0;
double totalGroupCount;
String currentToken = " ";
Scanner inFile = new Scanner (new File ("test1.txt"));
while (inFile.hasNextLine()) {
currentToken = inFile.nextLine( );
if (currentToken == "BG") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "GB") {
boyCount++;
girlCount++;
mixedGroupCount++; }
else if (currentToken == "BB") {
boyCount += 2;
boyGroupCount++; }
else {
girlCount += 2;
girlGroupCount++; }
}
inFile.close();
totalPersonCount = boyCount + girlCount;
totalGroupCount = boyGroupCount + girlGroupCount + mixedGroupCount;
System.out.println("Sample Size: " + totalPersonCount);
System.out.println("Two Boys (%): " + boyGroupCount / totalGroupCount + "%");
System.out.println("One Boy, One Girl (%): " + mixedGroupCount + "%");
System.out.println("Two Girls (%): " + girlGroupCount / totalGroupCount + "%");
} // End of main method.
} // End of class Family.
currentToken == "BB" should be currentToken.equals("BB")
Don't use == use the method equals instead
Hint: you don't want to compare strings using ==, look into the equals method.

Categories

Resources