Java - How can I insert user input position in existing array - java

I am pretty new in Java. I am developing a Java console application which has a field and a frog jumping around in it, the user decides the size of the field through input in a 2d array, (kind of like a chess board but the difference is that the user decides how big the field should be). For instance the users enter height of field in feet and the width in feet. So far I have managed to do a bit of the class Field and class Position, which takes input from user and puts it on a array (int [][]fieldsize).
Class Controller:
package project;
public class Controller {
public static void main( String[] args ) {
Field field = new Field();
Position position = new Position();
}
}
Class Field:
package project;
import java.util.Scanner;
public class Field{
int y;
int x;
int[][] fieldsize;
public Field() {
Scanner scan = new Scanner(System.in);
System.out
.println("Enter the size of the field in feets(width
and length separated by space, x y):");
x = scan.nextInt();
y = scan.nextInt();
int[][] fieldsize = new int[y][x];
this.fieldsize= fieldsize;
}
public int[][] getFieldSize() {
return fieldsize;
}
}
I have managed to "collect" the fields size from user input into int [][] fieldsize array.
Now I want to ask the user about the starting position for the frog and the heading direction, S(south), N(north), E(east), W(west) and then add the frog to the field. For instance the user types 3 4 E. This should put the frog to position [3] [4] East(Heading). How do I resolve this?
Class Position:
package project;
import java.util.Scanner;
public class Position {
public Position() {
int x;
int y;
String heading;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the starting position and heading for the frog, X Y and N, S, W or E position");
x = scan.nextInt();
y = scan.nextInt();
heading = scan.next();
//How do I put this inputs in the Field(fieldsize)?? So they get into this position in the field??
}
}
It is a bit difficult to describe what I mean, but I hope you guys can help me!
Thanks in advance!

OK. First thing you should consider before starting to code - what is the design. And the question like this usually appears when the code comes before the design.
So the first question should be:
What classes do I need and what every class should do and how would they interact.
An object is a self-contained component that contains properties and
methods needed to make a certain type of data useful. An object’s
properties are what it knows and its methods are what it can do.
For example - What can the object of the class Field do? How would it interact with the Position? And what can I do with the Position?
Then you start to design the classes. You sure don't want to read the user input in a constructor. What if you want to get the input from the file tomorrow and get it from the cloud or by voice the next month? Or even worse - what if there is an input error? What would be the state of the object?
You usually need to provide all the data needed to create the object to the constructor. The constructor shouldn't care where you get it from. You can have a public Field(int x, int y) and call it in your main class after reading the user input (I'm not suggesting that you should have this exact constructor, just an example).
You may want to set the position as a method of the Field (field will contain the position)
field.setPosition(position);
or have a move method of the Position (you can have as much positions as you like on the field)
position.setField(field);
position.moveTo(x,y);
Or you can even get to the conclusion you don't need a Position at all, and it would merely be the Field's property:
field.setCurrentX(x);
field.setCurrentY(y);
The design is really up to you here. Just have the design before you code.

Related

Java: Certain coordinates labeled on a plotted line

I'm working on a program that creates a plotted line from a generated array list of real time numbers. The numbers aren't necessarily linear and can create a crooked pattern. The program counts the points of inversion and gives them to the user, however the clutter on the screen can be quite a problem when a large number of inversions exist. Is there a way to rewrite/modify the code as to make it so that only certain numbers are printed, for example if the person wants the numbers 80, 90, and 143 to only show. Code attached:
CustomCoordinate is a custom class that helps setup the list, included for clarity.
private int count;
private int num;
public CustomCoordinate(long time, double value, int number) {
super(time, value);
this.count = number;
}
public int getCount() {
return count;
}
For clarification, selDateInSec is a calendar object where the user inputs the date of when the first data point label will be located along the x-axis. Any inversion before this won't be labeled, any after will.
int x = 0;
if (inversions) {
for(CustomCoordinate c : points) {
if(c.getTime() > selDateInSec) {
Label lbl = new Label (instr.format(++x), f, txtColor, bgColor);
lbl.setLocation(c);
addFigure(lbl);
}
}
}
Thanks in advance
You can take input from the user about the points they are interested in and then use filter function on it to filter out the points of interest. Hence you'll be able to show only the points of interest without clutter.

JAVA seperate class method not incrementing a variable in my main class method

so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");

How do I retrieve a Java Object based on a value of it's instance variables

I want to add a certain Object in an ArrayList based on the user's input.
i.e: If the user inputs two numbers I shall retrieve an Object of type building with given X, Y coordinates in a 2D Array I created
You mean something like this?
Building retrieveBuilding(Building[][] buildingMap) {
System.out.println("Enter X");
int x = scan.nextInt();
System.out.println("Enter Y");
int y = scan.nextInt();
return buildingMap[x][y];
}
ArrayList<Building> buildings = new ArrayList<Building>();
buildings.add(retrieveBuilding(buildingMap));
I assume 2D array buildingMap is already created and contains building on all coordinates - you need to add a check for null otherwise. You should also validate input to make sure that [X,Y] is in your 2D array.
By the way, I didn't test my code and I am not sure if it does exactly what you wanted but I hope it gave you some idea.

how to take onlythe x and y from Point class

I have a variable private Point _centralStation which located in class that I called her City.
the user in the main class decides which value will be to the location of the centralStation.
So he put for example:
Point center = new Point(5,5) .
I want to create a method who called MoveCentralStation(int x, int y)
that moves the location from his last value to the new one, but
the new points have to be in the first quarter of the x,y axis.
I mean x cannot be -4 for example.
let's say for the exmaple it was 5,5
and now the user entered -4,5
how can I deal with the x and y new values sepertely?
Thank you
You have to explain yourself a little better. However, this is what I understood.
You have such a class:
class City{
private Point _centralStation;
public City(){
this._centralStation = new Point(5,5);
//the initialization you specified
}
public void moveCentralStation(int new_x, int new_y){
//TODO exactly what you have to implement
}
public Point getCentralStation(){
//since you are not implementing just getters and setters you rather do
return new Point(_centralStation.x,_centralStation.y);
//instead of return _centralStation [this is what we call defensive copies]
}
}
Well, somewhere in the code, a client would call
City c = new City();
c.moveCentralStation(x,y); //given x,y are variables in the client's context
And these are the requirements for the moveCentralStation(int x, int y) operation:
x coordinate shall be positive
y coordinate shall be positive
First of all I suggest you to follow style conventions on the way you code: use capital letters only for the class names. Let's jump into the real problem.
We need to refine the above requirements to make a specific implementation compliant with them. They aren't clear enough. An example of refinining i may suggest is the following:
If x coordinate is less than zero, an IllegalArgumentException shall be thrown
If y coordinate is less than zero, an IllegalArgumentException shall be thrown
And that's very simple to implement:
public void moveCentralStation(int new_x, int new_y){
if(new_x < 0) throw new IllegalArgumentException("x must be positive");
if(new_y < 0) throw new IllegalArgumentException("y must be positive");
_centralStation.x = new_x;
_centralStation.y = new_y;
}
It's a good practice to set private fields only when they are all consistants.

Methods in java (grade calculator)

We've been learning about methods in java (using netbeans) in class and I'm still a bit confused about using methods. One homework question basically asks to design a grade calculator using methods by prompting the user for a mark, the max mark possible, the weighting of that test and then producing a final score for that test.
eg. (35/50)*75% = overall mark
However, I am struggling to use methods and I was wondering if someone could point me in the right direction as to why my code below has some errors and doesn't run? I don't want any full answers because I would like to try and do it best on my own and not plagiarise. Any help would be greatly appreciated :)! (Also pls be nice because I am new to programming and I'm not very good)
Thanks!
import java.util.Scanner;
public class gradeCalc
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
scoreCalc();
System.out.print("Your score is" + scoreCalc());
}
public static double scoreCalc (int score1, int maxMark, double weighting, double finalScore)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter mark");
in.hasNextInt();
score1 = in.nextInt();
System.out.print("Enter Max mark");
in.hasNextInt();
maxMark = in.nextInt();
System.out.print("Enter weighting as a decimal (eg. 75% = 0.75)");
in.hasNextInt();
weighting = in.nextInt();
finalScore = (score1/maxMark)* weighting;
return finalScore;
}
}
You are calling your method scoreCalc() without passing the parameters you defined.
When you are calling it, it was defined as having 3 parameters.
scoreCalc(7, 10, 3.0, 8.0);
Also, when creating a class, start it with upper case, GradeCalc
As you can see scoreCalc method needs a set of parameters, but you call it without parameters.
The second: there is no need in Scanner in = new Scanner(System.in); into your main(String[] args) method. You are calling it into scoreCalc method.
Third: you are calling scoreCalc twice. The first call is before System.out.println, the second is into System.out.println. And your application will ask user twice to enter values.
store result value in a variable and show it later:
double result = scoreCalc(.... required params .....);
System.out.println("Your score is: " + result);
To start :
1) Follow coding conventions. (Class name should start with a capital letter).
2) In your context, you don't need Scanner in = new Scanner(System.in); in main() because you are not using it.
3) You are a calling the method scoreCalc() without parameters. Whereas, the method needs to be called with parameters.
4) A method,is a module. It as block of code which increases re-usability. So I suggest that accept the values from user in main() method and then pass them to the method for calculation.
A couple of things spring to mind:
You execute scoreCalc() twice. Probably you want to execute it once and save the result in a double variable like: double score = scoreCalc().
Speaking of scoreCalc(): Your definition takes 4 parameters that your don't have as input for that method. You should remove those from your method definition, and instead add score1, maxMark, weighting and finalScorevariable declarations in the method-body.
In your main function, you declare and instantiate a Scanner object you don't use.
Be careful with arithmetic that mixes int and double.
Some mistakes/errors to point out are:-
1) You do not need this statement Scanner in = new Scanner(System.in); in your main() , as you are not taking input from user through that function.
2) Your function scoreCalc (int score1, int maxMark, double weighting, double finalScore) takes parameters, for example its call should look like scoreCalc(15, 50, 1.5, 2.7), but you are calling it as scoreCalc(), that is without paramters from main().
Edit:- There is one more serious flaw in your program, which might work , but is not good coding. I wont provide code for it , and will leave implementation to you. Take input from user in the main() (using scanner) , assign the result to a temp variable there, and then pass that variable as parameter to the function scoreCalc()
//pseudocode in main()
Scanner in = new Scanner(System.in);
int score= in.nextInt();
.
.
.
scoreCalc(score,...);
Or you can make your scoreCalc function without parameters, and take user input in it (like present), and finally return just the result to main().
Both approaches seem appropriate and you are free to choose :)
As opposed to other answers I will start with one other thing.
You forgot about the most important method - and that is the Constructor.
You have to create a grade calculator, so you create a class(type) that represents objects of grade calculators. Using the Java convention this class should be named GradeCalculator, don't use abbreviations like Calc so that the name is not ambiguous.
So back to the constructor - You have not created your Calculator object. It may not be needed and you may achieve your goal not using it, but it's not a good practice.
So use this method as well - this way, you'll create actual Calculator object.
It can be achieved like that:
public static void main(String[] args)
{
GradeCalculator myCalculator = new GradeCalculator();
}
And now you can imagine you have your calculator in front of you. Whan can you do with it?
Getting a mark would be a good start - so, what you can do is:
myCalculator.getMark()
Now you'll have to define an method getMark():
private void getMark() { }
In which you would prompt the user for the input.
You can also do:
myCalculator.getMaxMark() { }
and that way get max mark (after defining a method).
The same way you can call method myCalculator.getWeighting(), myCalculator.calculateFinalResult(), myCalculator.printResult().
This way you'll have actual object with the following mehtods (things that it can do):
public GradeCalculator() { } //constructor
private void getMark() { } //prompts user for mark
private void getMaxMark() { } //prompts user for max mark
private void getWeighting() { } //prompts user for weighting factor
private void calculateFinalResult() // calculates the final result
private void printResult() // prints the result.
And that I would call creating a calculator using methods - and that I would grade highly.
Try to think of the classes you are creating as a real objects and create methods representing the behaviour that objects really have. The sooner you'll start to do that the better for you.
Writing whole code in one method is not a good practice and in bigger applications can lead to various problems. So even when doing small projects try to do them using best practices, so that you don't develop bad habbits.
Edit:
So that your whole program can look like this:
import java.util.Scanner;
public class GradeCalculator
{
//here you define instance fields. Those will be visible in all of your classes methods.
private Scanner userInput; //this is the userInput the calculator keypad if you will.
private int mark; //this is the mark the user will enter.
private int maxMark; //this is the mark the user will enter.
private int weightingFactor; //this is the weighting factor the user will enter.
private int result; //this is the result that will be calculated.
public static void main(final String args[])
{
Scanner userInput = new Scanner(System.in); //create the input(keypad).
GradeCalculator calculator = new GradeCalculator(userInput); //create the calculator providing it with an input(keypad)
calculator.getMark();
calculator.getMaxMark();
calculator.getWeightingFactor();
calculator.printResult();
}
private GradeCalculator(final Scanner userInput)
{
this.userInput = userInput; //from now the provided userInput will be this calculators userInput. 'this' means that it's this specific calculators field (defined above). Some other calculator may have some other input.
}
private void getMark() { } //here some work for you to do.
private void getMaxMark() { } //here some work for you to do.
private void getWeightingFactor() { } //here some work for you to do.
private void printResult() { } //here some work for you to do.
}
Please mind the fact that after constructing the Calculator object you don't have to use methods that are static.

Categories