Java - random errors on my semicolon and curly brackets - java

this is my first question on Stack Overflow, do comment on how I can improve my question-asking.
So basically I have random errors appearing in my Java code, for the semicolon, curly bracket, and sometimes for other random characters. I have no idea why they keep popping up now and then - they only occur sometimes. I've made sure that all the brackets are paired. Here's an example of when the errors appear :
public static *void* main(String[*]* args) *{*
public class TestClass {
int num1 = 1;
int num2 = 1;
int num3*;*
for(int i = 0; i < 2; i++) {
num3 = num1 + num2;
num1 = num2;
num2 = num3;
num3 = num1 + num2;
System.out.println(num3);
}
}
}
All the character between asterisks have errors in my code. All of them say : "Syntax error on token :...."
And if rewrite the exact same code somewhere else, the errors disappear
What's going on?
Oh, and the asterisks aren't actually in my code, they stand for the squiggly red underlinings in the original code.

You declared class inside of a main method - this is incorrect, you should declare method inside of your class instead - this is an example how you could improve your program to make it work correctly:
public class TestClass {
public static void main(String[] args) {
int num1 = 1;
int num2 = 1;
int num3;
for(int i = 0; i < 2; i++) {
num3 = num1 + num2;
num1 = num2;
num2 = num3;
num3 = num1 + num2;
System.out.println(num3);
}
}
}

As mentioned in the other replies you have your class inside your method, instead of your method inside of your class.
When thinking about object oriented programming, your classes should be the concept you are trying to represent and the methods should be what they do.
For example:
public class Dog{
public void bark(){
//foo
}
}
Is like saying there's a dog and it can bark.
However:
public class Bark{
public void dog(){
//foo
}
}
Is like saying there's a bark and it can dog. It doesn't make much sense.
And what you have now is even a bit stranger:
public void bark(){
public class Dog{
//foo
}
}
Which doesn't have any particular meaning in programming. But the best that I could reason would be that something can bark, but also contains a dog. It doesn't make any sense really.

You got the class and main method backwards. The main method goes inside the class:
public class TestClass{
public static void main(String[] args){
// code here
}
}

There are several problems.
1. You are trying to define the method "main" outside of a class. You can't do that.
2. You are trying to define a class inside the main method. That is wrong.
3. You are writing executable code (the loop) inside the class definition but not inside a method of the class.

All of your code needs to be inside
public class Main{
}

Related

calling method to a main in java

I'm writing a program that calculates the hypotenuse of a triangle, and I'm supposed to call up a method into the main.
Is it better to have them in 2 separate files, or to have the method I'm calling up in the program I'm running?
In the program, I keep getting error messages about the last line of code, with the JOptionPane output.
What am I getting wrong?
import javax.swing.JOptionPane;
import java.util.Scanner;
public class A2
{
public static double Hypo(double a,double b,double c);
double a,b,c;
{
hyp=((a*a)+(b*b));
c=Math.sqrt(hyp);
}
int x,y;
double c;
String text1=JOptionPane.showInputDialog("How long is side A? ");
int x=Integer.parseInt(text1);
String text2=JOptionPanes.howInputDialog("How long is side B? ");
int y=Integer.parseInt(text2);
double c=A2.Hypo(x,y);
JOptionPane.showMessageDialog(null, "The hypotenuse of the triangle is " +c);
}
This code has so many problems it's hard to know where to begin.
Here's some advice:
Good names matter. You can and must do better than A2 for a class.
Learn and follow the Sun Java coding standards.
Style and readability matter. Learn a good code layout and stick to it.
Start with this. It runs and gives correct results:
import javax.swing.*;
/**
* A2
* #author Michael
* #link https://stackoverflow.com/questions/30965862/calling-method-to-a-main-in-java
* #since 6/21/2015 11:00 AM
*/
public class SimpleMathDemo {
public static double hypotenuse(double a,double b) {
return Math.sqrt(a*a+b*b);
}
public static void main(String[] args) {
String text1= JOptionPane.showInputDialog("How long is side A? ");
int x=Integer.parseInt(text1);
String text2=JOptionPane.showInputDialog("How long is side B? ");
int y=Integer.parseInt(text2);
double c= SimpleMathDemo.hypotenuse(x,y);
JOptionPane.showMessageDialog(null, "The hypotenuse of the triangle is " +c);
}
}
Code analysis
public class A2 {
//Missing method body no return values ..Is this an abstact function?/
public static double Hypo(double a, double b, double c);
double a, b, c;
//Whats this part doing hanging in the middle??
{
//where is the variable declaration of hyp
hyp = ((a * a) + (b * b));
c = Math.sqrt(hyp);
}
int x, y;
//variable c is already declared
double c;
String text1 = JOptionPane.showInputDialog("How long is side A? ");
//variable x is already declared
int x = Integer.parseInt(text1);
//JOptionPane not JOptionPanes
String text2 = JOptionPanes.howInputDialog("How long is side B? ");
//variable y is already declared
int y = Integer.parseInt(text2);
//variable c is already declared and Hypo function has three arguements in the declaration
double c = A2.Hypo(x, y);
//wont work because the whole code is buggy
JOptionPane.showMessageDialog (null, "The hypotenuse of the triangle is " +c);
}
}
To elaborate more:
import javax.swing.JOptionPane;
public class A2 {
public static double Hypo(int a, int b) {
double hyp=((a*a)+(b*b));
double c=Math.sqrt(hyp);
return c;
}
public static void main(String[] args) {
int x, y;
double c;
String text1=JOptionPane.showInputDialog("How long is side A? ");
x=Integer.parseInt(text1);
String text2=JOptionPane.showInputDialog("How long is side B? ");
y=Integer.parseInt(text2);
JOptionPane.showMessageDialog(null, "The hypotenuse of the triangle is " + Hypo(x,y));
}
}
You need to choose a correct return type, whether it be void, int, double, etc, and each method with a return type should return a value with the set type.
You also always need at least one main method in a program. There can be multiple in different classes.
You will need to use a more specific variable names, and follow oracle convention for brackets {}.
DO not declare a variable twice as in:
int x, y;
int x = 1; // WRONG
x = 1; // Correct

Java: "error: cannot find symbol"

(Rookie mistake, I'm sure.)
I'm a first year computer science student, and attempting to write a program for an assignment, with the code;
import java.util.Scanner;
public class Lab10Ex1 {
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type a number: ");
int n = keyboard.nextInt();
calcNumFactors();
}
public static void calcNumFactors(){
System.out.print(n + 1);
}
}
But upon compiling, I get the error;
Lab10Ex1.java:10: error: cannot find symbol System.out.print(n +
1);
^
symbol: variable n
location: class Lab10Ex1
If someone could explain to me what I've done wrong, or how to fix it, I would greatly appreciate it.
The n variable was declared in the main method and thus is visible only in the main method, nowhere else, and certainly not inside of the calcNumFactors method. To solve this, give your calcNumFactors method an int parameter which would allow calling methods to pass an int, such as n into the method.
public static void calcNumFactors(int number) {
// work with number in here
}
and call it like so:
int n = keyboard.nextInt();
calcNumFactors(n);
You must declare the variable n in public static void calcNumFactors()
In your code, you have to pass the value of n as an argument to the function calcNumFactors() as Hovercraft Full Of Eels said.
import java.util.Scanner;
public class Lab10Ex1 {
private static int n;
public static void main(String[] arg) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type a number: ");
n = keyboard.nextInt();
calcNumFactors();
}
public static void calcNumFactors(){
System.out.print(n + 1);
}
}
In my case, I copied an Enum file from a Grails (.groovy) project and forgot to change the extension to .java

Java variables not available in different methods within class - newbie

I'm new to Java and I looked everywhere but I'm not getting a simple concept.
I declare two variables as int. I want the two variables to be global to all methods.
In my first method, I want to get the value of the first variable from user input.
Then I want that new value available, recognized, and called by the second method. However, every time the first method ends, the value of the variable is set back to 0, and the second method does not find the value the user gave to it in the first method input. What am I doing wrong? Do I need to declare my variables differently? Do I need to declare my methods differently? Thanks for your help!
import acm.program.*;
public class FindRange extends ConsoleProgram {
int num1;
int num2;
public void run() {
println("This program finds the largest and smallest numbers.");
getNum1();
getNum2();
// getNumUntilZero();
}
public void getNum1() {
int num1 = readInt("?:");
if (num1 == 0) { //do not accept 0 for first number
println("Please try again without 0.");
getNum1();
}
}
public void getNum2() {
int num2 = readInt("?:");
if (num2 == 0) { //if 2nd number is 0, print 1st num as high and low nums
println("Biggest number:" + num1);
println("Smallest number:" + num1);
}
}
}
when you do int num1 = readInt("?:"); inside method getNum1(), its a local variable stored in stack . it does not refer to global variable (declared as instance variable )which you want to refer
So do it like this:
public void getNum1() {
num1 = readInt("?:");
if (num1 == 0) { // do not accept 0 for first number
println("Please try again without 0.");
getNum1();
}
}
public void getNum2() {
num2 = readInt("?:");
if (num2 == 0) { // if 2nd number is 0, print 1st num as high and low nums
println("Biggest number:" + num1);
println("Smallest number:" + num1);
}
}
actually you have created new variable inside method. so not actually assigning values to the class variables, but to method variable:
so change
int num2 = readInt("?:");
to
num2 = readInt("?:");
and
int num1 = readInt("?:");
to
num1 = readInt("?:");
You redeclare a local variable called the same thing. This should give an IDE warning along of the lines of "local variable hides a field". So in the scope of the method there is another numX.
You need to reference the instance variable and not declare a new variable:
public void getNumX() {
numX = readInt("?:");
//...
}
You see I have removed the int declaration so that this now assigns the value to numX rather than to a local variable.

exception in thread "main" java.nosuchmethoderror:main [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
i am new in java.i want to write a program to swap 2 nos.
i have written 2 programs on it.one is running and other is not.
i cant understand the fault of the not running program.pls help me to understand my fault.
here i giving you both the programs along with the output.
the running program:
public class SwapElementsExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
swap(num1, num2);
}
private static void swap(int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
}
}
the output is:
before swapping
value of num1 is : 10
value of num2 is : 20
after swapping
value of num1 is : 20
value of num2 is : 10
in the above mentioned program i have not any problem.
but in the next program what is the fault i cannot find.
pls help me to find the error.
class Swap
{
public static void main(int a, int b)
{
int c=0;
c=b;
b=a;
a=c;
c=0;
System.out.println(a);
System.out.println(b);
}
}
in the execution there is no error msg.
but in runtime there is a error msg and that is:
exception in thread "main" java.nosuchmethoderror:main
pls let me know the problem of this program.
public static void main(int a, int b) is not correct.
It must be:
public static void main(String[] args). This is by definition.
If you want to get the first and second argument:
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
problem lies here
public static void main(int a, int b)
Java always starts executing program from the main method you declared in the first sample code.
When you start your java application, the java interpreter tries to find a method
public static void main(String[] args)
to run the application.
In one class you can declare several methods with the same name but with different parameters they get. Like that:
public static void main(String[] args) {
}
public static void main(int a, int b) {
}
public static void main(float a, float b) {
}
And all these methods will be accepted by compiler. Because every method is not identifying by its name only, but by its name and signature. Signature is based on the parameters you pass to a method. Type of every parameter and parameters sequence are the signature body.
So, when you start your app without public static void main(String[] args) method inside, then interpreter is unable to find the main method with expected signature String[] args, and throws the exception.

input 2 variables(user input by "Buffered Reader") to be pass to a class?

i am a beginner at java language and i use "text pad". i have a problem with my simple program. my task is to input 2 values and show the "sum","difference","product" and "quotient" altogether. (simple right?) in which , here below is the class that supposed to be doing the job of arithmetic. in which is "correct" as i compiled.
public class mathclass
{
int x;
int y;
int total;
void add ()
{
total = x+y;
}
void sub ()
{
total = x-y;
}
void multi ()
{
total = x*y;
}
void div ()
{
total = x/y;
}
}
And here is the main program that supposed to be the input and output of the program.
my problem here is that i can't pass the 2 variables (num1 and num2) to "mathclass"
i did research on how to pass 2 variables to a another class. but there is nothing same to mine that i have. i did use some like the putting "private or public" on the variables.
my teacher said to use the BufferedReader for input. and i am having a hard time how to get this program right. (sorry if i had wrong english(if i am wrong. ))
import java.io.*;
public class mathmain
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args)throws IOException
{
mathclass math1 = new mathclass();
System.out.print("Enter 1st Number :");
num1 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.print("Enter 2nd Number :");
num2 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
math1.add();
{
System.out.print("Sum : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.sub();
{
System.out.print("Difference : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.multi();
{
System.out.print("Product : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.div();
{
System.out.print("Quotient : ");
System.out.println(math1.total);
}
}
}
It's really not clear what you're trying to do here. (Why doesn't add take two arguments for instance?)
Perhaps your after something like this:
// Set up arguments
math1.x = num1;
math1.y = num2;
// Perform the add.
math1.add();
// { <-- brace completely useless.
// Print the result
System.out.print("Sum : ");
System.out.println(math1.total);
// } <-- brace completely useless.
However, I would encourage you to use return values and use parameters:
class MathClass {
public int add(int a, int b) {
return a + b;
}
...
}
and then use the class like
int sum = math1.add(num1, num2);
System.out.println("Sum: " + sum);
You should take some look on how to code in Java because you're going the wrong way.
Either you create a constructor to initialize x & y either you put them in the method add(x,y) which would lead you to make the method static and remove references of x & y from the class. Same goes for the total that should be the return of your function.
Try this,
Use Two Parameter Constructor for mathmain class...
public mathmain(int x, int y){
this.x = x;
this.y = y;
}
Please use Uppercase for the Fist alphabet of the class name (eg: MathMain),
and yes, use Camel Case for writing Class, Variables, Method,etc Names in java.
Since you're beginning, I will not point out the design flaws. Your problem comes from how you are using your read values. You read values into num1 and num2, but you never set them in your mathclass object:
math1.x = num1;
math1.y = num2;
As per what aioobe said, you should look at java design rules to help you create robust, useful classes. I would also encourage you to encapsulate your classes and use parameters and return values whenever possible.
Good luck in learning java, and I hope this helped!

Categories

Resources