How to create a method for JOption Pane in java? - 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);

Related

Comparing return values from two overloaded methods in an if statement (in main method)

So i'm new to java, we just started this language in my programming class about a month ago. Anyhow, we're on overloading methods right now (just started methods last week) and I'm having trouble with comparing the values of the return statements in the overloaded methods. My intention is to compare them in an if statement in the main method. I'm sure the answer is simple, but i can't find information on it in my textbook or online. Sorry about the sloppy indentation, I'm having trouble with the features on this website and it's the first time i've used it. would appreciate any help! Here is the program:
import java.util.Scanner;
public class pizzaCalculation {
public static void main(String[] args){
//create scanner
Scanner i = new Scanner(System.in);
//create sentinel while loop, initiate priceperinch for both pizzas
int sentinel = 1;
//create while loop
while(sentinel != 0){
//create input for round pizza
System.out.println("What is the price of the round pizza?");
double priceRound = i.nextDouble();
System.out.println("What is the radius?");
double radius = i.nextDouble();
pizzaPrice(radius, priceRound);
System.out.println("What is the price of the rectangular pizza?");
double priceRect = i.nextDouble();
System.out.println("What is the width and length of the rectangular pizza?");
double width = i.nextDouble();
double length = i.nextDouble();
pizzaPrice();
//create if statement to determine best deal
if (pricePerInchRound > pricePerInchRect){
System.out.println("The best deal is the round pizza which is $"+pricePerInchRound);
}else{
System.out.println("The best deal is the rectangular pizza is $"+pricePerInchRect);
}
//ask if user would like to do again
System.out.println("Would you like to do another calculation? Enter 1 for yes and 0 for no.");
sentinel = i.nextInt();
}
}
public static double pizzaPrice(double num1, double priceRound){
Scanner i = new Scanner(System.in);
//this is for round pizza
double areaRound = Math.PI * num1 * num1;
double pricePerInchRound = priceRound / areaRound;
return pricePerInchRound;
}
public static double pizzaPrice(double num1, double num2, double priceRect){
//this is for rectangular pizza
//create scanner
Scanner i = new Scanner(System.in);
double areaRect = num1 * num2;
double pricePerInchRect = priceRect / areaRect;
return pricePerInchRect;
}
}
So there are several issues:
You need to pass parameters to the second call of pizzaPrice() like this
pizzaPrice(width, length, priceRect);
You need to store results of method calls in variables like
pricePerInchRound = pizzaPrice(a, b);
pricePerInchRect = pizzaPrice(a, b, c);
You are calling pizzaPrice() but you need to store the resulting value in a variable so you can use it later (and pass the right parameters).
double pricePerInchRound = pizzaPrice(radius, priceRound);
and ...
double pricePerInchRect = pizzaPrice(width, length, priceRect);
Also, take care to name your method parameters better - num1, num2 aren't very descriptive. You could have used width, length.

Display method to display results from other methods Java

I'm trying to show the results from GCD and LCM using the display method. I try accessing the numbers object in the display method and it cannot resolve the symbol. Everything works with the code I'm just not sure how else I can access the numbers object inside the display method. Any help is greatly appreciated! Thanks
public static void main(String[] args) {
TwoNumbers numbers = getNumbers();
System.out.println(numbers.getNum1());
System.out.println(+numbers.getNum2());
GCD(numbers.getNum1(), numbers.getNum2());
System.out.println(GCD(numbers.getNum1(), numbers.getNum2()));
LCM(numbers.getNum1(), numbers.getNum2());
System.out.println(LCM(numbers.getNum1(), numbers.getNum2()));
}
public static TwoNumbers getNumbers(){
int num1;
int num2;
Scanner input = new Scanner(System.in);
System.out.println("Enter your first number: ");
num1 = input.nextInt();
System.out.println("Enter your second number");
num2 = input.nextInt();
return new TwoNumbers(num1, num2);
}
public static int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public static long LCM(int a, int b) {
return a * (b / GCD(a, b));
}
public static void display(){
}
TwoNumbers numbers = getNumbers();
If you are trying to access numbers of main method. Then you can not do that, scope of numbers is only inside main method. You can not access it directly from other method.
Either you pass the numbers as parameter to display method or you can declare numbers as class level static variable.
public static void display(TwoNumbers numbers){
//Now you have numbers inside display
}
Moreover, you do not need to call the GCD and LCM method again from the display. You can simply pass result of both methods to display method from main.
TwoNumbers gcdNumbers = GCD(numbers.getNum1(), numbers.getNum2());
display(gcdNumbers);
TwoNumbers lcmNumbers = LCM(numbers.getNum1(), numbers.getNum2());
display(lcmNumbers);

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

Where should scanner go in this program?

I'm working on a program that takes the input of two numbers and then does some different calculations. I have my TwoNumbers class with several different methods to calculate sum, distance, average, etc.
Should I put the scanner in this class, or should I put it in the Main method?
I know this is really basic but I've only been learning java for a couple weeks and I'm having a hard time finding how this should be done/how to get the input to correlate to my instance variables and firstNumber and secondNumber
public class TwoNumbers{
private double firstNumber;
private double secondNumber;
public double getSum()
{
double sum = firstNumber + secondNumber;
return sum;
}
public double getDifference()
{
double difference = firstNumber - secondNumber;
return difference;
}
public double getProduct()
{
double product = firstNumber - secondNumber;
return product;
}
public double getAverage()
{
double average = (firstNumber + secondNumber) / 2;
return average;
}
public double getDistance()
{
double distance = Math.abs(firstNumber - secondNumber);
return distance;
}
public double getMax()
{
double maximum = Math.max(firstNumber, secondNumber);
return maximum;
}
public double getMin()
{
double minimum = Math.min(firstNumber, secondNumber);
return minimum;
}
}
Each class should follow the single responsibility principle. Your TwoNumbers class should only work with the double numbers and perform operations on them, nothing more. Providing the double numbers for this class should be in the client, and also the ability to provide the numbers, which means that the client may define the Scanner or another way to provide the data.
The class you have displayed, the TwoNumbers class, should have no user input in it as it should encapsulate the concept of two numbers and two numbers only. It should be written in such a way that it can be used with a Scanner program or with a GUI program without having to change it. Thus the UI should be in main or in another class.
You would probably want to make a constructor for the class, and within the constructor pass the variables you want. This would mean that you get your input from somewhere else, IE the main method or some other means.
public TwoNumbers(double num1, double num2){
firstNumber = num1;
secondNumber = num2;
}
For example:
public double getSum(firstnumber, secondnumber) // <-- you need pass in the value
{
double sum = firstNumber + secondNumber;
return sum;
}
/*
* somewhere in the main or another method you can delare the first number / 2nd number
* for example:
*/
public void static main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first number");
firstnumber = input.nextInt();
System.out.println("enter first number");
secondnumber = input.nextInt();
}
After that all you need to do is just calling the method you want to pass the number to.
You need to have a constructor in TwoNumbers:
public class TwoNumbers {
private double firstNumber;
private double secondNumber;
public TwoNumbers(double firstNumber, double secondNumber){
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
}
Then in some other Class, you can have your scanner:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter firstNumber");
double firstNumber = scanner.nextDouble();
System.out.println("Enter secondNumber");
double secondNumber = scanner.nextDouble();
TwoNumbers obj = new TwoNumbers(firstNumber, secondNumber);
//Call methods from TwoNumbers
}
Really the code would work if you put the scanner in the main class or in the TwoNumbers class. The best practice way of doing this would be to place your scanner and any other input/output code in you main class, and the processing/calculation code in another class. Which one you choose will be based on your application, but most of the time you will have the scanner in the main class. So...
public class Driver {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s;
while((s = in.nextLine()) != "stop"){
TwoNumbers.sum(Double.parseDouble(s.split(" ")[0]), Double.parseDouble(s.split(" ")[1]));
}
in.close();
}
}
public class TwoNumbers{
public static double sum(double a, double b){
return a+b;
}
}
}

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.

Categories

Resources