Java class doesn't have main method - java

I need to run a method code for GCD. My java file is called "GCD.java" and the public class is called "GCD." Yet I keep getting the message "Class GCD does not have a main method" even though I have no red explanation point circles in any of my lines. I can run the code without the method code (i.e. public static void main(String[] args)), but I need to run the code with a method. Thanks.
==========================
import java.util.Scanner;
public class GCD
{
public static int getDivisor(int x, int y)
{
System.out.println("Greatest Common Divisor Finder");
System.out.println();
String choice = "y";
Scanner sc = new Scanner(System.in);
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter first number: ");
x = sc.nextInt();
System.out.print("Enter second number: ");
y = sc.nextInt();
int secondNumber = 0;
int firstNumber = 0;
int Greatestcommondivisionfinder = 0;
// x = first, y = second
if (x > y)
{
do
{
x -= y;
}
while (x > y);
do
{
y -= x;
}
while (y > 0);
System.out.println("Greatest Common Divisor: " + x);
}
else if (y > x)
{
do
{
y -= x;
}
while(y > x);
do
{
x -= y;
}
while (x > 0);
System.out.println("Greatest Common Divisor: " + y);
}
else
{
int subtract;
do
{
subtract = (int)y - (int)x;
}
while(y > x);
int gcd;
gcd = (int)x - subtract;
}
System.out.println();
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
return 0;
}
}

It's entirely valid for a class not to have a main method - or for it to have a main method which isn't declared as public static void main(String[] args).
However, in order to treat a class as the entry point for a Java application, it needs that method, with that signature (although the parameter name can vary).
So basically, you've got a class which is fine in itself, but you can't launch on its own. You could create a separate class, e.g.
public class GcdLauncher {
public static void main(String[] args) {
GCD.getDivisor(0, 0); // Parameters are ignored anyway...
}
}
Then after compilation you could run:
java GcdLauncher
Or you could add a public static void main(String[] args) method to your GCD class.
I would strongly advise you to change your getDivisor method not to have parameters though - you're not actually using them anyway...

Yes, as your Eclipse correctly says, you don't have main method in your GCD.java file. In-order run this class independently, you need to have main method. Otherwise you can only create Object of this class and call from other class.

If your class is to be used as a main program, it has to implement an
public static void main(String[] args))
Method from where you can call your GCD method.

Related

"Better Code" + User Input

So I just created a little program, which prints out a Box of Stars after asking the User to input a specific height and width of the Box, for example:
height: 4; width: 5 would print out this
Starbox :
Here is my code
import java.util.*;
public class Stars {
public static Scanner scan = new Scanner(System.in);
public static int height = scan.nextInt();
public static Scanner scan2 = new Scanner(System.in);
public static int width = scan.nextInt();
public static void main(String[] args) {
drawBox(height, width);
}
public static void drawBox(int height, int width) {
drawStars(width);
drawStarsWithSpaces(height, width);
drawStars(width);
}
public static void drawStars(int width) {
for (int i = 0; i < width; i++) {
System.out.print("*");
}
System.out.println();
}
public static void drawStarsWithSpaces(int height, int width) {
for (int x = 0; x < height - 2; x++) {
System.out.print("*");
for (int i = 0; i < width - 2; i++) {
System.out.print(" ");
}
System.out.print("*");
System.out.println();
}
}
}
My first Question now is, how do implement a Text saying "Height of the Box" and after that "Width of the Box" when I start the program, so the user knows what to input.
Next thing is that I heard, to not use global variables for some reason and that I should implement code only after the main method... but what would the code of the program with these requirements look like?
First, you don't need two Scanners. One is enough.
Second, the comments on your code are right - it's considered bad practice to use static variables if they're not needed (That's what you referenced as 'global').
These values should be internal to the main function (Which should read the values and invoke appropriate functions, so they should be declared and used in it, and not outside of it.
It would look like:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int width = input.nextInt(), height.nextInt();
...
}
As for running code only after main: you initialize width and height in deceleration. As they're declared static, they're initialized the moment the class is loaded.
Before main has an opportunity to be run!
That is also considered bad practice.
And one more thing - it means you can't run any code before the nextInt() happens (Well, you could initialize another static variable with a method that would print the desired instructions...).
To summarize:
Make all the variables you use local to main and then you could print (using System.out.println()) whatever you wanted before scanning the next input (as scanning will happen in main itself.

java runtime error (NZEC)

So i am working on this ATM problem on codechef and my program runs on my compiler and meets all the problem's requirement however codechef's compiler keeps giving me this NZEC runtime error and i cant figure out why. Here is the code: How can i fix it?
import java.util.Scanner;
public class ATM {
public static final double charge = 0.50;
public static void main(String args[]) {
int x,y;
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
x = keyboard.nextInt();
y = keyboard.nextInt();
if( y > x + charge && x % 5 == 0) {
double balance = y - x - charge;
System.out.println(balance + "0");
} else {
System.out.println(y);
}
}
}
}
You can't use the scanner object in CodeChef. Use BufferedReader instead.
First of all, you did not choose proper data types for your input. Your second input, i.e, y should be of double type, not int type. Then you are not printing your answer in the proper format required by Codechef. Codechef strictly follows the format in which it accepts the answer. Here, your answer must display an output of double/float data type with exactly two decimal places.
Here, I have rectified your mistakes:
import java.util.Scanner;
class ATM {
public static final double charge = 0.50;
public static void main(String args[]) {
int x;
double y;
Scanner keyboard = new Scanner(System.in);
while (keyboard.hasNext()) {
x = keyboard.nextInt();
y = keyboard.nextDouble();
if( y > x + charge && x % 5 == 0) {
double balance = y - x - charge;
System.out.printf("%.2f",balance);
} else {
System.out.printf("%.2f",y);
}
}
}
}
Keep coding :)

How to invoke multiple method signatures within a main method?

So I have three required codes I have already figured out. They are the codes for a quadratic formula, codes for an ISBN checker, and a code for Newtons Method. I'm supposed to make a menu with options 1, 2, and three each containing these codes respectively.
I guess this means I need different methods for this right? I was never really taught - I was told we had to always put in public class void main (String []args){ for everything, and I was just told there were variations to this?
For Quadratics formula, the information is : Return - void and parameters of three doubles, Newtons method: Return - double and parameters of 1 double, and ISBN checker: Return: Boolean and Parameters of 1 string. I don't really understand the parameters thing either. Help would be appreciated. I know this aesthetically looks horrible, but because my codes for now are relatively short I just edit the style when I' done. I know a lot of things are wrong in this too and I've spent time trying to figure them out.
import Java.util.Scanner;
public class HelperMethod{
public static void main(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
System.out.println ("You have three options. press one for the quadratic Formula, 2 for the newtons Method, and 3 for an ISBN checker.");
int input = userInputScanner.nextInt();
if (input = 1){
}else if (input = 2) {
private class NewtonsMethod {
public static void NewtonsMethod(String[] args) {
Scanner userInputScanner = new Scanner (System.in);
double guess, fX, fPrimeX, newGuess;
System.out.println ("enter in a value give");
guess = userInputScanner.nextDouble();
System.out.println ("Your guess is " + guess);
while (true) {
fX = (6 * Math.pow (guess,4)) - (13 * Math.pow (guess,3)) - (18 * Math.pow (guess,2)) + (7 * guess) + 6;
fPrimeX = (24 * Math.pow (guess,3)) - (39 * Math.pow (guess,2)) - 36 * guess + 7;
newGuess = guess - (fX / fPrimeX);
System.out.println ("A possible root is " + newGuess);
if (Math.abs(newGuess - guess) < 0.00001) {
break;
} else {
guess = newGuess;
}
}
System.out.println ("The root is: " + newGuess);
}
}
}else{
private class BookNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char f;
int e, g, h;
int result = 0;
System.out.println ("Pleas enter a thirteen digit number");
String a = scanner.nextLine();
if (a.length() == 13){
for (int i = 0; i < 13; i ++) {
f = a.charAt(i);
e = Character.digit(f, 10);
if (i % 2 == 0) {
g = e * 1;
result = result + g;
} else {
g = e * 3;
result = result + g;
}
}
System.out.println ("The added sum of you numbers is " + result);
if (result % 10 == 0) {
System.out.println ("This combination IS a ISBN number");
} else {
System.out.println ("This is NOT an ISBN number");
}
} else {
System.out.println ("This combination is not thirteen digits long");
}
}
}
}
}
}
First of all, right now you're setting input to 1 in your first if statement. To compare input to 1 instead, use the == operator, i.e. if (input == 1) {.... Secondly, you don't really need to use classes, you can simply have methods NewtonsMethod(), BookNumber() etc. and run them when the input is correct.
public class HelperMethod{
public static void main(String[] args) {
int input;
//Handle user input
switch (input) {
case 1:
newtonsMethod();
break;
case 2:
bookNumber();
break;
case 3:
anotherMethod();
break;
}
}
public static void newtonsMethod() {
//Your code
}
public static void bookNumber() {
//Your code
}
public static void anotherMethod() {
//Your code
}
}
Methods should never be inside one another. That is what classes are for. A method is an element within a class. For example, in your case your class was named "HelperMethod". Your methods need to begin after the main method's code block is closed with a curly brace "}"
as an example
// This would be your main method.
public static void main(String args[]) {
// Your method is CALLED here.
someMethod();
{
// Then this is where your next method would start.
public static void someMethod() {
// Your code for the method of course goes here.
}
Of course you need your class setup and needed imports ABOVE the main method but you have that setup correctly already. With this setup, it makes it easy to call public methods that are in other classes. Your private methods are not really needed unless you intend to use more than one class, at which point you will need to import that class and then call the method like so
SomeClass.someMethod();

Initialization outside of conditionals

I was a newbie, so sorry for my silly question.
Here's the error:
Test.java:19: error: variable y might not have been initialized
Just wondering how I can retain the value of 'y' without changing everything else outside the conditional block. I know (but not really) why this is erroring, because 'y' isn't defined outside the else block.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int x, y;
System.out.print("enter value: ");
x = kb.nextInt();
if (x != 5) {
System.out.println("invalid value");
System.exit(0);
}
else {
y = 10;
}
System.out.println("y = " + y);
}
}
Either initialize it, or put the System.out.println inside the else statement where you initialize y.
else
{
y = 10;
System.out.println("y = " + y);
}
System.out.print("enter value: ");
int x = kb.nextInt();
int y =0;
As local variables are not initialized automatically you will have to initialize them before using
int x, y = 0;
Do what the error message says and initialise y

Newtonian Square Root Java Program

I wrote this program to show the Newtonian method of finding the square root and then to run the math function to find that square root and print both of them out. The math part is working well but the loop I created isn't coming up with the right square root for the newtonian method. Any ideas? Thanks in advance.
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
double guess, new_guess, last_guess, accuracy, n, x, absolutex;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter in N for Newton: ");
n = keyboard.nextDouble();
last_guess = n / 2;
do {
new_guess = ((n/last_guess) + last_guess)/2;
x = new_guess - last_guess;
if(x>=0)
absolutex=x;
else
absolutex=-x;
} while(absolutex < .000001);
System.out.println("Newton = " +new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " +mth);
}
}
Invert the loop condition. You want to loop while absolutex is bigger than epsilon, not while it's smaller. You want to stop when it is small enough.
do {
} while(absolutex > .000001);
looks like math part need little tweaks, so does with loop condition. here try it, it works
package newton_sqrt;
import java.util.Scanner;
public class Newton_sqrt {
public static void main(String[] args) {
// TODO code application logic here
double guess, new_guess = 0, last_guess, accuracy, n, x, absolutex;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter in N for Newton: ");
n = keyboard.nextDouble();
last_guess = n / 2;
do {
new_guess = last_guess - (last_guess*last_guess-n) / (2*last_guess);
x = Math.abs(last_guess - new_guess);
if (x < .000001) {
break ;
} else {
last_guess = new_guess;
}
} while (n >= .00);
System.out.println("Newton = " + new_guess);
double mth = Math.sqrt(n);
System.out.println("Math.sqrt = " + mth);
}
}

Categories