Can we use Setter Method in java to perform operations? - java

Is setter method only use to assigning values? or can we perform operations in it. Here in this code the commented part is giving me correct output but while using set and get I am getting output as 0.
I want to avoid calling totalMarksOfStudent() method again and again because it have 5 parameters which I dont want to give again and again. So what is the way to return totalMarksStudent in another class without calling totalMarksOfStudent().
int totalMarksStudent = 0;
public void setMarks(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
}
public int getMarks(){
return totalMarksStudent;
}
// public int totalMarksOfStudent(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
// totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
// return totalMarksStudent;
}
public String displayTotalMarks() {
String totalMarks1 = "Name " + name + "\tRoll No " + rollNo + "\tTotal Marks " + getMarks();//totalMarksOfStudent(englishMarks, mathsMarks, physicsMarks, chemistryMarks, csMarks);
return totalMarks1;
}

Better to avoid that...
I think it's better to have some fields like your parameters in setMarks (englishMarks , mathsMarks , ...) , and give value to them in constructor or setter methods. Also it's better to have a method named something like calculateTotalMarks , and call it without any parameters whenever you need it. Remember that there will be no problem to have operations in setter methods but usually and for better designed program we avoid that. Methods should do the thing their name says : for example , setter just for assigning , getter just for accessing values , calculateTotalMarks for calculating the total marks and so on ...

setter method is usually used to assigning values. It is promise.
You can reduce parameters by using Object
I recommend to make object of MarksStudent. because common attribute can bind to one class. It make understand easily code
for example
// Java is object-oriented language
class marksStudents {
private int english;
private int math;
private int physics;
private int chemistry;
private int cs;
//getMethods is Abbreviation
public int getTotal() {
return english+math+physics+chemistry+cs;
}
//setMethods
public void setEnglish(int english) {
this.english = english;
}
public void setMath(int math) {
this.math = math;
}
public void setPhysics(int physics) {
this.physics = physics;
}
public void setChemistry(int chemistry) {
this.chemistry = chemistry;
}
public void setCs(int cs) {
this.cs = cs;
}
}
To execute
public class Main{
public static void main(String[] args) {
// You can make object marksStudents of studentsA
marksStudents studentsA = new marksStudents();
studentsA.setChemistry(20);
studentsA.setEnglish(30);
studentsA.setMath(40);
studentsA.setCs(50);
studentsA.setPhysics(60);
//200
System.out.println(studentsA.getTotal());
// You can make object marksStudents of studentsB too
marksStudents studentsB = new marksStudents();
studentsB.setChemistry(10);
studentsB.setEnglish(10);
studentsB.setMath(10);
studentsB.setCs(10);
studentsB.setPhysics(10);
//50
System.out.println(studentsB.getTotal());
}
}

The getter/setter method is only a practice. Not bad practice - it just defines a class, whose instances for the external world are handled by a list of independent values. Using them makes your code better comprehensible and easy to understand, what is it doing.
So it is no problem to make other operations with it, in general.
Some frameworks like to use reflection to use getters/setters and also reach the variables directly in them. In these cases, doing any different in the getters/setters than reading/writing the private members is no wise idea. Sometimes you can use a little bit of api/impl interface trickery to handle this problem.

Related

I cant sort my Collection

This is my Code and I can't sort my LinkedList.
import java.util.Collections;
import java.util.LinkedList;
import org.omg.CosNaming.NameComponent;
public class Zug implements Comparable<Zug> {
private String abfahrtzeit;
private String zuggattung;
private int zugnummer;
private int fahrtzeit;
public Zug(String zeile) {
String[] teile = zeile.split(";");
this.abfahrtzeit = teile[0];
this.zuggattung = teile[1];
this.zugnummer = Integer.parseInt(teile[2]);
this.fahrtzeit = Integer.parseInt(teile[3]);
}
public String getAbfahrtzeit() {
return abfahrtzeit;
}
public String getZuggattung() {
return zuggattung;
}
public int getZugnummer() {
return zugnummer;
}
public int getFahrtzeit() {
return fahrtzeit;
}
public String toString() {
return this.abfahrtzeit + ";" + this.zuggattung + ";" + this.zugnummer + ";" + this.fahrtzeit;
}
// This is the Problem Block
#Override
public int compareTo (Zug z) {
String datei = "Zuege.dat";
LinkedList<Zug> ll = new LinkedList<Zug>();
Collections.sort( ll, new NameComponent() );
ll = getDaten(datei);
return this.fahrtzeit - z.getFahrtzeit();
}
// End Of Problem Block
private LinkedList<Zug> getDaten(String datei) {
return null;
}
}
As RealSkeptic and matoni write, you must not do anything other in the compareTo(Zug z) method than compare this to z - as the method name implies. compareTo(Zug z) is called by methods sorting a collection whenever they need to compare two elements of that collection. Loading lists of objects in that method doesn't make any sense.
The most simple implementation would be
#Override
public int compareTo(Zug z) {
return this.fahrtzeit - z.getFahrtzeit();
}
You may want to test your code with that implementation. Generate a few example Zug objects, add them to a List, sort that list using Collecitons.sort() and enjoy the result (or give us a meaningful error message).
Java Practices has an elaborate example on how to write a compareTo()-method.
Please note that this implementation is not consistent with equals() (as detailed in the javadoc).
Sorting by fahrzeit might not be the only way to sort your objects and probably should not be the natural order. You probably should implement a Comparator (e.g. FahrzeitComparator, AbfahrtzeitComparator ...) to be able to sort by different criteria. See this example.
Oh, and:
Rewriting your code with English variable names would allow more people to understand what your objects should represent...

Java return multiple strings in one method

I am attempting to write a program which asks users what their pet name is, species, finds out thirst level and gives a response accordingly.
I would appreciate if someone could help me with a problem im having, in each of the 2 methods askpetname and thirstlevel there are 2 strings i want accessible throughout the entire class without using global variables.
Can someone tell me what it is i am doing incorrectly or point me in the right direction.
Also, i understand that my excess use of methods for tedious tasks is bad practice but it helps with memorising syntax.
Thanks.
class dinoo
{
public static void main(String[] p)
{
explain();
output();
System.exit(0);
}
public static void explain()
{
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
public static String askpetname()
{
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
print("Awesome, cool dinosaur name, what species is " + petname+ " ?");
String petspecies = scanner.nextLine();
return petname, petspecies;
}
public static int thirstlevel()
{
Random ran = new Random();
int thirst = ran.nextInt(11);
int hunger = ran.nextInt(11);
return thirst,hunger;
}
public static String anger(int thirst, int hunger)
{
double angerscore = (thirst+hunger)/2;
String temper;
if(angerscore<=2)
{
temper = "Serene";
}
else if(3<=angerscore<=6)
{
temper= "Grouchy";
}
else if(6<angerscore)
{
temper = "DANGEROUS";
}
return temper;
}
public static String warning()
{
if (temper.equals("Serene"))
{
print("He's looking happy!");
}
else if(temper.equals("Grouchy"))
{
print("Ahhh hes a bit "+temper+", you better start feeding him before he gets mad!");
}
else if(temper.equals("DANGEROUS"))
{
print("GET OUT OF THERE, HES " + temper+"!!!. He will have to be put down for everyones safety.");
}
}
public static void output()
{
print(askpetname() + "'s, thirst level is "+thirstlevel()+"/10");
return;
}
public static String print(String message)
{
System.out.println(message);
return message;
}
}
That code won't compile since you can't have:
return string1, string2;
or
else if(3<=angerscore<=6)
Instead of trying to return multiple Strings, your best bet is to create a class, say called Pet, one that holds String fields for the pet's name, a Species field for its species, as well as any other fields for hunger, thirst ... that would best encapsulate all the data that makes up one logical "pet" as well as a methods such as getAnger() that returns a value for anger depending on the Pet's state. Then you can create and return a viable Pet object from your creational method.
Also, your code has lots of compilation errors, suggesting that you could improve the way that you create your code. Never try to add new code to "bad" code, to code that won't compile. If possible, use an IDE such as NetBeans, Eclipse, or IntelliJ to help you create your programs. The IDE's will flag you if any of your code contains compilation errors, and then the key is: don't add new code until you've first fixed the existing compilation error. If you can't use an IDE, then you must compile early and often, and do the same thing -- fix all errors before adding new.
First, I would recommend shooting through a tutorial first before attempting this, do all the hello worlds covering scope, objects, arrays and functions. Get familiar with Object Oriented Style, although thats not even procedural programming ... nothing returns 2 objects ... always 1 (it could be an array containing many objects, but an array is a single object)
Moving on,although this is terrible coding practice, but its ok for a beginner,since your functions are all static, create a private static variable inside each function and create getter functions
//convert
String petname = scanner.nextLine();
// To this
private static String petname = scanner.nextLine();
// Then add this below it
public static String getPetName()
{
return petname;
}
and same for every piece of data you need.
Now remove the return statement from all of your functions and declare return type as void
Then call all functions from Main,
askpetname();
thirstlevel();
then print final output (after you have called the functions) as such
System.out.println("Petname: " + getPetname + " ThirstLevel: " + getThirstLevel() + " HungerLevel: " + getHungerLevel);

Java - Subclasses of Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Disclaimer: I'm a beginner so feel free to point stuff out...
I have a superclass composed by an array of int with 8 values, now i want to create a subclass to randomly pick 4 items in the array and store them in another Object.
Superclass:
public class SideDeck{
public static final int MaxValue = 6;
public static final int MinValue = -6;
public static final int MaxArrayValue = 8;
public final int[] sidecards = new int[MaxArrayValue];
public SideDeck(){
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
public SideDeck(int sidecards1,int sidecards2,int sidecards3,int sidecards4,int sidecards5,int sidecards6, int sidecards7, int sidecards8){
sidecards[0]=sidecards1;
sidecards[1]=sidecards2;
sidecards[2]=sidecards3;
sidecards[3]=sidecards4;
sidecards[4]=sidecards5;
sidecards[5]=sidecards6;
sidecards[6]=sidecards7;
sidecards[7]=sidecards8;
}
public boolean ValidSidedeck(){
int check=0;
if (sidecards[0]!=0) {
for(int i=0;i<MaxArrayValue;i++){
if ((sidecards[i] > MinValue) && (sidecards[i] < MaxValue)){
check=1;
} else{
check=0;
break;
}
}
} else {
check=0;
}
if (check==1){
return true;
} else {
return false;
}
}
public String toString(){
String s="";
for(int i=0;i<MaxArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
public void ResetSidedeck(){
if (sidecards[0]!=0) {//why check it? what if we just run it?
for(int i=0;i<MaxArrayValue;i++){
sidecards[i]=0;
}
}
}
}
Subclass: (Not really sure what to do here… ) Basically it should pick 4 random positions from the .super and store them here, just that i have no clue how to create the object this way. And passing the super as constructor doesn't seem right since it's gonna pass the Object and not the array(and i don't need the full array anyway). Main thing is that i wanna keep the superclss like that, maybe just adding a method there so extract the 4 values..and passing them as arguments…?
import java.lang.Math;
public final class PlayableSideDeck extends SideDeck{
private final static int MaxCArrayValue=4;
public final int[] sidecardsPlay = new int[MaxCArrayValue];
public PlayableSideDeck(SideDeck sidecards){
/* sidecardsPlay[0]=0;
sidecardsPlay[1]=0;
sidecardsPlay[2]=0;
sidecardsPlay[3]=0;*/
// SetDeck();//<-Can i call a private method in the constructor
}
public void SetDeck(){
/* for(int j=0;j<4;j++){
int position=(super.sidecards[PickDeck()]);//<--this is the main problem.. since it's gonna call the object i guess.
sidecards[j]=position;
System.out.println(/*"i= " + i + *//* " ||| j= " + j + "|||| new sidecard= " + sidecards[j] + " |||| old sidecard=" + super.sidecards[PickDeck()]);
}*/
for(int j=0;j<MaxCArrayValue;j++){
sidecardsPlay[j]=(super.sidecards[PickDeck()]);
System.out.println(/*"i= " + i + */ " ||| j= " + j + "|||| new sidecard= " + sidecardsPlay[j] + " |||| old sidecard=" + super.sidecards[PickDeck()] + "|| random= " + PickDeck());
}
}
public int PickDeck(){
return ((int)(Math.random() * 8));
}
public String toString(){
String s="";
for(int i=0;i<MaxCArrayValue;i++){
s+=(" || Card n° " + (i+1) + " = " + sidecards[i]);
}
return s;
}
}
Thanks.
I'm not sure how you plan to use PlayableSideDeck, so I'll answer answer this two ways and you can pick the most fitting answer.
First, as the book Effective Java (by Josh Bloch) points out, you should favor composition over inheritance. By using composition you have your answer to the question of whether you should pass an instance of SideDeck to the constructor of PlayableSideDeck - you will have to since you won't be inheriting any access to SideDeck. Anyway, I'd recommend reading Item 16 in the book (google for it, there are copies available online) and see if composition doesn't better fit your needs.
Second, if you decide to go with inheritance, you don't need to pass an instance of SideDeck to the constructor of PlayableSideDeck. This is because when you create an instance of PlayableSideDeck you are automatically creating an instance of SideDeck along with it. All constructors in Java will implicitly call super() (which is the superclasses's default constructor) if you don't explicitly provide another such call yourself. For example, you could prevent the implicit call to super() like so:
public class BaseClass {
protected String strValue;
public BaseClass () {
strValue = "";
}
public BaseClass (String str) {
strValue = str;
}
}
public class SubClass extends BaseClass {
private int intValue;
SubClass (String str, int i) {
super (str);
intValue = i;
// note that since strValue is protected, SubClass can access directly
System.out.println ("strValue = " + strValue);
}
}
In this example, if you call new SubClass ("foobar") then you will see strValue = foobar printed on the console.
If BaseClass didn't have a zero argument constructor you would, in fact, be required to call super(str) since the compiler wouldn't be able to figure out how to do it for you.
Also, since you asked, here are a few other tips and pointers:
In the constructor SideDeck() you explicitly initialize all values of the array to 0, which isn't necessary. They will already all be 0. If you needed to init them to 0 then you'd be better off avoiding code duplication by calling ResetSideDeck. Speaking of which, you can shorten that code to Arrays.fill (sidecards, 0); (be sure to import java.util.Arrays).
Yes, you can call private methods from a constructor - but only private methods that are part of the local class, not any of the superclasses (you can, however, call protected methods of superclasses).
You're right about not checking sidecards[0] == 0 since there's little efficiency to be gained unless MaxArrayValue becomes very large.
Your class member variables such as sidecards should be private (or maybe protected if you need to access them from a subclass). Use getter/setter methods to access them.
Lastly, Java naming conventions would tell you to use a lower-case letter for method names (e.g. setDeck, pickDeck, resetDeck, etc.), and for even more idiomatic Java you could rename ValidaDeck to isValidDeck (since it returns a boolean). For the constants such as MaxArrayValue the convention is to use all upper-case with underscores between words, e.g. MAX_ARRAY_VALUE.
Hope this all helps!

Is it possible to return more than one value from a method in Java? [duplicate]

This question already has answers here:
How to return multiple objects from a Java method?
(25 answers)
Closed 7 years ago.
I am using a simulator to play craps and I am trying to return two values from the same method (or rather I would like to).
When I wrote my return statement I simply tried putting "&" which compiled and runs properly; but I have no way of accessing the second returned value.
public static int crapsGame(){
int myPoint;
int gameStatus = rollagain;
int d1,d2;
int rolls=1;
d1 = rollDice();
d2 = rollDice();
switch ( d1+d2 ) {
case 7:
case 11:
gameStatus = win;
break;
case 2:
case 3:
case 12:
gameStatus = loss;
break;
default:
myPoint = d1+d2;
do {
d1=rollDice();
d2=rollDice();
rolls++;
if ( d1+d2 == myPoint )
gameStatus = win;
else if ( d1+d2 == 7 )
gameStatus = loss;
} while (gameStatus == rollagain);
} // end of switch
return gameStatus & rolls;
}
When I return the value as:
gameStatus=crapsGame();
It appropriately sets the varaible to win or lose but if I try something as simple as following that statement with:
rolls=crapsGame();
It is assigned the same value as gamestatus...a 0 or a 1 (win or lose).
Any way that I can access the second returned value? Or is there a completely different way to go about it?
Create your own value holder object to hold both values, then return it.
return new ValueHolder(gameStatus, rolls);
It's possible to return an array with multiple values, but that's cryptic and it does nothing for readability. It's much easier to understand what this means...
valueHolder.getGameStatus()
than what this means.
intArray[0]
returning gameStatus & rolls means "return the bitwise and of gameStatus and rolls" which probably is not what you want
you have some options here:
return an array
create a class that represents the response with a property for each value and return an instance
use one of the many java collections to return the values (probably lists or maps)
You can return an array of values or a Collection of values.
Is it possible to return more than one value from a method in Java?
No it is not. Java allows only one value to be returned. This restriction is hard-wired into the language.
However, there are a few approaches to deal with this restriction:
Write a light-weight "holder" class with fields for the multiple values you want to return, and create and return an instance of that class.
Return a Map containing the values. The problem with this (and the next) approach is that you are straying into an area that requires runtime type checking ... and that can lead to fragility.
Return an array containing the values. The array has to have a base type that will accommodate the types of all of the values.
If this is a method on an object, then add some fields on the same object and methods that allow the caller to pick up "auxiliary results" from the last call. (For example, the JDBC ResultSet class does this to allow a client to determine if the value just retrieved was a NULL.) The problem is that this makes the class non-reentrant at the instance level.
(You could even return extra results in statics, but it is a really bad idea. It makes the class non-reentrant across all instances, not to mention all of the other badnesses associated with misused statics.)
Of these, the first option is the cleanest. If you are worried about the overhead of creating holder instances, etc, you could consider reusing the instances; e.g. have the caller pass an existing "holder" to the called method into which the results should be placed.
The best practice for an OOP approach is to return an Object. An object that contains all the values you want.
Example:
class Main {
public static void main(String[] args) {
MyResponse response = requestResponse();
System.out.println( response.toString() );
}
private static MyResponse requestResponse() {
return new MyResponse( "this is first arg", "this is second arg" );
}
}
class MyResponse {
private String x, y;
public MyResponse( String x, String y ) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return "x: " + x + "\t y: " + y;
}
}
If you want an even more scalable approach then you have to use JSON responses. (let me know if you want an example with JSON too)
You can following ways to do this:
Use a Container class, for example
public class GameStatusAndRolls {
String gameStatus;
String rolls;
... // constructor and getter/setter
}
public static GameStatusAndRolls crapsGame(String gameStatus, String rolls) {
return new GameStatusAndRolls(gameStatus, rolls);
}
public static void main(String[] args) {
...
GameStatusAndRolls gameStatusAndRolls = crapsGame(gameStatus, rolls);
gameStatusAndRolls.getGameStatus();
Use List or an array, for example
public static List<Integer> crapsGame(String gameStatus, String rolls) {
return Arrays.asList(gameStatus, rolls);
}
private static final int GAME_STATUS = 0;
private static final int ROOLS = 0;
public static void main(String[] args) {
...
List<Integer> list = crapsGame(gameStatus, rolls);
... list.get(0)...list.get(GAME_STATUS);
... list.get(1)...list.get(ROOLS);
or
public static String[] crapsGame(String gameStatus, String rolls) {
return new String[] {gameStatus, rolls};
}
private static final int GAME_STATUS = 0;
private static final int ROOLS = 0;
public static void main(String[] args) {
...
String[] array = crapsGame(gameStatus, rolls);
... array[0]...array[GAME_STATUS];
... array[1]...array[ROOLS];
Use Map, for example
public static Map<String, String> crapsGame(String gameStatus, String rolls) {
Map<String, String> result = new HashMap<>(2);
result.put("gameStatus", gameStatus);
result.put("rolls", rolls);
return result;
}
public static void main(String[] args) {
...
Map map = crapsGame(gameStatus, rolls);
... map.get("gameStatus")...map.get("rolls");

Java enum alternative to how I did this?

Teaching myself Java by coding a MIDI handling program. One thing the program needs to be able to do is convert back and forth between MIDI note numbers and their corresponding compact string representations. I looked at using an enum setup, but due to naming constraints you can't do something like
c-1, c#-1, ... g9;
because of the sharps and negatives (yes, I'm following the convention that makes you end up with a negative octave :P).
It seemed clunky to have to make a conversion between what's allowed and what I want.
CNEG1("c-1"),
CSNEG1("c#-1"),
DNEG1("d-1"),
...
G9("g9");
So I came up with the static imports scheme below, and it works fine. However, I want to learn more about how to use enums, and I have a hunch that they might actually be somehow better suited to the task - if only I understood the ins and outs better. So that's my question: can anyone come up with an elegant way to provide the same functionality using an enum scheme? Moreover, would there be a strong argument for doing so?
public abstract class MethodsAndConstants {
public static final String TONICS[] = {"c","c#","d","d#","e","f","f#","g","g#","a","a#","b"};
static final NoteMap notemap = new NoteMap();
static class NoteMap{
static String map[] = new String[128];
NoteMap() {
for (int i = 0; i < 128; i++){
int octave = i/12 - 1;
String tonic = MethodsAndConstants.TONICS[i%12];
map[i] = tonic + octave;
}
}
}
public static int convert_midi_note(String name){
return indexOf(NoteMap.map, name);
}
public static String convert_midi_note(int note_num){
return NoteMap.map[note_num];
}
public static int indexOf(String[] a, String item){
return java.util.Arrays.asList(a).indexOf(item);
}
}
EDIT ------------------------------------------
After heavy consideration I think in this particular situation enums might be overkill after all. I might end up just using this code down here, same sort of static import approach but no longer even requiring anything like the NoteMap business up above.
note_num -> name conversions are really straightforward, and the name -> note_num stuff is just good ol' string-parsing fun.
public abstract class MethodsAndConstants {
public static final String[] TONICS = {"c","c#","d","d#","e","f","f#","g","g#","a","a#","b"};
static String convert(int i) {
String tonic = MethodsAndConstants.TONICS[i%12];
int octave = (i / 12) - 1;
return tonic + octave;
}
static int convert(String s) {
int tonic = java.util.Arrays.asList(MethodsAndConstants.TONICS).indexOf(s.substring(0,1));
if (s.contains("#")) tonic += 1;
int octave = Integer.parseInt(s.substring(s.length()-1));
if (s.contains("-")) octave -= 2; // case octave = -1
int note_num = ((octave + 1) * 12) + tonic;
return note_num;
}
}
You could use an enum to represent the pitch, but I might try encapsulating a Pitch in a class
public class Pitch {
private final int octave;
private final Note note;
public enum Note {
C("C",4), CSHARP("C#/Db",5), DFLAT("C#/Db",5), //and so on
private final String thePitch;
private final int midiAdjust;
private Note(final String thePitch, final int midiAdjust) {
this.thePitch = thePitch;
this.midiAdjust = midiAdjust;
}
String getThePitch() {
return thePitch;
}
int getMidiAdjust() {
return midiAdjust;
}
}
public Pitch(Note note, int octave) {
this.note = note;
this.octave = octave;
}
public int getMidiNumber(){
return 12*octave + note.getMidiAdjust();
}
}
This would account for the fact that the note (C, C#, D, D#, E...) is going to be one of a repeating set, but you could have all kinds of octaves, in this case handled by an int. It would greatly reduce the size of your enum.
EDIT: I added a few lines in here as an idea. You could pass a second parameter into the constructor of the enum to allow you to return a MIDI number representing the pitch. In this one I assumed that the lowest number represented by MIDI is an A, but I may be wrong on that. Also the 12*octave is intended to add a whole octave of pitches for each increment. You will probably have to adjust this slightly, as I see you are using that one weird notation.
Something like that:
public enum Note {
CNEG1("c-1"), CSNEG1("c#-1"), DNEG1("d-1");
private final String tonicOctave;
private Note(final String tonicOctave) {
this.tonicOctave = tonicOctave;
}
public String getTonicOctave() {
return this.tonicOctave;
}
public static Note fromTonicOctave(final String val) {
for (final Note note: Note.values()) {
if (note.getTonicOctave().equals(val)) {
return note;
}
}
return null;
}
}
Note, you can have as many parameters as you need in your enum, so if you need to separate tonic and octave, you can.

Categories

Resources