I have a problem with my code, whenever I try to make a Tester Class, the code won't compile( my guess is that they are not linking with each other). However when they are not in tester form, they work perfectly.
Here is my code:
import java.io.*;
import java.util.*;
public class DistToline {
public static double A;
public static double B;
public static double C;
public static double distance;
public static double
getDist(double a, double b){
distance= Math.abs(((A*a)+(B*b)+(C))/(Math.pow(A, 2))+(Math.pow(B, 2)));
return distance;
}
public static void main(String args[])
{
Scanner f= new Scanner(System.in);
System.out.print("Enter the A value for the line:");
A = f.nextDouble();
Scanner g= new Scanner(System.in);
System.out.print("Enter the B value for the line:");
B = g.nextDouble();
Scanner h= new Scanner(System.in);
System.out.print("Enter the C value for the line:");
C = h.nextDouble();
Scanner i= new Scanner(System.in);
System.out.print("Enter the x coordinate of the point:");
Double X = i.nextDouble();
Scanner j= new Scanner(System.in);
System.out.print("Enter the y coordinate of the point:");
Double Y = j.nextDouble();
System.out.print("Distance from the point to the line is: ");
System.out.println(getDist(2.17, -4));
}
}
That is my full code, however when I make a Tester class, the codes are not linking with each other. I think this is because I haven't declared yet.
Here is my attempt on creating a Tester Class-
Tester:
class Tester{
public static void main(String args[])
{
Scanner f= new Scanner(System.in);
System.out.print("Enter the A value for the line:");
A = f.nextDouble();
Scanner g= new Scanner(System.in);
System.out.print("Enter the B value for the line:");
B = g.nextDouble();
Scanner h= new Scanner(System.in);
System.out.print("Enter the C value for the line:");
C = h.nextDouble();
Scanner i= new Scanner(System.in);
System.out.print("Enter the x coordinate of the point:");
Double X = i.nextDouble();
Scanner j= new Scanner(System.in);
System.out.print("Enter the y coordinate of the point:");
Double Y = j.nextDouble();
System.out.print("Distance from the point to the line is: ");
System.out.println(getDist(2.17, -4));
}
}
Class:
import java.io.*;
import java.util.*;
public class DistToline {
public static double A;
public static double B;
public static double C;
public static double distance;
public static double
getDist(double a, double b){
distance= Math.abs(((A*a)+(B*b)+(C))/(Math.pow(A, 2))+(Math.pow(B, 2)));
return distance;
}
The code is not stating any variables and they aren't even linking with each other. Is this because they are not declared? If so how would I fix it so that they are linking with each other?
The problem is due to the fact that your getDist() function is inside the DistToline class, but your mainline (void main()) is in the Tester class. You need to invoke the getDist() function by explicitly specifying the class it's in, as follows:
System.out.println(DistToline.getDist(2.17, -4));
Note this works because getDist() is declared as static. If getDist() were non-static, you would have to instantiate the DistToline class and call the function from the instance.
In your mainline you will also need to reference the variables A, B, and C the same way:
DistToline.A = f.NextDouble();
This is because they are static members of the DistToline class.
One more thing, although this won't affect the result: your public static distance variable can and should be moved into the getDist() function, as it doesn't need to be a static. Although you can just eliminate it altogether, and return the result of Math.abs directly:
public static double
getDist(double a, double b){
return Math.abs(((A*a)+(B*b)+(C))/(Math.pow(A, 2))+(Math.pow(B, 2)));
}
Related
I recently made a simple calculator that calculates the perimeter and area of a rectangle when you give it the measurements of two sides. However, two of my lines of System.out.println are not working. How can I fix this?
Here is the code:
import java.util.Scanner;
class Rectangle
{
static int n;
static int m;
Scanner s= new Scanner(System.in);
//The below two System.out.println lines do not work. How do I fix this?
System.out.println("Enter the width:")
n = s.nextInt();
System.out.println("Enter the length:");
m = s.nextInt();
public static void main(String args[])
{
int Area;
Area=n*m;
System.out.println("Area = " + Area);
return;
}
private static int solvePerimeter;
{
int Perimeter;
Perimeter = 2*(m+n);
System.out.println("Perimeter = " + Perimeter);
Print statements should be inside a function.
Change your code to :
import java.util.Scanner;
class Rectangle
{
static int n;
static int m;
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the width:")
n = s.nextInt();
System.out.println("Enter the length:");
m = s.nextInt();
}
You also need to declare two separate functions for area and perimeter and call from main method.
Your System.out.println("Enter the width:"); should be inside a method. Other than any variable declaration, everything should be inside methods.
import java.util.Scanner;
class Rectangle
{
static int n;
static int m;
Scanner s= new Scanner(System.in);
//The below two System.out.println lines do not work. How do I fix this?
public void readArguments() {
System.out.println("Enter the width:");
n = s.nextInt();
System.out.println("Enter the length:");
m = s.nextInt();
}
public static void main(String args[])
{
int Area;
readArguments();
Area=n*m;
System.out.println("Area = " + Area);
return;
}
private static int solvePerimeter;
{
int Perimeter;
Perimeter = 2*(m+n);
System.out.println("Perimeter = " + Perimeter);
I have 2 methods in Java.
In the first method, I am asking the user to make a choice, then i want to store this choice for using in the future.
The second method I wrote only to call the first one to use this choice.
Now, I want to use this variable and add it into an ArrayList. Is it possible to do it?
public static void letUserChooseAgain () {
System.out.println("Please choose an option (1/2):");
System.out.println("1. Dollars to Pounds");
System.out.println("2. Pounds to Dollars");
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
userChoiceToRemember(userChoice);
}
public static void userChoiceToRemember (double number) {
double remember = number;
}
I belive, I understood your requirement properly if it is kindly find the source code
It can be proposed in two different approach:
APPROACH 1
import java.util.ArrayList;
static ArrayList < Double > numbers = new ArrayList < Double > ();
public static void letUserChooseAgain ()
{
System.out.println ("Please choose an option (1/2):");
System.out.println ("1. Dollars to Pounds");
System.out.println ("2. Pounds to Dollars");
Scanner scanner = new Scanner (System.in);
double userChoice = scanner.nextDouble ();
numbers.add (userChoice);
userChoiceToRemember (userChoice);
}
public static void userChoiceToRemember (double number)
{
double remember = number;
System.out.println ("Remembered User Choice :" + numbers.get (0));
}
APPROACH 2
import java.util.ArrayList;
static ArrayList < Double > numbers = new ArrayList < Double > ();
public static void letUserChooseAgain ()
{
System.out.println ("Please choose an option (1/2):");
System.out.println ("1. Dollars to Pounds");
System.out.println ("2. Pounds to Dollars");
Scanner scanner = new Scanner (System.in);
double userChoice = scanner.nextDouble ();
userChoiceToRemember (userChoice);
}
public static void userChoiceToRemember (double number)
{
double remember = number;
numbers.add (remember);
System.out.println ("Remembered User Choice :" + numbers.get (0));
}
I hope the above code will help you, have a nice day !!
If i understand you right you want to safe the number in a array like this?
Array<Double> numbers = new Array<>();
public static void letUserChooseAgain () {
System.out.println("Please choose an option (1/2):");
System.out.println("1. Dollars to Pounds");
System.out.println("2. Pounds to Dollars");
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
userChoiceToRemember(userChoice);
}
public static void userChoiceToRemember (double number) {
double remember = number;
numbers.add(number);
}
You need to create a data structure that will keep the value that needs to be shared . Normally, it is done by defining a class that have members that keep the data needed by the class and methods that can access and change the members. This simple java class with members and accessor methods is called Java Bean.
Another option in your case is to have a static variable of type ArrayList<Double> to keep user choices.
I would go for a simple class that keeps user choices with a ArrayList<Double> member. An additional class would be the one that controls the flow of your program using the input provided by the user.
In your main class - the entry point to your program you woould need to instantiate both the class that controls the flow and the one that stores the user choices.
Either give it an ArrayList to add to:
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
ArrayList<Double> myArrayList = new ArrayList<Double>()
userChoiceToRemember(userChoice, myArrayList);
}
public static void userChoiceToRemember (double number, ArrayList<Double> anArrayList) {
anArrayList.add(number);
}
Have the method create it's own
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
ArrayList<Double> userChoiceInList = userChoiceToRemember(userChoice);
}
public static ArrayList<Double> userChoiceToRemember (double number, ArrayList<Double> anArrayList) {
ArrayList<Double> myArrayList = new ArrayList<Double>()
myArrayList.add(number);
return myArrayList;
}
or add it to the ArrayList outside of the loop
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
double userChoice = scanner.nextDouble();
ArrayList<Double> myArrayList = new ArrayList<Double>()
myArrayList.add(userChoiceToRemember(userChoice));
}
public static void userChoiceToRemember (double number) {
return number;
}
That's assuming there's a good reason you can't just:
public static void letUserChooseAgain () {
Scanner scanner = new Scanner(System.in);
ArrayList<Double> myArrayList = new ArrayList<Double>()
myArrayList.add(scanner.nextDouble());
}
I am trying to call a method that has a value that comes from a different method but modified. Here is the code:
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int num;
System.out.println("Please enter an integer");
num = in.nextInt();
System.out.println(Multiply(num));
System.out.println(Multiply2(x));
}
public static int Multiply(int num){
int x = num*2;
return x;
}
public static int Multiply2(int x){
int val = x*2;
return val;
}
}
I know I have to declare x inside of main but then I have to initialize it but I want the value of x to equal to the one that equals to the Multiply2 method which multiplies the num from the method, Multiply, by 2. x would be equal to num multiplied by 2; How am I able to do this?
Your methods are exactly the same
The name of the variable doesn't matter. Wheter its called x or val, it makes no difference.
With that in mind, if you want x to be the value returned from your Multiply function, just store that in a variable and use it later. For instance,
int someValue = Multiply(num);
System.out.println(someValue);
System.out.println(Multiply2(someValue));
PS: By convention, we don't capitalize methods names. So they should be multiply and multiply2
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int num;
System.out.println("Please enter an integer");
num = in.nextInt();
System.out.println(Multiply(num));
System.out.println(Multiply2(Multiply(num)));
}
public static int Multiply(int num) {
int x = num * 2;
return x;
}
public static int Multiply2(int x) {
int val = x * 2;
return val;
}
}
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;
}
}
}
I want the program to accept operation signs (+, -, * ,/) as input. Whenever I do that it throws an exception. Can anybody help me fix this problem and make the program accept one of these signs as input.
import java.lang.*;
import java.util.*;
public class Calculator
{
private double solution;
private static double x, y;
private static char ops;
public static interface Calculate
{
public abstract double operation(double x, double y);
}
public static class addition implements Calculate
{
public double operation(double x, double y){
return(x+y);
}
}
public static class subtraction implements Calculate
{
public double operation(double x, double y){
return(x-y);
}
}
public static class multiplication implements Calculate
{
public double operation(double x, double y){
return(x*y);
}
}
public static class division implements Calculate
{
public double operation(double x, double y){
return(x/y);
}
}
public void calc(int ops){
Scanner operands = new Scanner(System.in);
System.out.println("operand 1: ");
x = operands.nextDouble();
System.out.println("operand 2: ");
y = operands.nextDouble();
System.out.println("Solution: ");
Calculate [] jumpTable = new Calculate[4];
jumpTable['+'] = new addition();
jumpTable['-'] = new subtraction();
jumpTable['*'] = new multiplication();
jumpTable['/'] = new division();
solution = jumpTable[ops].operation(x, y);
System.out.println(solution);
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 0 for Addition");
System.out.println(" Enter 1 for Subtraction");
System.out.println(" Enter 2 for Multiplication");
System.out.println(" Enter 3 for Division");
Scanner operation = new Scanner(System.in);
ops = operation.next().charAt(0);
Calculator calc = new Calculator();
calc.calc(ops);
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at Calculator.calc(Calculator.java:54)
at Calculator.main(Calculator.java:76)
jumpTable['+']
will be translated to the ASCII code (43) of the + sign (it's converted to a char), leaving you with a number out of the 0-4 range. You probably want to use actual numeric indices (or make sure your array can contain the highest numerical representation for your set of char values, in this case 47 by /).
ASCII table:
You can only reference jumpTable by 0..3 indices. But you're trying to reference it by '+' sign which is beyond this scope. Consider using HashMap<String, Calculate> for storing operations in such way:
Map<String, Calculate> jumpTable = new HashMap<String, Calculate>();
jumpTable.put("+", new addition());
jumpTable.put("-", new subtraction());
jumpTable.put("*", new multiplication());
jumpTable.put("/", new division());
String operation = Character.toString((char) ops);
solution = jumpTable.get(operation).operation(x, y);