How to fold away all variables to improve code readabillity? - java

In some my code i have a lot of variables. So to make it more readable i want to be able to fold them away so instead of this:
public class BIhcsAhuStartSeq_v2 {
int counterVal_1 =0;
int counterVal_2 =0;
String clear="";
String reset= "reset";
public void test(){
if(counterVal_1==1){setString(clear)}
}
}
I want to do something like the below example so i can fold all variables away. How can i do this?
public class BIhcsAhuStartSeq_v2 {
{
int counterVal_1 =0;
int counterVal_2 =0;
String clear="";
String reset= "reset";
}
//example, but i cant acces the variables in the constructor ?
public void test(){
if(counterVal_1==1){setString(clear)}
}
}

This has been asked several times here, on Stack Overflow.
Basically, the folding function implementation varies by IDE. For Eclipse, there was the Coffee-Bytes plugin to do custom (tagged), fold-able code blocks, but that has been abandoned.
https://code.google.com/archive/p/coffee-bytes/
Other mentions have been to use Jet Brains IDEA
https://blog.jetbrains.com/idea/2012/03/custom-code-folding-regions-in-intellij-idea-111/

Related

Can we use Setter Method in java to perform operations?

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.

How to create boolean array in global - Java

I want create Boolean array in global, here code i tried to make
public class BettingHandler extends BaseClientRequestHandler
{
public static int player[] = new int [100];
public static int i;
public static boolean playerAct[];
public void handleClientRequest(User user, ISFSObject params)
{
RouletteExtension gameExt = (RouletteExtension) getParentExtension();
if (BettingHandler.player[BettingHandler.i] != -1)
{
trace("player problem");
BettingHandler.player[BettingHandler.i] = user.getPlayerId();
BettingHandler.playerAct[BettingHandler.i] = true;
i++;
}
trace("If this showed, no error");
}
}
In Eclipse not showed redcross sign in left this code
public static boolean playerAct[];
and here
BettingHandler.playerAct[BettingHandler.i] = true;
I make this for handler in SFS2X, so i check error in SFS2X zone monitor but unfortunately, this script just run till this
trace("player problem");
when remove this code
BettingHandler.playerAct[BettingHandler.i] = true;
script run till this
trace("If this showed, no error");
so i know something wrong with BettingHandler.playerAct[BettingHandler.i] = true;, How could I fix my code?
You never initialized the array but you are trying to use it.
public static boolean playerAct[] = new boolean[100];
Funny thing:
public static int player[] = new int [100];
public static int i;
public static boolean playerAct[];
The first array, there you actually create an array for 100 elements.
You omit that step for your second array. And you are really surprised that the second gives you problems?
Besides: whatever framework your are working with; maybe you should first step back and learn some more about the basics of Java. For example, the above code might work when fixed; but doing everything with public static variables ... looks very much like bad design.

stackoverflowerror null

The error i am having here is a infinite or near infinite loop in my method calls and class's creating other class's constructors. What my program is trying to do is semi-randomly generate survey results based off actual statistics. I would highly appreciate not only some insight in whats going wrong here. But some advice and pointers on how to prevent this from happening and ways to analyze the error messages by myself. I get how some of the work but like i stated below i am new to programming im a freshman in college so programming is new to me. Thanks in advance and sorry for my previous post, thought i would take the time to give you guys an appropriate one.
Im new to programming this is my 2nd project ive done on my own so im sorry if its not the best.
This is my Test class:
public Tester()
{
randomGenerator = new Random();
probability = new Probability();
stats = new Statistics();
double chance = randomGenerator.nextDouble();
double gender = probability.getProbabilityOfMale();
if(chance > gender)
{
male = false;
stats.incrementFemale();
}else{
male = true;
stats.incrementMale();
}
age = randomGenerator.nextInt(49)+16;
int range = stats.getNumberOfQuestion();
for(int i=0;i<range;i++)
{
probabilities = probability.probOfAnswer(i);
answers = probability.getAnswers(i);
chance = randomGenerator.nextDouble();
int size = probabilities.size();
for(int j=0;j<size;j++)
{
double qTemp = chance - probabilities.get(j);
if(qTemp <= 0.0)
{
Answer aTemp = answers.get(j);
aTemp.incrementCounter();
answers.set(j,aTemp);
}
}
}
}
Statistics class:
public ArrayList<Answer> getAnswers(int index)
{
temp = survey.getAnswers(index);
return temp;
}
public int getMale()
{
return male;
}
public int getFemale()
{
return female;
}
public int getNumberOfQuestion()
{
return numberOfQuestion;
}
public void incrementNumberOfQuestion()
{
numberOfQuestion++;
}
public void incrementMale()
{
male++;
}
public void incrementFemale()
{
female++;
}
and probability class:
public Probability()
{
stats = new Statistics();
probOfAnswer = new ArrayList<Double>(0);
}
public ArrayList<Double> probOfAnswer(int index)
{
temp = stats.getAnswers(index);
int size = temp.size();
for(int i=0;i<size;i++)
{
aTemp = temp.get(i);
for(int j=0;j<size;j++)
{
Answer aTemp = temp.get(j);
sum += (double)aTemp.getCounter();
}
double number = (double)aTemp.getCounter();
probOfAnswer.add(number/sum);
sum = 0;
}
return probOfAnswer;
}
public ArrayList<Answer> getAnswers(int index)
{
temp = stats.getAnswers(index);
return temp;
}
public ArrayList<Double> getProbofAnswer()
{
return probOfAnswer;
}
public void probabilityOfMale()
{
double male = (double)stats.getMale();
double female = (double)stats.getFemale();
probabilityOfMale = male / (male + female);
}
public double getProbabilityOfMale()
{
return probabilityOfMale;
}
These are the only real important parts where the loop exsists the rest of the code is not needed to be uploaded.
Im having difficulty uploading my error message on this site its not accepting it as code in the code insert, then it wont let me submit the message afterwards so im going to upload the code elseware and link it.
http://forum.overdosed.net/index.php/topic/56608-this-is-unimportant/
But i dont know how long that forum will let me keep that post there ><
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Probability.<init>(Probability.java:19)
You need to check why Question is creating Statistics object and again Statistics is trying to create Question object leading to infinite recursion. As the line numbers are given you can take a look at corresponding lines.
Judging by the stack trace, the problem lies in three parts which you haven't shown us - the Question and Statistics constructors and the Survey.addQuestion method:
From the stack trace:
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
at Survey.addQuestion(Survey.java:23)
at Statistics.<init>(Statistics.java:52)
at Question.<init>(Question.java:17)
So your Question constructor is calling the Statistics constructor. But the Statistics constructor is then calling Survey.addQuestion, which is in turn calling the Question constructor.
It feels to me like there's much more construction going on than is really useful. Why would a Statistics constructor need to add anything to a survey? I wouldn't expect a Statistics class to even know about surveys and questions.
It's entirely possible that a lot of this can be fixed by passing a reference to an existing object to the constructors - so the Probability constructor may be better taking a Statistics reference in its constructor and using that for its stats field than creating a new Statistics object itself. It's hard to say without knowing what these classes are really meant to represent though... which may be part of the problem. Do you have a firm grasp of what the responsibility of each class is? Think about that carefully before making any code changes.
We don't have the relevant source code, but the error message says what's wrong:
Tester creates a Probability
Probability constructor creates a Statistics
Statistics constructor calls Survey.addQuestion()
addQuestion() creates a Question
Question creates a Statistics (goto 3 and loop infinitely)
I think you should probably pass objects around rather than creating them each time.

Java: setting a objects variable in outside function

public static void main(String[] args) {
Player Anfallare = new Player("A");
Player Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
(...)
}
Is what I have in main function, now I made a own function,
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1;
}else{
Forsvarare.armees-=1;
}
}
which should set the object's variable to -=1.. But this doesn't work because the function doesnt know that Anfallare and Forsvarare is an object..
What can i do in this case?
You need to define the Players as class fields, instead of inside the main method.
For a gentle introduction to Java, I suggest you to start reading here:
http://download.oracle.com/javase/tutorial/java/index.html
Also, there are great book suggestions here: https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far . Some of those books are great to begin learning.
Example here:
public class Game {
private static Player Anfallare, Forsvarare; // <-- you define them here, so they are available to any method in the class
public static void main(String[] args) {
Anfallare = new Player("A"); // <-- it is already defined as a Player, so now you only need to instantiate it
Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
// ...
}
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1; // <-- it is already defined and instantiated
}else{
Forsvarare.armees-=1;
}
}
}
While Aleadam's solution is by far the best answer, another thing you could do to specifically resolve this issue is change the arguments of the function:
public static void MotVarandra(Player a, Player f){
if(f.getDice(1) >= a.getDice(1)){
f.armees-=1;
}else{
a.armees-=1;
}
}
Ultimately, your optimal solution just depends on what your program is doing. Chances are, this is just another way of looking at it.
As a side note, be sure to use descriptive naming techniques, a and f are somewhat hard coded, and only make sense if you use only those variable names for your Players. It's best to not potentially limit your code.

Multiple open and close curly brackets inside method. - Java

public class MyTestClass {
public static void main(String[] args) {
new MyTestClass().myMethod();
}
public void myMethod(){
{
//do something
}
{
//do something
}
{
//do something
}
}//method close
}//class close
What is the benefit of doing this? I have seen this kind of code.
It is not common practice to do this kind of thing, and I wouldn't do it normally.
They are defined as Blocks in the JLS, here.
Those inner blocks ( i.e. { ... } ) can serve a couple of purposes:
Blocks limit the scope of any variables declared within them; e.g.
public void foo() {
int i = 1;
{
int j = 2;
}
// Can't refer to the "j" declared here. But can declare a new one.
int j = 3;
}
However, I wouldn't recommend doing this. IMO, it's better to use different variable names OR refactor the code into smaller methods. Either way, most Java programmers would regard the { and } as annoying visual clutter.
Blocks can be used to attach labels.
HERE : {
...
break HERE; // breaks to the statement following the block
...
}
However, in practice you hardly ever see labelled break statements. And because they are so unusual, they tend to render the code less readable.
public void stuff() {
int i = 48;
{
int i = 21;
System.out.println(i); // prints 21
}
System.out.println(i); // prints 48
}
Basically, it's a way to create scopes smaller than entire function... Benefit?.. have the people stare at your code longer before they understand it... IMO it's bad style and should be avoided

Categories

Resources