calling method to a main in java - 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

Related

Need help adding methods in main class

Hello I'm working on a project for my java class, I'm supposed to write a code for a Algebra tutor that goes like this:
Write a program with a that displays a randomly generated problem that asks the user to solve for the y variable, takes input from the user, and prints "correct" if the user answered correctly and prints "incorrect" if not. Your main should give one problem and then exit. Use one or more methods to produce this behavior.
This is regarding the formula mx + b. So here is what I have so far, and works!
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
class Main {
public static void main(String[] arg){
double min_value = -100;
double max_value = 100;
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int)m_value * (int)x_value + (int)b_value;
if (user_answer.equals(correct_answer))
System.out.println("You are correct!");
else
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
}
}
so even tho the output is correct, I need to break down the code into smaller methods, this is where Im getting confused on how to take a piece of that code and put it in another method that once it runs it calls for that method too and gives me the same output. I been ready the material given but the more I read it the more confuse I get. If anybody has any ideas or suggestions please let me know any info will be really appreciate. Thank you
Here's a quick rundown on methods, so it's not completely done yet. Ask, if you need more help! Good luck on your homework and on becoming one of the beast developers!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
Technically you've solved the problem correctly, you are using one or more methods, but perhaps what you trying to do is a common code refactor called the extract method / extract function refactor Executing this type of refactor leads to much more readable and maintainable code, and is easy to do.
As a starter, identify code that repeats or looks similar, in your case, the following lines look ripe for extract method:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
Notice that the RHS of each line is identicial, so we can replace the explicit code with a method call like this:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
You can identify other areas of code that either contain repetition or perhaps some hard to understand code that would be more understandable if it was extracted into a method that had a name that reveals what the code is doing.
Please review this, you are comparing string with integer,
if (user_answer.equals(correct_answer))
This may help you:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}

Simple Java program related to hierarchical inheritance is not giving desired output

I have written the following Java program:
Tab1:
package base;
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner obj = new Scanner(System.in);
System.out.println("Enter first number: ");
int num1 = obj.nextInt();
System.out.println("Enter the second number: ");
int num2 = obj.nextInt();
Add obj1 = new Add();
Mul obj2 = new Mul();
obj1.getData(num1, num2);
int add = obj1.addition();
int mul = obj2.multiplication();
System.out.println("The addition of the two numbers is: " +add);
System.out.println("The multiplication of the two numbers is: " +mul);
}
}
Tab2:
package base;
public class Parent {
int num1, num2;
void getData(int x, int y){
num1 = x;
num2 = y;
}
}
Tab3:
package base;
public class Add extends Parent {
int addition(){
int x;
x = num1 + num2;
return x;
}
}
Tab4:
package base;
public class Mul extends Parent {
int multiplication(){
int x;
x = num1*num2;
return x;
}
}
When I run the code it gives me a result like this:
Enter first number:
5
Enter second number:
4
The addition of the two numbers is: 9
The multiplication of the two numbers is: 0
I have got the same type of result with all kind of different inputs.
The result of the multiplication is always 0
I have cross checked my code several times but apparently I cannot find any mistake.
Where am I going wrong?
Any help will be greatly appreciated.
You should pass argument to Mul instance before calling its method
obj2.getData(num1, num2);
int mul = obj2.multiplication();
There is no call to getData() on obj2:
obj2.getData(num1, num2);
Add obj1 = new Add();
Mul obj2 = new Mul();
obj1.getData(num1, num2);
You created two distinct objects, obj1 and obj2 but put non-zero values only into obj1. The values in obj2 are still zero.

Little coding challenge (Fermat’s Last Theorem)

I am trying to learn Java; here is the exercise I am struggling with:
Fermat’s Last Theorem says that there are no integers a, b, and c such that a^n + b^n = c^n except in the case when n = 2.
Write a method named checkFermat that takes four integers as parameters— a, b, c and n—and that checks to see if Fermat’s theorem holds. If n is greater than 2 and it turns out to be true that a^n + b^n = c^n, the program should print “Holy smokes, Fermat was wrong!” Otherwise the program should print “No, that doesn’t work.”
You should assume that there is a method named raiseToPow that takes two integers as arguments and that raises the first argument to the power of the second. For example:
int x = raiseToPow(2, 3);
would assign the value 8 to x, because 2^3 = 8.
I have encountered several problems, for example I can't seem to use Math.Pow(a, n) with an int, only with a double. If you are interested, here is what I have so far, feel free to skip it and just write your own version of the program in the answers.
(Please keep in mind I started this book only a few days back.)
package fermat.s_last_theorem;
import java.lang.Math;
import java.util.Scanner;
public class FermatS_Last_Theorem {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
System.out.println("Inster First Number");
double frst = s.nextDouble();
System.out.println("Insert Second Number");
double scnd = s.nextDouble();
System.out.println("Insert Exponent");
double expo = s.nextDouble();
double v = FLaw(frst,scnd,expo);
double k = FLawRes(v, expo);
System.out.println("The answer is " + v);
System.out.println("Your answer rooted by your exponent is " + k);
Law(v, Pow(k, expo));
}
public static double Pow(double a, double b) {
double res = Math.pow (a, b);
return (res);
}
public static double FLaw(double frst, double scnd, double expo) {
double D1 = Pow(frst, expo);
double D2 = Pow(scnd, expo);
return (D1 + D2);
}
public static double FLawRes(double res, double base) {
double D3 = Pow(res, 1/base);
return D3;
}
public static void Law(double v, double k) {
if (v==k) {
System.out.println("Pythagora works.");
} else {
System.out.println("Pythagora doesnt work");
}
}
}
The main problem is that I am not exactly sure how to answer the question the exercise asks, and the program listed above does not work as it should.
You should assume that there is a method named raiseToPow ...
That means you write your code using such a method, even though you don't have the method. Your code will be reviewed manually, or teacher may supply the method and run your code.
If you want to test your code, you can always implement it yourself. You should just remove the method before turning in the code.
But the intent here is that this is a write-on-paper exercise.
Now, how to implement int raiseToPow(int a, int b)?
Think about what it means. 34 means 3 * 3 * 3 * 3.
So, implement the method to multiply by a by itself b times.
I'll leave that as another exercise for you.
You can break it out like this :
public boolean checkFermat(int a, int b, int c, int n) {
if(n != 2 &&
(checkFermatCondition(a,b,c,n) ||
checkFermatCondition(a,c,b,n) ||
checkFermatCondition(b,c,a,n))) {
System.out.println("Holy smokes, Fermat was wrong!");
} else {
System.out.println("No, that doesn’t work.");
}
}
In this method you are just trying to reduce you check condition with all of the combinations by calling this method with different parameters
private boolean checkFermatCondition(int a, int b, int c, int n) {
return raiseToPow(a,n)+raiseToPow(b,n) == raiseToPow(c,n);
}
Your function raiseToPow()'s functionality can be achieved using Math.pow:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println( "Fermat's Last Theorem: a^n+b^n != c^n (n!=2)");
int a, b, c, n;
System.out.print("Enter value for a:");
a = s.nextInt();
System.out.print("Enter value for b:");
b = s.nextInt();
System.out.print("Enter value for c:");
c = s.nextInt();
while(true){
System.out.print("Enter value for n:");
n = s.nextInt();
if(n!=2)
break;
System.out.println("n cannot be 2");
}
checkFremat(a,b,c,n);
}
public static void checkFremat(int a, int b, int c, int n){
if ((int)Math.pow(a, n)+(int)Math.pow(b, n)!=(int)Math.pow(c, n))
System.out.println("Fermat was correct!");
else
System.out.println("Holy smokes, Fermat was wrong!");
}
}
Try it here!

How to create a method for JOption Pane in java?

how can I make a method for JOptionPane in java, thats gets and stores the value given by the user in a given variable and converts it into double / int, the variable which I want to store the value in is outside the method and in main class
e.g.
public static void main(String args[]){
double num1
int num2
// calling the method
method(pane, num1);
}
public void method(String pane, double number){
String pane = JOptionPane.showInputDialog("choose a number");
number = Double.parseDouble(pane);
}
}
which then can be printed like so
system.out.println(num1);
Make the method return double. And make num1 = method()
number will be destroyed when you exit the method as it's local to the method. So num1 will be 0, as it's the default value for double and it won't be affected.
You should do something like that:
double res; //a class member
..
..
String pane = JOptionPane.showInputDialog("choose a number");
res = Double.parseDouble(pane);

Passing Variables between methods?

So im trying to write a simple java program for college and I'm a complete newbie at this java stuff. I keep getting an error when I compile, "error - could not find symbol" within the method printreciept. I know that it's something like not being able to access the variables within the main. Could anyone help? I know I'll prob have alot of errors if I do fix it but I'd rather start here! P.S. sorry for all of the code :/
import java.util.Scanner;
public class Order {
public static void main (String[] args) {
String clubcard;
double clubcard_discount;
double special_discount;
double balance;
double final_balance;
int apples;
int oranges;
int apples_cost;
int oranges_cost;
final Scanner scanner = new Scanner( System.in);
System.out.println("How Many Bags of Apples?");
apples = scanner.nextInt( );
System.out.println("How many bags of Oranges?");
oranges = scanner.nextInt( );
System.out.println("Do you have a clubcard? Yes/No");
clubcard = scanner.nextLine();
if(clubcard == "Yes") {
clubcard_discount = clubcard_discount - 1.0;
final_balance = final_balance - (balance / 100 * 10);
}
else if(clubcard == "No") {
special_discount = 0.0;
}
if(apples == 3) {
special_discount = -1.0;
balance = balance - 1.0;
}
}
//Calculating the cost of apples and oranges
public void calculate_apples (final double apples_cost ) {
apples_cost = apples * 1.0;
}
public void calculate_oranges (final double oranges_cost ) {
oranges_cost = oranges * 1.25;
}
//Printing the receipt
public static void printReceipt() {
System.out.println("Bags of apples: " + apples);
System.out.println("Bags of oranges: " + oranges);
System.out.println("Clubcard: " + clubcard);
System.out.println( );
System.out.println("Price for apples: " + apples_cost);
System.out.println("Special discount: " + special_discount);
System.out.println("Price of oranges: " + oranges_cost);
System.out.println("Total: " + balance);
System.out.println("Clubcard discount: " + clubcard_discount);
System.out.println( );
System.out.println("Final price: " + final_balance);
System.out.println( );
System.out.println("Thanks for doing business with CS2500.");
}
}
You have declared all your variables as local variables inside the main method, so they aren't in scope outside main. To have them accessible to other methods, you can do one of the following:
pass them to the methods as parameters
declare them as static class variables outside any methods, but inside the class.
You can add the variables making them static .
public class Order {
static String clubcard;
static double clubcard_discount;
static double special_discount;
static double balance;
static double final_balance;
static int apples;
static int oranges;
static int apples_cost;
static int oranges_cost;
public static void main (String[] args) { ...
Try this and let us know.
You aren't passing the variables, that's the problem. You declared them in main. However, if you declare them as static variables before the main method, that will work.
variables declared inside any method are for that method only(local scope).
Either declare those methods at class level or pass them as arguments from main(as per use case, if methods being called from main).
The variables you are passing are visible only inside main.
The function printReceipt() is unable to see the variables because they are out of its scope of visibility.
Here you have few options you can try and the program will work:
Declare the variables as the data members of the public class Order rather than keeping them as members of the main() function (best option).
public class Order{
static String clubcard;
static double clubcard_discount;
static double special_discount;
static double balance;
static double final_balance;
static int apples;
static int oranges;
static int apples_cost;
static int oranges_cost;
//main() and other functions...
}
OR
Pass the data members as arguments to the PrintReceipt() function (though this may make you function a bit messy).
public static void printReceipt(int apples, int oranges, .... .... ){
//...defining your function
}
Hope this helps!

Categories

Resources