This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am trying to make a command line calculator using Java, I have come up with the code below it works without the if-else ladder,but I can't make it work with if-else, during debugging I tried printing the "z" which is indeed add when the arguments are passed as java name 1 2 add, But I can't seem to trigger the id (z == "add"), please suggest what I am missing.
public class commandlinecal {
public static void main(String arg[])
{
int x = Integer.parseInt(arg[0]);
int y = Integer.parseInt(arg[1]);
String z = arg[2];
if (z == "add")
{
add(x,y);
}
else if (z == "sub")
{
sub(x,y);
}
else if (z=="mul")
{
mul(x,y);
}
else if(z=="div")
{
div(x,y);
}
}
public static void add(int x,int y)
{
int result = x + y;
System.out.println("The sum is" + " "+result);
}
public static void sub (int x,int y)
{
int result = x-y;
System.out.println("The sub is"+" "+result);
}
public static void mul (int x,int y)
{
int result = x * y;
System.out.println("The multiplication is"+" "+result );
}
public static void div (int x,int y)
{
float result = x / y;
System.out.println("The division is"+" "+result);
}
}
Use if (z.equals("add")) { ... } instead.
Related
This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 3 years ago.
my console doesn't seem to be showing any output on my projects, on some, it does at first. I am new to this so I don't understand it, this is an example of my code
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
}
public void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Replace your main method with the following code and it should work as you are expecting:
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
}
The reason why it didn't work for you is because you have missed to call the methods you have created in the class. I have added the following lines in the main method to complete that missing part:
TestAmazing t=new TestAmazing();
t.roomtemp();
t.bonusball();
t.currentpopulationofchina();
t.gameloadingstatus();
None of your methods are static, so you'll need to create an instance of your TestAmazing class, and call methods via your instance.
That might look something like:
public static void main(String args[]) {
TestAmazing test = new TestAmazing();
test.roomtemp();
test.bonusball();
// etc...
}
Comment from QA:
this worked thank you! do I have to always do this and put it in the
same place? – Joe Emery
Not necessarily. It depends on the requirements of your program. If all of your methods are STATIC then you don't need an instance of your class. In that case, then you'd simply call all of your methods directly from main, like this:
public class TestAmazing {
public static void main(String args[]) {
// Put your data type declarations below.
int count = 0;
double cost = 3.45;
char choice = 'x';
boolean goodChoice = true;
short lowest = '5';
// Put the code for your calculations in this method.
// temp in a room
roomtemp();
bonusball();
currentpopulationofchina();
gameloadingstatus()
}
public static void roomtemp() {
int person = 1;
int temp = 20 + (person);
System.out.println("the temperature in the room is" + temp);
}
// nunber of jackpot ball
public static void bonusball() {
int bonusball;
bonusball = (int) (Math.random() * 59);
System.out.println("the jackpot ball is " + bonusball);
// population of china
}
public static void currentpopulationofchina() {
// check whether a game is finished or not
long populationOfChina2017 = 1394200000;
long populationexpectedincreaseto2019 = 5840000;
long populationOfChina = populationOfChina2017 + populationexpectedincreaseto2019;
System.out.println("the population of china is" + populationOfChina);
}
// check where a game is finished or not
public static void gameloadingstatus() {
int gameLoading;
gameLoading = (int) (Math.random() * 100);
if (gameLoading == 100) {
System.out.println("game is ready");
} else {
System.out.println("game is not ready");
}
}
}
Notice how every method has static in its declaration.
This question already has answers here:
What is a StackOverflowError?
(16 answers)
Understanding recursion [closed]
(20 answers)
Closed 3 years ago.
i'm writing a program based on the Quadratic Equation everything looks good to me and there are not syntax or logical errors from what i see and also Eclipse isn't detecting any errors before running.
this is the output from the code:
Exception in thread "main" java.lang.StackOverflowError
at QuadraticEquation.getDiscriminant(QuadraticEquation.java:33)
note it continues like this for about 50 lines or so
public class QuadraticEquation {
private double a;
private double b;
private double c;
public QuadraticEquation() {
double a = 0;
double b = 0;
double c = 0;
}
public QuadraticEquation(double newA, double newB, double newC) {
a = newA;
b = newB;
c = newC;
}
public double discriminant1 = Math.pow(b, 2) - 4 * a * c;
public double discriminant2 = Math.pow(b, 2) - 4 * a * c;
public double getA() {
return getA();
}
public double getB() {
return getB();
}
public double getC() {
return getC();
}
public double getDiscriminant() {
double discriminant = (b * 2) - (4 * a * c);
return getDiscriminant();
}
public double getRoot1() {
double r1 = (-1*b) + Math.sqrt(discriminant1) / (2*a);
return getRoot1();
}
public double getRoot2() {
double r2 = (-1*b) - Math.sqrt(discriminant2) / (2*a);
return getRoot2();
}
public void setA(double newA1) {
a = newA1;
}
public void setB(double newB1) {
b = newB1;
}
public void setC(double newC1) {
c = newC1;
}
}
import java.util.Scanner;
public class TestEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
QuadraticEquation Quadratic = new QuadraticEquation();
System.out.println("Please enter the values of the following variables: ");
System.out.println("a: ");
Quadratic.setA(input.nextDouble());
System.out.println("b: ");
Quadratic.setB(input.nextDouble());
System.out.println("c: ");
Quadratic.setC(input.nextDouble());
if (Quadratic.getDiscriminant() < 0) {
System.out.println("The equation has the following roots:");
System.out.println("The first one is " + Quadratic.getRoot1());
System.out.println("The second one is " + Quadratic.getRoot2());
}
else if (Quadratic.getDiscriminant() == 0) {
System.out.println("The equation has one root:");
System.out.println(Quadratic.getRoot1());
}
else {
System.out.println("The equation has the no real roots");
return;
}
}
}
Your error is an infinite recursion here:
public double getDiscriminant() {
double discriminant = (b * 2) - (4 * a * c);
return getDiscriminant();
}
This function calls itself infinitely until the stack overflows. I believe you wanted to return the variable discriminant instead?
Same for your functions getRoot1, getRoot2, getA, getB, and getC.
I have written a polynomial class and a tester class. The polynomial class can evaluate and return the sum of the polynomial when the degree, coefficients and the value of x are provided. Basically I need to edit my toString method so it actually prints out the polynomial
import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
return sum;
}
/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;
}
}
This should be along the lines you should be proceeding. I included the main function in your Polynomial class for simplicity, so you will have to modify that if you want to keep it in your tester class. Notice that degree has been made into an integer array of size degree +1(allocated in the constructor):
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
}
public double getSum(){
return sum;
}
public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;
}
public static void main(String[] args) {
int degree;
double sum;
int coefficient;
Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();
Polynomial fun = new Polynomial(degree);
fun.Evaluate(3.0);
System.out.println(" The sum of the polynomial is " + fun.getSum());
System.out.println(fun);
}
}
The usual way of making the objects of a class printable is to supply a toString method in the class, which specifies how to express objects of that class as a String. Methods such as println and other ways of outputting a value will call a class's toString method if they need to print an object of that class.
You should adopt the same pattern with your Polynomial class - write a toString method with all the output logic. Then in your PolynomialTester class, all you need to write is System.out.println(fun); and the rest will just happen. You'll find this far more versatile than writing a method that actually does the printing. For example, you'll be able to write something like
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");
if that's your idea of fun.
A few other things concern me about your class.
You seem to be only storing one coefficient and one exponent. I'd expect a polynomial to have a whole array of coefficients.
You have fields for evaluation and sum - but these only really make sense while a polynomial is being evaluated. They're not long-term properties of the polynomial. So don't store them in fields. Have them as local variables of the evaluate method, and return the result of the evaluation.
I'd expect a class like this to be immutable. That is, you should provide all the coefficients when the object is created, and just never change them thereafter. If you do it that way, there's no need to write setter methods.
So I've written my own version of your class, that fixes those issues listed above, and implements a toString method that you can use for printing it. A second version of toString lets you specify which letter you want to use for x. I've used "varargs" in the constructor, so you can construct your polynomial with a line such as
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
specifying the coefficients from the constant term through in order to the coefficient of the term with the highest exponent. Or you can just pass an array.
See that I've changed the logic a wee bit - my version prints the polynomial in the conventional order, from highest to lowest exponent. It leaves off the decimals if the coefficient is an integer. It doesn't print a 1 in front of an x. And it deals cleanly with - signs.
import java.util.Arrays;
public class Polynomial {
private double[] coefficients;
public Polynomial(double... coefficients) {
this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
}
public int getDegree() {
int biggestExponent = coefficients.length - 1;
while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
biggestExponent--;
}
return biggestExponent;
}
public double getCoefficient(int exponent) {
if (exponent < 0 || exponent > getDegree()) {
return 0.0;
} else {
return coefficients[exponent];
}
}
public double evaluateAt(double x) {
double toReturn = 0.0;
for (int term = 0; term < coefficients.length; term++) {
toReturn += coefficients[term] * Math.pow(x, term);
}
return toReturn;
}
#Override
public String toString() {
return toString('x');
}
public String toString(char variable) {
boolean anythingAppendedYet = false;
StringBuilder toReturn = new StringBuilder();
for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
if (coefficients[exponent] != 0.0) {
appendSign(toReturn, exponent, anythingAppendedYet);
appendNumberPart(toReturn, exponent);
appendLetterAndExponent(toReturn, exponent, variable);
anythingAppendedYet = true;
}
}
if (anythingAppendedYet) {
return toReturn.toString();
} else {
return "0";
}
}
private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
if (coefficients[exponent] < 0) {
toAppendTo.append(" - ");
} else if (anythingAppendedYet) {
toAppendTo.append(" + ");
}
}
private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
double numberPart = Math.abs(coefficients[exponent]);
if (numberPart != 1.0 || exponent == 0) {
//Don't print 1 in front of the letter, but do print 1 if it's the constant term.
if (numberPart == Math.rint(numberPart)) {
// Coefficient is an integer, so don't show decimals
toAppendTo.append((long) numberPart);
} else {
toAppendTo.append(numberPart);
}
}
}
private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
if (exponent > 0) {
toAppendTo.append(variable);
}
if (exponent > 1) {
toAppendTo.append("^");
toAppendTo.append(exponent);
}
}
}
So I tested it with this class
public class PolynomialTester {
public static void main(String[] args) {
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
System.out.println(fun.getDegree());
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
}
}
and the output was
4
139.0
x^4 + 5x^2 + 2x + 7
then I realised that you wanted to be able to input the coefficients in a loop. So I changed PolynomialTester to this. See how I build the array and then create the object.
import java.util.Scanner;
public class PolynomialTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the degree:");
int degree = input.nextInt();
double[] coefficients = new double[degree + 1];
for( int exponent = 0; exponent <= degree; exponent++) {
System.out.println("Enter the coefficient of x^" + exponent);
coefficients[exponent] = input.nextDouble();
}
Polynomial fun = new Polynomial (coefficients);
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
input.close();
}
}
Note that if you really want your polynomial to be printed in "reverse" order, with the constant term first, you could change the loop in the toString method to this.
for (int exponent = 0; exponent < coefficients.length; exponent++) {
You may add a class member String poly, then modify the following method.
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient= key.nextInt();
evaluation = Math.pow(value, i)*coefficient ;
this.sum += evaluation;
this.poly = "";
if(coefficient != 0)
{
if(i > 0)
{
this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
}
else
{
this.poly = Integer.toString(coefficient)
}
}
}
}
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 7 years ago.
I want to be able to store and manage ordered pairs of the
form: (x, y). To solve this problem I created two classes: EuclideanSpace and Point. This is a homework assignment and so it is set up with these specific methods and the class EuclideanSpace and the inner class Point. I thought I had it almost figured out but when I run it it prints out '0' for the x and the y values after the first entry. For every entry after that it prints 'null'.
import java.util.Scanner;
public class EuclideanSpace {
Point point[];
Scanner scanner = new Scanner(System.in);
public EuclideanSpace() {
point = new Point[10];
}// End constructor
// Adds points to the array
public boolean addPoint(int x, int y) {
for (int i = 0; i < 10; i++) {
if (point[i] == null) {
point[i] = new Point();
}// End if
return true;
}// End for
return false;
}// End addPoint
// Prints a point in a given index in the point array
public void printPoint(int i) {
System.out.println(point[i]);
}
// Inner class
public static class Point {
private int x;
private int y;
public void Point(int x, int y) {
this.x = x;
this.y = y;
}// End Point method
public String toString() {
return "X = " + x + "Y = " + y;
}// End toString
}// End inner Class
}// End
Driver class:
import java.awt.Point;
import java.util.Scanner;
public class ICDriver {
static Scanner scanner = new Scanner(System.in);
// New object from the class EuclideanSpace
static EuclideanSpace es = new EuclideanSpace();
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Add point x coordinate? ");
int pointX = scanner.nextInt();
System.out.println("Add point y coordinate? ");
int pointY = scanner.nextInt();
es.addPoint(pointX, pointY);
es.printPoint(i);
} // End for
}// End main
}// End
// Correct your addPoint method
public boolean addPoint(int x, int y) {
for (int i = 0; i < 10; i++) {
if (point[i] == null) {
point[i] = new Point(x,y);
return true;
}// End if
}// End for
return false;
}// End addPoint
//Remove void from your constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
The Program I'm trying to make is supposed to draw a Polygon using points stored in an ArrayList. I rechecked the code and I am also using the driver, but when I try to run the program, it gives me a NullPointerException when I try to add coordinates for the program to use when drawing.
import java.awt.geom.*;
import java.util.ArrayList;
import gpdraw.*;
public class IrregularPolygon
{
private ArrayList <Point2D.Double> myPolygon;
DrawingTool myPen;
SketchPad myPaper;
double dblPerimeter;
double dblSegment;
double dblArea;
public IrregularPolygon()//Creating the sketchpad and pen
{
myPaper = new SketchPad(500,500);
myPen = new DrawingTool(myPaper);
}
public void add(Point2D.Double aPoint)//Adds to the array
{
myPolygon.add(aPoint);// This is where the problem is I think, I don't know what to do
}
public void draw()//This method draws the polygon
{
for(int x = 0; x < myPolygon.size() - 1 ; x++)
{
myPen.down();
myPen.move(myPolygon.get(x).getX(),myPolygon.get(x).getY());
myPen.up();
}
}
public double perimeter()//This method finds the perimeter
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
dblPerimeter += myPolygon.get(x).distance(myPolygon.get(x+1));
}
return dblPerimeter;
}
public double area()//This method finds the area
{
for(int x = 0; x < myPolygon.size() - 1; x++)
{
double X1 = (myPolygon.get(x).getX());
double Y1 = (myPolygon.get(x).getY());
double X2 = (myPolygon.get(x + 1).getX());
double Y2 = (myPolygon.get(x + 1).getY());
dblArea += (X1 * Y2 - Y1 * X2);
}
return dblArea;
}
}
and the programs runs from this driver:
import java.util.*;
import java.awt.geom.Point2D;
public class IrregularPolygonDriver
{
static boolean blnReadyToDraw = false;
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
int num;
IrregularPolygon poly = new IrregularPolygon();
while(blnReadyToDraw == false)
{
System.out.println("Would you like to add a point, find the perimeter, or calculate the area?");
System.out.println("To add a point, enter 1; to find the perimeter, enter 2; to find the area, enter 3");
num = in.nextInt();
if(num == 1)
{
double dblNum1;
double dblNum2;
Point2D.Double dblNumber;
System.out.println("Enter an x value and a y value: ");
dblNum1 = in.nextDouble();
dblNum2 = in.nextDouble();
dblNumber = new Point2D.Double(dblNum1,dblNum2);
poly.add(dblNumber);
System.out.println("Keep adding points until you are done drawing the figure.");
}
else if(num == 2)
{
poly.perimeter();
}
else if(num == 3)
{
poly.area();
}
else
{
blnReadyToDraw = true;
System.out.println("Preparing to Draw");
}
}
poly.draw();
}
}
This is happening because your myPolygon is null.
Change:
private ArrayList <Point2D.Double> myPolygon;
To this:
private ArrayList <Point2D.Double> myPolygon = new ArrayList<>();
Or, in your constructor, add this line:
myPolygon = new ArrayList<>();
You didn't initialize your ArrayList,
private ArrayList <Point2D.Double> myPolygon;
is equivalent to
private ArrayList <Point2D.Double> myPolygon = null;
so when you say
myPolygon.add(aPoint); // <-- null.add(aPoint);
You could assign it in the constructor, or at declaration (using the List interface and the diamond operator <>) with something like
private List<Point2D.Double> myPolygon = new ArrayList<>();