Java Double Math - java

So I, have this code to trace and I had the results of 2.25 and 2.75. But when I compile it, I get 1.5 and 2.0. Why is that? Do the parentheses have anything to do with that?
public class TraceClass {
private double valBefore;
private double valAfter;
public TraceClass(double valIn) {
this.valBefore = valIn;
this.valAfter = 0.0;
}
public void doIt(boolean which){
if (which == true) {
this.valAfter = ((int) this.valBefore) + .5;
}
else {
this.valAfter = (int) (this.valBefore + .5);
}
}
public double getValAfter(){
return this.valAfter;
}
}
public class MainClass {
public static void main(String[] args) {
TraceClass traceObj = new TraceClass(1.75);
traceObj.doIt(true);
double temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
traceObj.doIt(false);
temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
}
}
edit: this is code that my teacher gave out ask practice for stack tracing. i got 2.25 because I added 1.75+.5= 2.25. But then I accidentally added .5 to 2.25 to get 2.75
edit2: typo

Both the parentheses and the casts to int affect the result, and the order matters.
For the true case, valBefore is casted to int first, yielding the integer value 1 (it is truncated). Then .5 is added, a double value, so 1 is widened to 1.0 and 1.5 results.
For the false case, valBefore is added to 0.5 first, and 1.5 + .5 is 2.0. Then that result is cased to int which yields 2. The assignment back to the double variable valAfter widens it back to double -- 2.0.

You are casting your variable to int for some strange reason which means you are adding 1 (integer part of 1.75) and 0.5 = 1.5 and in the second case you are casting the result of the addition to int so you get 1.5 + 0.5 = 2 (then casted to double again), so the second time you do not lose anything since the result happened to be an even integer.
Just remove all cast to int, it makes no sense when calculating with double values

When you cast the double value into an int, it just does not count the decimal parts. I just convert an int to double. you don't need to cast either.
import org.junit.jupiter.api.Test;
public class DoubleIssueStackOverflow {
#Test
public void test_first(){
TraceClass traceObj = new TraceClass(1.75);
traceObj.doIt(true);
double temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
traceObj.doIt(false);
temp = traceObj.getValAfter();
System.out.println("Result is " + temp);
}
public class TraceClass {
private double valBefore;
private double valAfter;
public TraceClass(double valIn) {
this.valBefore = valIn;
this.valAfter = 0.0;
}
public void doIt(boolean which) {
if (which == true) {
this.valAfter = this.valBefore + .5;
} else {
this.valAfter = this.valBefore + .5;
}
}
public double getValAfter() {
return this.valAfter;
}
}
}

Related

Why is this recursive method on guessing the square root of a user inputted number not working

For some reason I keep just getting error trying to compile this code, but it seems tat everything works, right?
import java.util.*;
public class squareRoot
{
public static void input(){
Scanner input = new Scanner (System.in);
double number = 16;
double root;
root = square(number);
System.out.println("Enter Guess");
double oldguess = input.nextDouble();
squareRoot(0, oldguess);
}
public static double square(double number){
double t;
double squareroot = number / 2;
do {
t = squareroot;
squareroot = (t + (number / t)) / 2;
} while ((t - squareroot) != 0);
return squareroot;}
public static double squareRoot(double newguess, double oldguess){
if (newguess == square(19)){
return newguess;
}
else{
newguess = (oldguess + (19/oldguess))/2;
System.out.println(newguess);
return squareRoot(newguess, oldguess);
}
}
}
Because oldguess is a constant. So after the first run through, this code produces the same result every time:
newguess = (oldguess + (19/oldguess))/2;
You need to cache the newguess at the start of the else, do your calculation and then replace oldguess with the cached value from newguess.
Like so:
public static double squareRoot(double newguess, double oldguess) {
double cache;
if (newguess == square(19)) {
return newguess;
} else {
cache = newguess;
newguess = (oldguess + (19 / oldguess)) / 2;
oldguess = cache;
System.out.println(newguess);
return squareRoot(newguess, oldguess);
}
}

Level Calculation with Java

I need to calculate a Level system for a friend of mine. The problem is that I have no clue how I should do that. He gave me a end point how much experience (31536000) is needed for the max level (44)
The level should increase in difficulty as higher you are (like degresive progression or logarithmic) I just have no clue how to calculate it backwards or even forward.
I am not that experience with Java since this is ages for me.
I need every experience needed for each level from 1 to 44 and you reach level 44 by earning 31536000 experience.
I have test some stuff but I am really not good at that and I know this is a little bit to high for me.
public class level{
public static final double base_exp = 1;
public static final double exp_increase_per_level = 0.40;
public static final int max_level = 44;
public static int level (double exp){
int i = 1;
double test_exp = base_exp;
while (i<max_level) {
if (test_exp > exp){
return i;
}
test_exp = test_exp + test_exp * exp_increase_per_level;
i++;
}
return max_level;
}
public static double level_to_exp (int level) {
if(level == 1)
return base_exp;
else {
double prev = level_to_exp(level-1);
return prev + prev * exp_increase_per_level;
}
}
public static double level_to_total_exp (int level) {
if(level == 1)
return base_exp;
else {
return level_to_total_exp(level-1) + level_to_exp(level-1) * (1 + exp_increase_per_level);
}
}
public static void main(String []args){
System.out.println("to level 1,"+level_to_exp(1)+"exp");
System.out.println("to level 2,"+level_to_exp(2)+"exp");
System.out.println("to level 44,"+level_to_exp(44)+"exp");
System.out.println("Total exp to level 44" +level_to_total_exp(44)+" acuumulated");
}
}
This is just basic maths. Your model appears to be:
score = base^level
So to get the level from the score:
log(score) = log(base^level) = level * log(base)
level = log(score) / log(base)
To calculate base, just substitute in level=44 and score=whatever, and rearrange.

compiler errors, I do not underdstand

I want to make it work to where I run ComplexTest.class and then in that class it runs Complex.class. I'm pretty new at java I have no idea what's wrong. Not sure why the compiler expects to see .class and a semi colon where it thinks they should be.
Main class
public class ComplexTest
{
//private final double re; // the real part
//private final double im; // the imaginary part
public static void main(String[] paramArrayOfString)
{
CreateObjs();
PrintHeader1();
PrintHeader2();
// invoke and Initialize a Complex object
Complex Comp = new Complex(); // Invokes Complex constructor (pg 315)
Comp.JunctionBox(CompA, CompB);
// multiply.printQuestionResult();
}
public static void CreateObjs()
{
Complex CompA = new Complex(9.5D, 7.7D);
Complex CompB = new Complex(1.2D, 3.1D);
}
public static void PrintHeader1()
{
System.out.printf(" A complex number in the \n form (x, y) is equal to \n x + yi, where i is \n square root of -1.\n");
}
public static void PrintHeader2()
{
System.out.printf("\n *-Complex numbers calculations-*");
}
}
2nd class
/******************************************************************************
* Data type for complex numbers.
*
* The data type is "imagmutable" so once you create and initialize
* a Complex object, you cannot change it. The "final" keyword
* when declaring re and imag enforces this rule, making it a
* compile-timage error to change the .re or .imag fields after
* they've been initialized.
*
* % java Complex
* a = 5.0 + 6.0i
* b = -3.0 + 4.0i
* b + a = 2.0 + 10.0i
* a - b = 8.0 + 2.0i
* a * b = -39.0 + 2.0i
* a / b = 0.36 - 1.52i
******************************************************************************/
public class Complex {
// Constants (final)
private final double re; // the real part
private final double imag; // the imaginaryinary part
// Variables
public double product;
// create a new object with the given real and imaginaryinary parts
public Complex(double real, double imaginary) {
re = real;
imag = imaginary;
}
// return a string representation of the invoking Complex object
public String toString() {
if (imag == 0) return "<" + re + ">";
if (re == 0) return "<" + imag + ">";
if (imag < 0) return "<" + re + " - " + (-imag) + ">";
return "<" + re + ", " + imag + ">";// + "i";
}
// return a new Complex object whose value is (this + b)
public Complex plus(Complex b) {
Complex a = this; // invoking object
double real = a.re + b.re;
double imaginary = a.imag + b.imag;
return new Complex(real, imaginary);
}
// return a new Complex object whose value is (this - b)
public Complex minus(Complex b) {
Complex a = this;
double real = a.re - b.re;
double imaginary = a.imag - b.imag;
return new Complex(real, imaginary);
}
// return a new Complex object whose value is (this * b)
public Complex timages(Complex b) {
Complex a = this;
double real = a.re * b.re - a.imag * b.imag;
double imaginary = a.re * b.imag + a.imag * b.re;
return new Complex(real, imaginary);
}
// return a new Complex object whose value is the reciprocal of this
public Complex reciprocal() {
double scale = re*re + imag*imag;
return new Complex(re / scale, -imag / scale);
}
// return the real or imaginaryinary part
public double re() { return re; }
public double imag() { return imag; }
// return a / b
public Complex divides(Complex b) {
Complex a = this;
return a.timages(b.reciprocal());
}
// sample client for testing
public static void main(String[] args) {
Complex a = new Complex(9.5, 7.7);
Complex b = new Complex(1.2, 3.1);
System.out.printf("a = %s\n", a);
System.out.println("b = " + b);
System.out.println("a + b = " + a.plus(b));
System.out.println("a - b = " + a.minus(b));
System.out.println("a * b = " + a.timages(b));
System.out.println("a / b = " + a.divides(b));
}
}
Compiler/Syntax errors:
ComplexTest.java:15: error: constructor Complex in class Complex cannot be applied to given types;
Complex Comp = new Complex(); // Invokes Complex constructor (pg 315)
^
required: double,double
found: no arguments
reason: actual and formal argument lists differ in length
ComplexTest.java:16: error: cannot find symbol
Comp.JunctionBox(CompA, CompB);
^
symbol: variable CompA
location: class ComplexTest
ComplexTest.java:16: error: cannot find symbol
Comp.JunctionBox(CompA, CompB);
^
symbol: variable CompB
location: class ComplexTest
3 errors
EDIT1: Fixed the junk class, updated the errors code block. I knew that the junk class was a problem.
EDIT2: I need more help, I am making more errors trying to fix the ones I already have.
You have a "junk" class declaration messing the file up.
public class JunctionBox() {
}
...is not a valid class declaration to begin with (the brackets should not be there), and you should only have a single public class declaration - with the class named as the file - in each Java file.
Removing that class declaration would make the file compile correctly.
The problem is due to having the concatenation of double and string you have to convert them first to string in every way possible
for example in the following way
change
if (imag == 0) return "<" + re + ">"
to
if (imag == 0) return "<" + String.valueOf(re) + ">"
Some errors are:
1) in the main method of ComplexTest you invoke the empty Constructor Complex() that you have not defined yet.
2) in the next line of code you use CompA and CompB object, but you have not defined them.
3) In the second file you first declare JunctionBox Class, but you put a main method method in a secodary class of the same file.
Correct first the above errors and the update you question.

Errors : Exception in thread "main" java.lang.Error: Unresolved compilation problems

I was watching a Java tutorial for beginners, and while writing the code I got a few errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, 'for each' statements are only available if source level is 1.5 or greater
Arrays cannot be resolved
Arrays cannot be resolved
Arrays cannot be resolved
at Animal.main(Animal.java:389)
My code is:
Animal.Java:
import java.util.Scanner;
// A class defines the attributes (fields) and capabilities (methods) of a real world object
public class Animal {
// static means this number is shared by all objects of type Animal
// final means that this value can't be changed
public static final double FAVNUMBER = 1.6180;
// Variables (Fields) start with a letter, underscore or $
// Private fields can only be accessed by other methods in the class
// Strings are objects that hold a series of characters
private String name;
// An integer can hold values from -2 ^ 31 to (2 ^ 31) -1
private int weight;
// Booleans have a value of true or false
private boolean hasOwner = false;
// Bytes can hold the values between -128 to 127
private byte age;
// Longs can hold the values between -2 ^ 63 to (2 ^ 63) - 1
private long uniqueID;
// Chars are unsigned ints that represent UTF-16 codes from 0 to 65,535
private char favoriteChar;
// Doubles are 64 bit IEEE 754 floating points with decimal values
private double speed;
// Floats are 32 bit IEEE 754 floating points with decimal values
private float height;
// Static variables have the same value for every object
// Any variable or function that doesn't make sense for an object to have should be made static
// protected means that this value can only be accessed by other code in the same package
// or by subclasses in other packages
protected static int numberOfAnimals = 0;
// A Scanner object allows you to except user input from the keyboard
static Scanner userInput = new Scanner(System.in);
// Any time an Animal object is created this function called the constructor is called
// to initialize the object
public Animal(){
// Shorthand for numberOfAnimals = numberOfAnimals + 1;
numberOfAnimals++;
int sumOfNumbers = 5 + 1;
System.out.println("5 + 1 = " + sumOfNumbers);
int diffOfNumbers = 5 - 1;
System.out.println("5 - 1 = " + diffOfNumbers);
int multOfNumbers = 5 * 1;
System.out.println("5 * 1 = " + multOfNumbers);
int divOfNumbers = 5 / 1;
System.out.println("5 / 1 = " + divOfNumbers);
int modOfNumbers = 5 % 3;
System.out.println("5 % 3 = " + modOfNumbers);
// print is used to print to the screen, but it doesn't end with a newline \n
System.out.print("Enter the name: \n");
// The if statement performs the actions between the { } if the condition is true
// userInput.hasNextLine() returns true if a String was entered in the keyboard
if(userInput.hasNextLine()){
// this provides you with a way to refer to the object itself
// userInput.nextLine() returns the value that was entered at the keyboard
this.setName(userInput.nextLine());
// hasNextInt, hasNextFloat, hasNextDouble, hasNextBoolean, hasNextByte,
// hasNextLong, nextInt, nextDouble, nextFloat, nextBoolean, etc.
}
this.setFavoriteChar();
this.setUniqueID();
}
// It is good to use getter and setter methods so that you can protect your data
// In Eclipse Right Click -> Source -> Generate Getter and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public boolean isHasOwner() {
return hasOwner;
}
public void setHasOwner(boolean hasOwner) {
this.hasOwner = hasOwner;
}
public byte getAge() {
return age;
}
public void setAge(byte age) {
this.age = age;
}
public long getUniqueID() {
return uniqueID;
}
// Method overloading allows you to accept different input with the same method name
public void setUniqueID(long uniqueID) {
this.uniqueID = uniqueID;
System.out.println("Unique ID set to: " + this.uniqueID);
}
public void setUniqueID() {
long minNumber = 1;
long maxNumber = 1000000;
// Generates a random number between 1 and 1000000
this.uniqueID = minNumber + (long)(Math.random() * ((maxNumber - minNumber) + 1));
// You can cast from one primitive value into another by putting what you want between ( )
// (byte) (short) (long) (double)
// (float), (boolean) & (char) don't work.
// (char) stays as a number instead of a character
// You convert from a primitive to a string like this
String stringNumber = Long.toString(maxNumber);
// Byte.toString(bigByte); Short.toString(bigShort); Integer.toString(bigInt);
// Float.toString(bigFloat); Double.toString(bigDouble); Boolean.toString(trueOrFalse);
// You convert from a String to a primitive like this
int numberString = Integer.parseInt(stringNumber);
// parseShort, parseLong, parseByte, parseFloat, parseDouble, parseBoolean
System.out.println("Unique ID set to: " + this.uniqueID);
}
public char getFavoriteChar() {
return favoriteChar;
}
public void setFavoriteChar(char favoriteChar) {
this.favoriteChar = favoriteChar;
}
public void setFavoriteChar() {
int randomNumber = (int) (Math.random() * 126) + 1;
this.favoriteChar = (char) randomNumber;
// if then else statement
// > < == != >= <=
if(randomNumber == 32){
System.out.println("Favorite character set to: Space");
} else if(randomNumber == 10){
System.out.println("Favorite character set to: New Line");
} else {
System.out.println("Favorite character set to: " + this.favoriteChar);
}
// Logical operators
// ! : Converts the boolean value to its right to its opposite form ie. true to false
// & : Returns true if boolean value on the right and left are both true (Always evaluates both boolean values)
// && : Returns true if boolean value on the right and left are both true (Stops evaluating after first false)
// | : Returns true if either boolean value on the right or left are true (Always evaluates both boolean values)
// || : Returns true if either boolean value on the right or left are true (Stops evaluating after first true)
// ^ : Returns true if there is 1 true and 1 false boolean value on the right or left
if((randomNumber > 97) && (randomNumber < 122)){
System.out.println("Favorite character is a lowercase letter");
}
if(((randomNumber > 97) && (randomNumber < 122)) || ((randomNumber > 64) && (randomNumber < 91))){
System.out.println("Favorite character is a letter");
}
if(!false){
System.out.println("I turned false to " + !false);
}
// The ternary operator assigns one or another value based on a condition
int whichIsBigger = (50 > randomNumber) ? 50 : randomNumber;
System.out.println("The biggest number is " + whichIsBigger);
// The switch statement is great for when you have a limited number of values
// and the values are int, byte, or char unless you have Java 7 which allows Strings
switch(randomNumber){
case 8 :
System.out.println("Favorite character set to: Backspace");
break;
case 9 :
System.out.println("Favorite character set to: Horizontal Tab");
break;
case 10 :
case 11 :
case 12 :
System.out.println("Favorite character set to: Something else weird");
break;
default :
System.out.println("Favorite character set to: " + this.favoriteChar);
break;
}
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
protected static int getNumberOfAnimals() {
return numberOfAnimals;
}
// Since numberOfAnimals is Static you must set the value using the class name
public void setNumberOfAnimals(int numberOfAnimals) {
Animal.numberOfAnimals = numberOfAnimals;
}
protected static void countTo(int startingNumber){
for(int i = startingNumber; i <= 100; i++){
// continue is used to skip 1 iteration of the loop
if(i == 90) continue;
System.out.println(i);
}
}
protected static String printNumbers(int maxNumbers){
int i = 1;
while(i < (maxNumbers / 2)){
System.out.println(i);
i++;
// This isn't needed, but if you want to jump out of a loop use break
if(i == (maxNumbers/2)) break;
}
Animal.countTo(maxNumbers/2);
// You can return a value like this
return "End of printNumbers()";
}
protected static void guessMyNumber(){
int number;
// Do while loops are used when you want to execute the code in the braces at least once
do {
System.out.println("Guess my number up to 100");
// If what they entered isn't a number send a warning
while(!userInput.hasNextInt()){
String numberEntered = userInput.next();
System.out.printf("%s is not a number\n", numberEntered);
}
number = userInput.nextInt();
}while(number != 50);
System.out.println("Yes the number was 50");
}
// This will be used to demonstrate polymorphism
public String makeSound(){
return "Grrrr";
}
// With polymorphism we can refer to any Animal and yet use overridden methods
// in the specific animal type
public static void speakAnimal(Animal randAnimal){
System.out.println("Animal says " + randAnimal.makeSound());
}
// public allows other classes to use this method
// static means that only a class can call for this to execute
// void means it doesn't return a value when it finishes executing
// This method can except Strings that can be stored in the String array args when it is executed
public static void main(String[] args){
Animal theDog = new Animal();
System.out.println("The animal is named " + theDog.getName());
System.out.println(Animal.printNumbers(100));
Animal.countTo(100);
Animal.guessMyNumber();
// An array is a fixed series of boxes that contain multiple values of the same data type
// How you create arrays
// int[] favoriteNumbers;
// favoriteNumbers = new int[20];
int[] favoriteNumbers = new int[20];
favoriteNumbers[0] = 100;
String[] stringArray = {"Random", "Words", "Here"};
// for(dataType[] varForRow : arrayName)
for(String word : stringArray)
{
System.out.println(word);
}
// This is a multidimensional array
String[][][] arrayName = { { { "000" }, { "100" }, { "200" }, { "300" } },
{ { "010" }, { "110" }, { "210" }, { "310" } },
{ { "020" }, { "120" }, { "220" }, { "320" } }};
for(int i = 0; i < arrayName.length; i++)
{
for(int j = 0; j < arrayName[i].length; j++)
{
for(int k = 0; k < arrayName[i][j].length; k++)
{
System.out.print("| " + arrayName[i][j][k] + " ");
}
}
System.out.println("|");
}
// You can copy an array (stringToCopy, indexes to copy)
String[] cloneOfArray = Arrays.copyOf(stringArray, 3);
// You can print out the whole array
System.out.println(Arrays.toString(cloneOfArray));
// Returns the index or a negative number
System.out.println(Arrays.binarySearch(cloneOfArray, "Random"));
}
}
Dog.Java
public class Dog extends Animal{
public Dog() {
}
// You can override Animal methods
public String makeSound(){
return "Woof";
}
public static void main(String[] args) {
Dog fido = new Dog();
fido.setName("Fido");
System.out.println(fido.getName());
}
}
Cat.java
public static void main(String[] args) {
Animal fido = new Dog();
Animal fluffy = new Cat();
// We can have an array of Animals that contain more specific subclasses
// Any overridden methods are used instead because of polymorphism
Animal[] theAnimals = new Animal[10];
theAnimals[0] = fido;
theAnimals[1] = fluffy;
System.out.println("Fido says " + theAnimals[0].makeSound());
System.out.println("Fluffy says " + theAnimals[1].makeSound());
// We can also pass subclasses of Animal and they just work
speakAnimal(fluffy);
}
}
I saw a few other answers here and read that I had to add import java.util.Scanner;
Which i already had..
Please tell me the problem in the code...
Thanks!
The line for(String word : stringArray) is a so called "for each" loop - a convenience added in Java 1.5.
But it seems your compiler is configued below 1.5, so it does not support the for each loop.
So you can either:
change the compiler level
change the loop to be 1.4 compatible to
String[] stringArray = {"Random", "Words", "Here"};
String word;
for(int i = 0; i < stringArray.length; i++)
{
word = stringArray[i];
System.out.println(word);
}
(in fact this is what the compiler would do for you...)
The issue is clear from the error message -
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, 'for each' statements are only available if source level is 1.5 or greater
You need java 1.5 or higher, You can download latest Java JDKs's from here
Or you can do as ultimate said, and make your loops compatible for lower versions of java (though I would suggest upgrading to above 1.5 , 1.5 is like very very old version anyway).

How can I check for previous elements and the elements added on to an arraylist in java and do error checks

I have a code that atm checks if the array list has reached the size or not, if no I want it to to perform checks before adding anything else to the list. I have attempted it but cannot figure out why it does not work. below is my method.
private static void addToArrayList(String fruit, double no1, int no2, int no3) throws Exception {
try {
if (arraysList.size() <= 5) {
int count = 0;
for (StoringArray item : arraysList)
if (item.equals("Apple")) {
++count;
if (count > 2)
throw new IllegalArgumentException( "You cannot add more than 2 apples." ); //Instead of this I want a Joption pane pop up to give this error if it applies, but at the moment I am not sure but this code with the current code I have is not working.
}
{
if ( arraysList.get( arraysList.size() - 1 ).equals("Banana") )
throw new IllegalArgumentException( "You have just added this please add something else and then add this if you want." ); }
arraysList.add(new StoringArray(fruit, no1, no2, no3));
}else{
JOptionPane.showMessageDialog(contentPane, "You cannot added mroe than 6 elements.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I want the error messages to appear in a Joption Pane and I want to check the following errors;
Say the list includes Apples, Bananas, Oranges, PineApples, Grapes
1; I want to check whether the user given parameters no1, no2 and no3 meet the conditon I want i.e.
for (StoreCommands item : commandsList)
if (item.equals("Apple")) {
}no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15.
2; If user tries to add two apples together in any order it should not be allowed, directly after one another.
3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
If all the conditions are the array values get added to the array list. Thanks I hope I explained myself properly, I have been working on this problem for ages and cannot figure it out for some reason. Thanks again.
----------------edited-----------------with class that stores the arrayList.
public class StoreCommands {
public String toString(){
return Name + " " + Number1 + " " + Number2 + " " + Number3;
}
private String Name;
private int Number1;
private int Number2;
private int Number3;
public String getCommand() {
return Name;
}
public double getcommandNOS() {
return Number1;
}
public int getcommandVLW() {
return Number2;
}
public int getcommandVRW() {
return Number3;
}
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
}
There are also some problems in your StoreCommands (?StoringArray) class and it doesn't compile.
1) The constructor is called StoringArray while the class is called StoreCommands.
2) You shouldn't accept a double value as second parameter and cast it to an int.
3) "Number2 = fno1;" inside the constructor should be "Number2 = fno2;" instead
4) You cannot compare your StoreCommands instance to a String value using equals. You need to compare to the String returned from the getCommand() method:
if (item.getCommand().equals("Apple"))
no1 need to be greater then 0, no2 needs to be less than 10 and no 3 needs to be less than 15. 2; If user tries to add two apples together in any order it should not be allowed, directly after one another. 3; If the user adds 2 Oranges, they should not be allowed and error message saying this should come up in JOption Pane message box.
perhaps something like this would do the job:
public static String getErrorMessage(List<StoreCommands> commands, String fruitsName, int no1, int no2, int no3) {
if (no1 <= 0 || no2 >= 10 || no3 >= 15) {
return "Some Error message...";
}
String previous = null;
int orangeCount = 0;
for (StoreCommands c : commands) {
if (fruitsName.equals("Apple") && previous != null && previous.equals("Apple")) {
return "Some Error message...";
} else if (c.getCommand().equals("Orange")) {
orangeCount++;
}
previous = c.getCommand();
}
return fruitsName.equals("Orange") && orangeCount == 1 ? "Some Error message" : null;
}
your class name is StoreCommands
but you have declared constructor named StoringArray
public StoringArray(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = (int) fno1;
Number2 = fno1;
Number3 = fno3;
}
replace this by
public StoreCommands(String fruitsNames, double fno1, int fno2, int fno3) throws Exception
{
Name = fruitsNames;
Number1 = fno1; //you do not need to cast int because both are int
Number2 = fno1;
Number3 = fno3;
}
in for loop change the conditional logic
for (StoringArray item : arraysList)
if (item.getCommand().equals("Apple"))
{
}
.. it should works now if your other logic and code is ok

Categories