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

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)

Related

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

What is wrong with my code in my java yahtzee game?

I am writing code for a yahtzee game in java and I need to write a method which allows the user to choose which dice to keep and which dice to re-roll. The part I'm having trouble with is that the user must be able to choose more than one value to keep.
For example on the first roll they may choose to keep 3's, 5's, and a 6. This is what I have so far, but the correct dice are not being kept when I test it.
//keep method
public void keep(int[] keepThis) {
for(int i = 0; i < keepOrRollArray.length; i++) {
for(int p = 0; p < keepThis.length; p++) {
if(faceValueArray[i] == keepThis[p])
keepOrRollArray[p] = 'K';
}
}
}
//keep method tested after a roll
newDiceArray.roll();
int[] userValue = new int[2];
userValue[0] = 3;
userValue[1] = 4;
newDiceArray.keep(userValue);
System.out.println("Practice roll: " + "\n" + newDiceArray +"\n");
First off, I'm guessing that there is quite a bit more to your code than what you have posted. (Otherwise, your code is egregiously incomplete, not to put too fine of a point on it). Without this additional code, we can't really help much.
In the meantime, however, if what you have isn't "keeping" the correct dice, you might ought to try having five separate questions querying the user whether they want to keep each of the dice: "Do you want to keep dice #1", "Do you want to keep dice #2" etc. Then update your keepThis array appropriately.

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;
.....
}

Manipulating input in 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.

Java Error When attempting to use the return from a method as an item in an if statement

I keep getting the following errors:
Cannot find symbol
Variable find
cannot find symbol
method getdata(int)
I am sure I am making this way more difficult than it is, but I am not sure how make this work so that the return from searching through the array, can be seen and evaluated by the if statement.
//assigns manager identification
manID = keyboard.nextInt();
//Fibonacci binary array for passwords
int[] passWArray = {00000000,00000001,00000001,00000010,00000011,00000101,00001000,00001101};
//item = find.getdata(manID);
if (getdata(manID) != -1)
{
//Do work here
dblPayRate = 10.85;
dblGrossPay = (intHours * dblPayRate) + (15.00);
dblTaxes = dblGrossPay * 0.19;
dblGrossPay -= dblTaxes;
//Print information to user
System.out.print("\n\n$" + df2.format(dblTaxes) +
" was withheld from this paycheck in taxes after working "+ intHours + " hours.\n\n");
System.out.print("The amount \"Employer Here\" owes you is $" + df2.format(dblGrossPay) + "\n");
}
else
{
// Dialog box for incorrect password
JOptionPane.showMessageDialog(null, "Invalid Entry! Contact the BOFH!");
//exits program (Note: needed for any JOptionPane programs)
System.exit(0);
}
}// end of long if statement for >50 hours
}//end of main method
public int find(int[] passWArray, int manID)
{
//search for manID in passWArray array
for (int index = 0; index < passWArray.length; index++)
if ( passWArray[index] == manID )
return manID;
//-1 indicates the value was not found
return -1;
}// end of find method
Change
if (getdata(manID) != -1)
into
if (find(passWArray , manID) != -1)
BTW those numbers don't magically become binary because they only contain 0's and 1's. Here's a hint:
int thirteen = Integer.parseInt("00001101", 2)
EDIT: in response to your next error
For now make the method static:
public static int find(int[] passWArray, int manID)
Eventually you might want to think about your 'Object-Oriented design' and just use the main() method as an entry point. Within main you create an instance of a class and let it do its work. In this way you can use the powers of O-O like encapsulation and inheritance and don't have to make everything static.
EDIT2: Afterthought
Your program seems to have the following 'actions':
user interaction
authentication
calculation
And there seem to be the following 'things' in your domain:
user
password
keyboard
display (command line and screen)
calculation
A good rule of thumb for an O-O design is to convert some of the 'things' and 'actions' already present in your domain into classes. A good class has a single responsibility and shares as little as possible of its data and methods with other classes (this is called information hiding).
Here's a class diagram that comes to mind:
User (represents a user, contains a single field 'password')
Authenticator (authenticates a user, contains the list of allowed passwords)
Console (all user interaction, either use System.out/in or Swing, but don't mix them)
Calculator (it calculates shit)

Categories

Resources