Constructor doesn't initialize proper values [duplicate] - java

This question already has answers here:
Adding char and int
(7 answers)
Closed 3 years ago.
I am a newcomer to Java, and in my code attached bellow I have 2 classes, Start.java and ecuație.java. ecuatie.java calculates the square footage of a quadratic ecuation, but for some reason, the constructor doesn't initialize the values properly. Could you shed some light on me as to why does this happen?
package com.ecuatie;
import com.ecuatie.ecuatie;
public class Start {
public static void main(String[] args) {
ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);
System.out.println(exemplu.delta() + '\n');
System.out.println(exemplu.X1() + '\n');
System.out.println(exemplu.X2() + '\n');
}
}
package com.ecuatie;
import java.lang.Math;
public class ecuatie {
private double a = 0, b = 0, c = 0;
ecuatie(double a, double b, double c) {
this.a = a; this.b = b; this.c = c;
}
public double delta() {
return (b * b) - (4 * a * c);
}
public double X1() {
return (-b + Math.sqrt(delta())) / (2 * a);
}
public double X2() {
return (-b - Math.sqrt(delta())) / (2 * a);
}
}

You're getting that because it's adding the ASCII value of the char.
ASCII value for '\n' is 10. so is is like you + exemplu.delta() with 10.
also you don't need add enter while you are using println().
so you just need to write your code like this.
public static void main(String[] args) {
ecuatie exemplu = new ecuatie(1.0d, 0.0d, -4.0d);
System.out.println(exemplu.delta() );
System.out.println(exemplu.X1() );
System.out.println(exemplu.X2() );
}

Related

How to pass the value of variables from main class to another class?

Hello everyone I'm currently creating a simple program. I have 2 classes the first one is calculator and the second one is parameters_return. What I want to happen is that when I read the values of x and y in my second class i want to use them in my first class Unfortunately, I can't run the program because it has an error. The code is below please help me with regards to this matter. I'm just self studying I really want to learn Java.
Code in (first class) calculator class is:
class calculator {
//with parameters with return type
int add(int a, int b) {
return (a + b);
}
//with parameters without return type
void sub(int a, int b) {
System.out.print(a - b);
}
//without parameters with return type
int mul() {
parameters_return s1 = new parameters_return();
int c = (s1.x) * (s1.y);
return c;
}
//without parameters without return type
void div() {
parameters_return s2 = new parameters_return();
int c = (s2.x) / (s2.y);
System.out.println("Division = " + c);
}
}
Code in my (second class) parameters_return class is:
class parameters_return {
int x, y;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
y = sc.nextInt();
calculator perform = new calculator();
//addition
int z = perform.add(x, y);
System.out.println("Added value = " + z);
//subtraction
System.out.println("Subtracted value = ");
perform.sub(x, y);
//multiplication
z = perform.mul();
System.out.println("Multiplication value = ");
//division
perform.div();
}
}
Is there any way to get values from main class and can be used in another class?
import java.util.*;
class ParametersReturn {
static int x, y;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
y = sc.nextInt();
Calculator perform = new Calculator();
//addition
int z = perform.add(x, y);
System.out.println("Added value = " + z);
//subtraction
System.out.println("Subtracted value = ");
perform.sub(x, y);
//multiplication
z = perform.mul();
System.out.println("Multiplication value = " + z);
//division
perform.div();
}
}
This should be your ParametersReturn Class and make sure you should start your class name with capital letter , you are using Scanner class to use it you have to import java.util package. And to use these variables in Calculator class make these variables static
class Calculator {
//with parameters with return type
int add(int a, int b) {
return (a + b);
}
//with parameters without return type
void sub(int a, int b) {
System.out.print(a - b);
}
//without parameters with return type
int mul() {
ParametersReturn s1 = new ParametersReturn();
int c = (s1.x) * (s1.y);
return c;
}
//without parameters without return type
void div() {
ParametersReturn s2 = new ParametersReturn();
int c = (s2.x) / (s2.y);
System.out.println("Division = " + c);
}
}
And in multiplication you forgot to print the value of z

(java.lang.StackOverflowError) how do i solve it? [duplicate]

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.

Actual and formal parameters

I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.

Quick sort not sorting array [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
I have the following code:
public class Main {
static void swap (Integer x, Integer y) {
Integer t = x;
x = y;
y = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
swap(a, b);
System.out.println("a=" + a + " b=" + b);
}
}
I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?
This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )
To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)
Thing tmp = a;
a = b;
b = tmp;
Everything in Java is passed by value and the values of variables are always primitives or references to object.
If you want to implement a swap method for Integer objects, you have to wrap the values into an array (or ArrayList) and swap inside the array. Here's an adaptation of your code:
public class Main {
static void swap (Integer[] values) {
if ((values == null) || (values.length != 2)) {
throw new IllegalArgumentException("Requires an array with exact two values");
}
Integer t = values[0];
values[0] = values[1];
values[1] = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] integers= new Integer[]{a,b};
swap(integers);
System.out.println("a=" + integers[0] + " b=" + integers[1]);
}
}
(Just added this answer because Svish mentioned, that "You can't really make a swap method in Java" fg)
As Svish and others pointed out it it's call by value, not by reference in Java. Since you have no pointers in Java you need some kind of holder object to really swap values this way. For example:
static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) {
Integer c = a.get();
a.set(b.get());
b.set(c);
}
public static void main(String[] args) {
AtomicReference<Integer> a = new AtomicReference<Integer>(1);
AtomicReference<Integer> b = new AtomicReference<Integer>(2);
System.out.println("a = " + a);
System.out.println("b = " + b);
swap(a, b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
You would need to pass the parameters by reference, which it's not possible in java. Also Integers are inmutables, so you cannot exchange the values as you don't have a setValue method.
Integer are immutable - you can't change their values. The swapping that occurs inside the swap function is to the references, not the values.
You would need to return both references in an array to achieve what you want
static Integer[] swap(Integer a, Integer b) {
return new Integer[]{b, a};
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] intArray = swap(a, b);
a = intArray[0];
b = intArray[1];
System.out.println("a=" + a + " b=" + b);
}
If Integer had a setValue method, you could do something like this.
static void swap(Integer a, Integer b) {
int temp = a.intValue();
a.setValue(b.intValue());
b.setValue(temp);
}
But it doesn't - so to achieve what you want, return an array.
Using the XOR operator is a very bad idea:
First, it is far less readable. Second, there were times when this was faster but nowadays the opposite is the case. See
Wikipedia
for reference.
As all the guys mentioned its a Pass-By-Value thing.
Just liked to add: you can use this method of swapping GLOBAL integers.
private void swap (){
a ^= b;
b ^= a;
a ^= b;
}
It eliminates the use of another variable, and its just cooler :)
Java code:
class swap {
int n1;
int n2;
int n3;
void valueSwap() {
n3 = n1;
n1 = n2;
n2 = n3;
}
public static void main(String[] arguments) {
Swap trial = new Swap();
trial.n1 = 2;
trial.n2 = 3;
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
trial.valueSwap();
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
}
}
Output:
trial.n1 = 2
trial.n2 = 3
trial.n1 = 3
trial.n2 = 2
Using Scanner:
import java.util.*;
public class Swap {
public static void main(String[] args){
int i,temp,Num1,Num2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Number1 and Number2");
Num1=sc.nextInt();
Num2=sc.nextInt();
System.out.println("Before Swapping Num1="+Num1+" Num2="+Num2);
temp=Num1;
Num1=Num2;
Num2=temp;
System.out.println("After Swapping Num1="+Num1+" Num2="+Num2);
}
}

JAVA - Use functional interface for calculations

So... this is my first post here on Stack and i'm also new into Java (into programming at all). I'm trying to make a simple commandline app that will calculate employees' profit depending of generated income. Already did it but as i'm learning functional interfaces and lambdas right now, i'd like to try use them. Down below you can find the code.
package BalanceCounter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of employees: ");
int empCounter = input.nextInt();
System.out.println();
List<Employee> employees = new ArrayList<>(empCounter);
for (int i = 0; i < empCounter; i++) {
employees.add(new Employee());
}
for (Employee employee : employees) {
System.out.println("Employee: " + employee.getEmpName()
+ "\nBase salary: " + employee.getEmpBaseSalary()
+ "\nProfit from income: " + employee.getEmpBonus()
+ "\n");
}
}
}
Here's Employee class with getEmpBonus() method in comment block. That's where i've tried to use functional interfaces.
package BalanceCounter;
import java.util.Scanner;
class Employee {
private String empName;
private double empBaseSalary;
private double empIncome;
private double empBonus;
Employee() {
Scanner input = new Scanner(System.in);
System.out.print("Employees name: ");
setEmpName(input.nextLine());
System.out.print("Type basic salary: ");
setEmpSalary(input.nextDouble());
System.out.print("Generated income: ");
setEmpIncome(input.nextDouble());
setEmpBonus();
System.out.println();
}
/*
* Here are all the setters
*/
private void setEmpName(String empName) {
this.empName = empName;
}
private void setEmpSalary(double empBaseSalary) {
this.empBaseSalary = empBaseSalary;
}
private void setEmpIncome(double empIncome) {
this.empIncome = empIncome;
}
private void setEmpBonus() {
if (getEmpIncome() <= 10000)
empBonus = (getEmpIncome() * 3) / 100;
else if (getEmpIncome() > 10000 && getEmpIncome() <= 20000)
empBonus = (getEmpIncome() * 2) / 100;
else empBonus = (getEmpIncome() * 1) / 100;
}
/*
* Time for the getters
*/
String getEmpName() {
return empName;
}
double getEmpBaseSalary() {
return empBaseSalary;
}
private double getEmpIncome() {
return empIncome;
}
double getEmpBonus() {
return empBonus;
}
/*
* double getEmpBonus(Calculation calculation) {
* return empBonus = calculation.calculate(this.empBonus);
* }
*/
}
And the last thing is Calculation interface.
package BalanceCounter;
public interface Calculation {
double calculate(double arg);
}
class CalcBonus implements Calculation{
public double calculate(double empBonus) {
return empBonus;
}
}
Sorry for the long post but wanted to give you all informations i have.
Also if you see some mistakes and bad habits in my code - please let me know. Kind regards.
package training;
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
interface RealMath {
double operation(double a, double b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public double operateBinary(int a, int b, RealMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator cal = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
IntegerMath multiplication = (a, b) -> a * b;
RealMath division = (a, b) -> a / b;
System.out.println("Add: 40 + 22 = " +
cal.operateBinary(40, 22, addition));
System.out.println("Sub: 120 - 80 = " +
cal.operateBinary(120, 80, subtraction));
System.out.println("Mul: 12 * 12 = " +
cal.operateBinary(12, 12, multiplication));
System.out.println("Div: 478 / 12 = " +
cal.operateBinary(478, 12, division));
}
}
This interface :
public interface Calculation {
double calculate(double arg);
}
has the same contract that DoubleUnaryOperator :
#FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
...
}
So you don't really need to introduce a new interface for this.
You could use the built-in one.
But if you want to really stress on the name and or arguments of the method.
As a general way, look before whether built-in Functional Interfaces could not match to your requirement before creating it.
Suppose now you uncomment your method and you want to use this method :
double getEmpBonus(DoubleUnaryOperator calculation) {
return empBonus = calculation.applyAsDouble(this.empBonus);
}
Without lambda, you have to create a subclass or an anonymous class if you want to pass an implementation that doubles the bonus :
class DoubleBonus implements DoubleUnaryOperator {
public double applyAsDouble(double operand) {
return operand * 2;
}
}
The idea of the lambda is that you could inline the subclass with a lambda expression.
You could so invoke the method in this way :
double doubledBonus = getEmpBonus(empBonus->empBonus*2);
You don't need any longer of the subclass or an anonymous class.

Categories

Resources