Manipulating input in Java - java

public static void main(String[] args) {
//call for input
System.out.println("Please Enter a 3-digit number..");
Scanner in = new Scanner(System.in);
int[] num = new int[3];
for (int i = 0; i < num.length; i++) {
int val = in.nextInt();
num[i] = val;
}
System.out.println("The Sum of the numbers is " + sumNums);
System.out.println("The Reverse of the numbers is " + reverseNums);
}
public int sumNums(int x) {
return num[0] + num[1] + num[2];
}
public in reverse(int x) {
return num[2] + num[1] + num[0];
}
I'm trying to create a couple methods that add a broken up number, for example, if I enter 123, it would result in 1+2+3=6, but I keep getting "cannot find symbol". Also is the way I broke up the input the most efficient?

There are several problems with your implementation.
In your println, you are not making a method call
System.out.println("The Sum of the numbers is " + sumNums);
System.out.println("The Reverse of the numbers is " + reverseNums );
Should be
System.out.println("The Sum of the numbers is " + sumNums(0));
System.out.println("The Reverse of the numbers is " + reverseNums(0) );
Also, your current sumNums and reverseNums methods aren't using the parameter passed in and they could probably be removed...

The () at the end of the function call is not optional in java, so in your printlns, you need to say sumNums() instead of sumNums. (there is no point of the int x, I assume you remove it.
There are other issues.. such as in should be int, and infact should probably be String if you want to reverse the number.. right now all you are doing is adding them up. And you probably want to pass num as a parameter to the other functions, or make it a class member..

your last method's return type has a typo.
you need to define the array num out of the main method(as a field), or the other methods didn't know this variable(Methods : OMG, What's is the num?)
calling a method is like that : methodName(params...)
I don't think you need to use the par "x" in those methods.
I recommend you to try a better code style

I wouldn't worry about efficiency if I were you. Right now, your program isn't getting any input into the methods that need it.
Two main things here:
Your methods aren't static, so you can't call them inside of main() without an instance of your class (let's call it TestClass for the time being).
You don't pass any of the information you get from the user to your methods to begin with. This is the reason you're running into "cannot find symbol" - num has no definition in the scope of those methods.
To at least remedy the latter issue, you should change the signature of your methods to accept an int array instead of a single int:
public int sumNums(int[] num) {
return num[0] + num[1] + num[2];
}
public int reverse(int[] num) {
return num[2] + num[1] + num[0];
}
I wouldn't expect the results of these two methods to differ in any way though, since addition is commutative.
Instantiating the object, and calling the methods, I leave as an exercise to the reader.

Related

Values are not initializing under try block?

trying to make program rotation of array, it was giving an Exception by user misinput so I use try block but now, under try block it is not initializing values....
Can some one tell the reason or solution for this....
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
System.out.println("Enter T : ");
int t = sc.nextInt();
sc.nextLine();
while(t!=0){
System.out.println("\nEnter N D : ");
String s = sc.nextLine();
s.trim();
String st[] = s.split(" ");
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
System.out.println("Enter Element : ");
s=sc.nextLine();
st = s.split(" ");
ar.rotateArray(st,n,d);
t--;
}
}
If you need valid input and you did not get valid input, the thing to do is to try again to get valid input, after telling the user the input was invalid. Don't just proceed with the invalid data. You therefore need an inner loop:
while (t!=0) {
boolean validInput = false;
while (!validInput) {
System.out.println("\nEnter N D : ");
String s = sc.nextLine().trim();
String[] st = s.split(" ");
int n,d;
try {
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
validInput = true;
}
catch (Exception e) {
System.out.println("Invalid input");
}
}
… process n and d as before …
}
For my taste the loop to get the valid input would be better off being a subroutine in its own right - for clarity.
Variable in local scope should be initialized , that is what error , so do initialize the variables n and d to some integer value say as below
int n = 0 ,d = 0;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}
When a method throws an exception, that method never returns.
This means that if n = Integer.parseInt(st[0]); throws an exception, it does not return a value, which means n will not be assigned a value (since there is no return value to assign to it).
You are ignoring the exception and trying to continue as if nothing went wrong. But something did go wrong—n was never assigned a value. So the compiler tells you that it is not safe to use n in any subsequent code.
To solve this, you first must decide what to do if the user provides invalid input. You can’t just ignore the exception. If the input doesn’t represent two integers, you don’t have any values to work with. You can’t continue in any meaningful way.
The best course of action is to remove your try and catch. This will cause the program to terminate if Integer.parseInt fails, which is almost certainly what you want (unless your assignment requires you to do something different). Remember that it is not possible to continue in any meaningful way without values assigned to n and d.
In other words, change this:
int n,d;
try{
n = Integer.parseInt(st[0]);
d = Integer.parseInt(st[1]);
}catch(Exception e){ System.out.println("Exception"+e.getMessage()); }
to this:
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
As a side note, this line does nothing:
s.trim();
…because Strings cannot be changed. s.trim() returns a new String which you must capture in a variable. You probably want to do this:
s = s.trim();
Your image is quite misleading and really doesn't point to the actual problem, it only points to what you perceive to be the problem. Your mistake was placing the initialization of variables n and d into a try block which takes your call to the rotateArray() method out of scope for that initialization of those variables.
The bigger problem is... What in the world are you rotating? Where is the Array to rotate? Is it actually a String Array or is it suppose to be an Integer Array? Please don't tell me it's the st[] String Array (which is what you're trying to do) because according to your code that array is used to establish the array size (n) portion to work with and the number of elements (d) the User wants to rotate by. No rocket science to rotate an Array with only two elements. Give the rotateArray() method an array to actually rotate.
Let's provide an Integer Array and a way to do this without a try/catch mechaism:
// The Array to carry out rotations on.
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String ls = System.lineSeparator();
Scanner sc = new Scanner(System.in);
ArrayRotation ar = new ArrayRotation();
int t = 0;
String value = "";
while (value.equals("")) {
System.out.print("Enter Number of times to Rotate Array: --> ");
value = sc.nextLine().trim();
/* Make sure a String representation of a Integer value is supplied.
The regular Expression "\\d+" in the String#matches() method
ensures the a numerical integer string is supplied. */
if (!value.matches("\\d+" || value.length() > 9) {
/* Will handle situations where nothing is supplied, alpha
characters might be supplied, or the supplied numerical
value is outrageously large. */
System.out.println("Invalid integer numerical value supplied!" + ls);
value = "";
}
}
t = Integer.parseInt(value);
while (t != 0) {
System.out.println();
System.out.print("Enter the Size (portion) of the Array to consider and the" + ls
+ "number of elements to rotate (separated with a space): --> ");
String s = sc.nextLine().trim();
// Quit if anything starting with the letter "Q"
// (like "q" or "quit") is supplied.
if (s.substring(0, 1).equalsIgnoreCase("q")) {
System.out.println("\"Quit\" Supplied!");
System.exit(0);
}
String st[] = s.split(" ");
/* Make sure two values were supplied and that
they are both numerical integer strings. */
if (st.length != 2 || !st[0].matches("\\d+") || !st[1].matches("\\d+")) {
System.out.println("Invalid Input! Try again and make sure 'both' "
+ "values are numerical Integers.");
continue;
}
// Declare and initialize the n and d variables.
int n = Integer.parseInt(st[0]);
int d = Integer.parseInt(st[1]);
/* If the number of elements to rotate is greater
than the portion of array to rotate in. */
if (d >= n) {
System.out.println("Invalid Input! The size of the Array portion to rotate" + ls
+ "must be greater than the number of elements to rotate.");
}
/* If the supplied Array size to deal with is
out of bounds of the Array itself. */
else if (n < 1 || n > array.length) {
System.out.println("You have supplied an invalid Array Size! (" + n
+ ") Size must be between 1 and " + array.length + "!"
+ ls);
}
/* If the supplied number of elements to rotate
is less than 1 or greater than the total number
of elements - 1. */
else if (d < 1 || d > (array.length - 1)) {
System.out.println("You have supplied an invalid number of elements to rotate! (" + d
+ ") Value must be between 1 and " + (array.length - 1) + "!" + ls);
}
// All is good - Do the rotation.
else {
ar.rotateArray(array, n, d); // Rotate the Array
// Display the current rotation...
System.out.println("Current Rotation: --> " + Arrays.toString(array));
t--;
}
}
// Done
The error you outline in your image is a general compilation error and is relatively generic for all data types. This error occurs when you are trying to use a local variable without first initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value (for example: Reference types are initialized with null and integer types are initialized with zero), but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is going to use it, you will receive this error. You of course will not get this error if you just declare the local variable but don't use it but then, why declare it in the first place.
Everyone is stating to initialize the local variables n and d because in reality, in order to successfully compile your code that is exactly what needs to be done in order for the rotateArray() method (which uses these uninitialized variables) to function. Again in reality, you do initialize them however your code does it within a try{} block which alters scope and the compiler is smart enough to know that if the initialization fails within the try{} block then the catch{} block could let that failure be ignored. In fact, if you were to place the call to the rotateArray() method within that try{} block then you would not get this compile time error since the call is within the scope of of where the variables n and d are actually initialized. You know, a decent IDE (line Eclipse, NetBeans, InteliJ, etc) should catch this error for you long before you try to compile.
According to your code, the actual intent of the try/catch blocks would be to handle the case of invalid input whereas a non-numerical integer value was supplied by the User. In this case it would be up to your catch{} block to handle that particular situation which should be to inform the User of the invalid input and then continue to re-prompt for proper input. At compile time the compiler really doesn't care about this mechanism since this would be a Runtime Error unless of course it is syntax related.
Nothing wrong with try/catch, I just like to avoid them if I can.

I'm a complete beginner at java and have entangled my methods

I'm making a horse-race themed program for my mom that compares the money taken in by her employees and ties it to a horse. I've created two methods which entirely rely on each other and have no idea how to call them into my main method. I, of course, also need to add a graphical element to this at some point, and figuring out how to make the program work with decimal integers would also be ideal. My main issue right now is I need to know how to call print3largest and inputs in my main method, or how to generally make this not a dumpster fire and maybe reduce it to less than 3 methods that aren't entangled like this.
I've searched through repository websites for hours now looking for a solution, but as I have no professional experience in any kind of programming I severely lack the terminology to find an answer, assuming anyone else is stupid enough to run into the same problem I have. I'm extremely limited in my programming knowledge, with java being the only thing I've ever messed with thanks to a course in high school. Sadly, that hardly helps as it was almost entirely through an interface that was essentially just scratch.
import java.util.Scanner;
class HorseComparison
{
public static void main(String[] args)
{
//no clue how to call print3largest or inputs here without ruining everything
}
static void print3largest(int arr[], int arr_size, String firsthorse, String secondhorse, String thirdhorse)
{
int i, first, second, third;
if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}
third = first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i ++)
{
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
third = second;
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
inputs(first, second, third);
System.out.println("The horse in the lead is " + firsthorse + " with " +
first + " dollars.");
System.out.println("The runner up is " + secondhorse + " with " +
second + " dollars.");
System.out.println("Third place is " + thirdhorse + " with " +
third + " dollars.");
}
static void inputs(int first, int second, int third)
{
Scanner sc = new Scanner(System.in);
int size;
System.out.println("How many horses are competing?");
size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the amount of money taken in by each horse (rounded to the nearest dollar and separated by spaces)");
//For reading the element
for(int i=0;i<size;i++) {
arr[i] = sc.nextInt();
int n = arr.length;
String firsthorse;
String secondhorse;
String thirdhorse;
System.out.println("Which horse has taken in "+ first +"?");
firsthorse = sc.toString();
System.out.println("Which horse has taken in "+ second +"?");
secondhorse = sc.toString();
System.out.println("Which horse has taken in "+ third +"?");
thirdhorse = sc.toString();
print3largest(arr, n, firsthorse, secondhorse, thirdhorse);
}
}
}
I want it to display the 3 highest amounts along with the input name of the horse tied to those amounts.
I don't feel like there really is enough information about what the program is intended to do for a clear, direct answer to be provided, but I will do my best.
First, what I would suggest, is you take a good look at this program and determine how you can separate out each responsibility. For example, do you really need to call inputs from print3largest, or could you possibly call this directly from your main?
Once you have established the intent of each function, consider making each function return a result. Generally speaking, you want parameters to be immutable. Learning functional programming habits now will help you down the road.
Here is what I would do:
Copy this file to a backup file.
Start a new Java project, create your class.
Write all of your display code. That is, develop the initial user experience. What inputs do you want to ask from the user? Capture those inputs.
Given those inputs, write your core algorithm, which currently appears to be primarily in print3largest. Return those results back to the caller.
Display your results back to the end user.
This might result in more functions, but that isn't a bad thing. I would also advise that you consider creating a separate class to hold some of this logic. This will give you an opportunity to learn about objects and separation of concerns.
you can call static methods directly by the method name
print3largest()
or you can use the classname before method name example
HorseComparision.print3largest() ```
Since both methods are static and so the Main method. Static methods can be called
Directly with method name, if you are calling from inside the class. Eg : print3largest(.. args), inputs(.. args)
call using ClassName.Method name. This can be used if you are calling method from outside or inside the class. Eg: HorseComparison.print3largest(.. args), HorseComparison.inputs(.. args)

How to make Java ignore previous instructions if specified sum is given?

Literally started with Java today, and my professor has given my class the task of modifying some very basic code.
I want to modify the code to make it print a message if the sum of n1 and n2 is 666, but I don't want it to print the actual sum or the message that would normally go attached to it. I saw somewhere around here that a similar question was asked, but the solution doesn't seem to work for me. I have no idea why. Please help.
import java.io.Console;
import java.util.Scanner;
public class FirstProgram{
Console t = new Console();
public static void main(String[] args)
{
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
int n1, n2;
Scanner keyboard = new Scanner(System.in);
n1 = keyboard.nextInt( );
n2 = keyboard.nextInt( );
//This should print normally when the sum is anything BUT 666
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
//If the sum IS 666, I don't want it to print the above lines, just the one below.
if (n1 + n2 == 666);
t.println("Nice try, Satan");
}
}
It gives two major errors: the constructor Console() is not visible, and that I cannot make a static reference to a non-static field t. I have no idea what any of that means or how to fix it.
You should learn how to make conditional statements. Java will not "ignore" and pass to another thing if you don't tell it how to do that. Remeber: computer can't do anything if one do not tell it to do and how to do that.
You are not initializing n1 and n2, they should be initialized after getting the value from the input.
And as said in the comments, always wrap loops, conditional statements within curly braces{} to make sure the code that will be executed be the one inside braces.
import java.util.Scanner;
public class FirstProgramm{
public static void main(String[] args){
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
int n1 = keyboard.nextInt( );
int n2 = keyboard.nextInt( );
//See? the result is stored inside this variable
int sum = n1 + n2;
//If the sum is equal 666 then print the message
if(sum == 666) {
System.out.println("Nice try, Satan");
}else {
//Else if the sum is something else, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}
}
}
You can even play with the operator that the if uses to evaluates the condition:
if(sum != 666) { //If sum is `not equal to` 666... if the sum is anything else than 666, print it
System.out.println("The sum of those two numbers is");
System.out.println(sum);
}else {// But if it is 666, print what is inside the parentheses
System.out.println("Nice try, Satan");
}
I will try to help you out here.
Firstly: the constructor Console() is not visible
I think this is in reference to the fact that Console was not really meant to be accessed like that. The constructor of Console is private, meaning that outside classes cannot access it. To remedy this issue, when you want to print to the console, use System.console.
Secondly: I cannot make a static reference to a non-static field t
This one is a bit difficult to explain to someone new. Your main function is static, which means it can be accessed without having to instantiate the class that contains it. Your variable t is a instance variable, meaning that it can be accessed by every function in the class when the class has be initialized. However, because the main function is static, you cannot access a non-static variable, because it may not be initialized yet. If you want to access a instance variable in a static function, you need to make that variable static as well, making it a class variable, which will always be accessible.
Lastly
To getting your code working, you need to read up on if statements. This is a conditional statement that is basically asking if this statement is true, do this. There is an else if and else statements as well that say else if this statement is true, do this and else do this.
Example of proper if/else if/else statement:
if(iAmTrue == true)
{
//do this
}
else if(theOtherIAmTrue == true)
{
//do this
}
else
{
//do this because everything else was not true
}
So to fix your code, you would need to do this:
if(n1 + n2 == 666)
{
System.out.println("Nice try, Satan");
}
else
{
//Put your other print message(s) here.
}
I have rewritten the code for you with a few recommendations to achieve what you need.
import java.util.Scanner;
public class FirstProgram {
// I have removed the Console variable, you don't need that.
// System.out.println prints to the console.
// Use constants for any number or string used to give them meaning
private static final int DEVILS_NUMBER = 666;
public static void main(String[] args) {
System.out.println("Hello out there.");
System.out.println("I will add two numbers for you.");
System.out.println("Enter two whole numbers on a line:");
Scanner keyboard = new Scanner(System.in);
// declare variables next to where they are used.
// additionally, never declare more than one variable per line.
// never do this: int n1, n2;
int n1 = keyboard.nextInt();
int n2 = keyboard.nextInt();
// store the sum in a variable so you can refer to it without doing the sum many times
int sum = n1 + n2;
//If the sum IS DEVILS_NUMBER, I don't want it to print the above lines, just the one below.
// always test the positive possibility first, never the negation
if (DEVILS_NUMBER == sum) {
System.out.println("Nice try, Satan");
} else {
//This should print normally when the sum is anything BUT DEVILS_NUMBER
System.out.println("The sum of those two numbers is");
System.out.println(n1 + n2);
}
}
Last but not least, have a look at Java Google Style for tips on how to properly format your code. If you are using an IDE like Eclipse, Intellij or NetBeans it can automatically format the code for you.

Problems with calling a method using an array

I'm relevantly new to Java and just started my first semi serious assignment. I'm confident most of my code is working, the only problem is because I've been using classes I can't seem to call a method which uses an array into my main class. Every other method I want to call seems to work. I wonder if anyone has any explanation or easy solution to this?
Thanks in advance for taking time looking into, really appreciate it!
import java.util.Scanner;
public class GeographyQuizMain
{
public static void main(String[] args)
{
takeQuiz();
}
public static void takeQuiz(Question[][] questions)
{
int score = 0;
RandomNumber randomQuestion = new RandomNumber();
//user chooses catergory
int cat = pickCatergory();
//ask 10 questions
for(int i = 0; i < 10;)
{
Scanner answerChoice = new Scanner(System.in);
randomQuestion.dice();
int q = (randomQuestion.dice() - 1);
//checks to see if question as been asked before
if (!questions[cat][q].beenAsked)
{
questions[cat][q].beenAsked = true; //changes question status to beenAsked
System.out.println(questions[cat][q].promt);
String answer = answerChoice.nextLine();
System.out.println("\nYou picked: " + answer + "\nThe correct answer was: " + questions[cat][q].answer + "\n");
if(answer.equals(questions[cat][q].answer))
{
score++;
}
i++;
}
}
System.out.println("That is the end of the quiz!\n"
+ "You got " + score + "/10");
}
Your problem is with the call itself,
This line public static void takeQuiz(Question[][] questions) states that the method will accept a two dimensional array ([][]) of an object named Question.
On the other hand, your call - takeQuiz(); passes no array of such.
You should initialise an array of such to make this compile and pass it to the function. i.e.
Question[][] questionArray = GenerateQuestionArray(); //you should write this method
takeQuiz(questionArray);
Like you stated, it's clearly you're new to Java and I strongly suggest you to read the instructions and the information provided to you in class about that. I bet the details of Object initialisation, methods and arrays are covered there.
It seems that problem with your method call, in your method takeQuiz(); is taking 2 dimensional array for questions but at the calling time you are not providing that parameter so, compiler not able to found the method.
That's the problem.
try to use like this, this is simple an example for you. replace this with your actual values.
String[][] questions= new String[3][3];
takeQuiz(questions);
this will work.
You have called your method takeQuiz() without actually supplying its arguments Question[][] questions

Trying to compare rep sales in an array list in Java

Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}

Categories

Resources