What are helper objects in java? - java

I come across few of the times called helper objects... can anybody elaborate what are those helper objects and why do we need them?

Some operations which are common to a couple of classes can be moved to helper classes, which are then used via object composition:
public class OrderService {
private PriceHelper priceHelper = new PriceHelper();
public double calculateOrderPrice(order) {
double price = 0;
for (Item item : order.getItems()) {
double += priceHelper.calculatePrice(item.getProduct());
}
}
}
public class ProductService {
private PriceHelper priceHelper = new PriceHelper();
public double getProductPrice(Product product) {
return priceHelper.calculatePrice(product);
}
}
Using helper classes can be done in multiple ways:
Instantiating them directly (as above)
via dependency injection
by making their methods static and accessing them in a static way, like IOUtils.closeQuietly(inputStream) closes an InputStream wihtout throwing exceptions.
at least my convention is to name classes with only static methods and not dependencies XUtils, and classees that in turn have dependencies / need to be managed by a DI container XHelper
(The example above is just a sample - it shouldn't be discussed in terms of Domain Driven Design)

These are objects that "sit to the side" of the main body of code, and do some of the work for the object. They "help" the object to do it's job.
As an example, many people have a Closer helper object. This will take various closeable objects, for example, java.sql.Statement, java.sql.Connection, etc and will close the object, and ignore any errors that come out of it. This tends to be because if you get an error closing an object, there is not much you can do about it anyway, so people just ignore it.
Rather than having this boilerplate:
try {
connection.close();
} catch (SQLException e) {
// just ignore… what can you do when you can't close the connection?
log.warn("couldn't close connection", e);
}
scattered around the codebase, they simply call:
Closer.close(connection);
instead. For example, look at guava closeQuietly.

A 'helper' method is typically a method to make something easier, whatever it is. Sometimes they're used to make things more readable/clearly organized (some may argue this, but it's ultimately very subjective):
public void doStuff() {
wakeUp();
drinkCoffee();
drive();
work();
goHome();
}
Where, each 'helper method' on their own are fairly complex... the concept becomes really clear and simple.
Another very good use of helper methods is to provide common functionality across many different classes. The best example of this is the Math class which contains a ton of static helper methods to help you calculate things like the log of a number, the exponent of a number... etc.
Where you draw the line as to what's a helper method and what's just a regular method is pretty subjective, but that's the gist of it. Other answers here are pretty good too.

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class Helpers {
public static String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
return dateFormat.format(new Date());
}
public static boolean isTimeABeforeTimeB(String timeA, String timeB) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
Date dA = dateFormat.parse(timeA);
Date dB = dateFormat.parse(timeB);
if (dA.getTime() < dB.getTime()) {
return true;
} else {
return false;
}
} catch (Exception e) {
//
}
return false;
}
public static String getDateAndTimeInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
dateFormat.setLenient(false);
boolean dateValid;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
dateValid = true;
try {
Date d = dateFormat.parse(ans);
} catch (Exception e) {
dateValid = false;
}
} while (!dateValid);
return ans;
}
public static String getStringInput(String prompt) {
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print(prompt);
ans = input.nextLine();
ans = ans.trim();
} while (ans.length() == 0);
return ans;
}
public static double getDoubleInput(String prompt) {
Scanner input = new Scanner(System.in);
double ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
//Convert string input to integer
try {
ans = Double.parseDouble(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
inputValid = true;
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
public static int getIntegerInput(String prompt, int lowerBound, int upperBound) {
Scanner input = new Scanner(System.in);
int ans = 0;
boolean inputValid;
do {
System.out.print(prompt);
String s = input.nextLine();
// Convert string input to integer
try {
ans = Integer.parseInt(s);
if (ans >= lowerBound && ans <= upperBound) {
inputValid = true;
} else {
inputValid = false;
}
} catch (Exception e) {
inputValid = false;
}
} while (!inputValid);
return ans;
}
}
that is an example of of a Helper Class. It contains method which of are common use of the other classes in the project.
Example if someone wants to enter an Integer number from a class hew ill have to type in this: String num = Helpers.getIntegerInput("input your number");
The prompt is the output that is show to the user. Other examples to input a String, double, date and time etc.

Helper class, in my opinion, is similar to normal functions declared outside of classes in C++. For example, if you need a global constant for many classes, then you can define a helper class that encloses a final static const variable.

You can see a helper class as a toolbox that can be used by other classes to perform task like testing if a string is a palindrome, if a given number is prime, if an array contains negative number etc. You can create helper class by making all its methods static and its constructor private, and optionally you can also make the class final. Thus it can not be instantiated and one can easily access to all its methods directly.
public final class HelperClass{
private HelperClass(){
}
public static boolean isPositive(int number) {
if (number >= 0)
return true;
else
return false;
}
}
Here the function can be use directly to test a number :
HelperClass.isPositive(5);

this helper class help you to validate multiple edit text fields at once
public class MyHelperClass {
public void toast(Context context, String message){
Toast toast=new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(message);
toast.show();
}
public void validateEditText(Context context,List<EditText> editTextList)
{
boolean result=false;
for (int i=0;i<editTextList.size();i++)
{
if (editTextList.get(i).getText().toString().trim().equals(""))
{
result=true;
toast(context," Required fields are not empty !");
i=editTextList.size();
}
}
}
}

Related

I want to create a variable that can send int, float and double values to my custom ArrayList

I have my custom arraylist MyArrayList. That can only store int, float or double values. But i want to get that from user input. I have a temp String variable that gets input as string. Now I want to add that
arraylist. so the string has to be converted to its type first.
class MyArrayList<E> extends ArrayList<E>{
#Override
public boolean add(E e) {
if(e instanceof Integer || e instanceof Float || e instanceof Double) {
super.add(e);
return true;
} else {
throw new ClassCastException("Please enter Integer, Float or Double");
}
}
}
public class TestArrayList{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MyArrayList<Object> arraylist = new MyArrayList<>();
Object object = new Object();
try {
System.out.println("Enter Elements");
System.out.println("To stop input press '.'");
String temp;
while(scanner.hasNext()) {
temp = scanner.nextLine();
try {
object = temp;
} catch(Exception e) {}
if(temp.equals(".")) break;
else
arraylist.add(temp);
}
scanner.close();
System.out.println(arraylist.toString());
} catch(Exception e) {
System.out.println(e);
}
}
}
It's a bit odd requirement because you can only store Object in your class and you have to use instanceof when you get elements from a list. To convert the string a simple way is to try to convert and then catch but ignore any exception like this
public static Object convertToSomeNumber(String input) {
try {
return Integer.valueOf(input);
} catch (Exception e) {
}
try {
return Double.valueOf(input);
} catch (Exception e) {
}
return null;
}
Now you can use it on your temp variable and add the result to the list if it is not null.
Note that I ignored Float so you need to add that yourself if you want to support it.
You can try and I would also suggest to change your arrayList to use Number instead of Object. https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html
You now also could have Byte/Short and some other types in this array list (but you might even want this), but in general you won't need you your own implementation of the ArrayList.
List just only one type; if you want use more type in to list; use Object;
and it's not recommended;
any way, mabe have more ways to implements business;

Java: How do I prevent duplicates from being added to ArrayList using conditional statement?

I'm nearly finished with a program that gathers the user's inputs (keywords) and displays them. I have it functioning in that regard but I also need to prevent duplicate keywords from being added to the List using a conditional if statement. I know I'm on the right track, but having trouble wrapping my mind around the syntax and use of a boolean to compare the entered keyword with the existing ArrayList.
I know there are methods such as Hash/Set but I'd like to be able to do it with the conditional statement before I move onto other techniques. Every answer I've found in the search seems to explain the use of Hash.
Thanks!
UPDATE: Iv'e edited my code to what I currently have based on #Jacob 's answer and this is what I was looking for, so thanks for the response. But it's still not removing duplicates, it's like it's not checking the array and skipping right to alreadyExists == false conditional statement. Or am I not comparing the values correctly?
import java.util.*;
public class KeywordData {
private ArrayList<Keyword> keywords = new ArrayList<Keyword>();
public void create() {
InputHelper inputHelper = new InputHelper();
String prompt = "";
boolean isTrue = true;
while (isTrue) {
prompt = inputHelper.getUserInput("Enter a string, otherwise type 'n' to exit:");
if (!prompt.equals("n")) {
Keyword keyword = new Keyword();
keyword.setUserKeyword(prompt);
boolean alreadyExists = false;
for (Keyword keyword1 : keywords) {
if (keyword1.equals(keyword)) {
alreadyExists = true;
}
}
if (alreadyExists == false) {
keywords.add(keyword);
} else {
System.out.println("You already added that word");
}
} else {
break;
}
}
}
public void displayKeywords() {
System.out.println();
System.out.println("********** Your unique user keywords **********");
for (Keyword keyword : keywords) {
keyword.display();
}
System.out.println();
}
}
This is how I did it, I showed my whole program because I changed some of your custom classes to just strings, and didn't really know what those custom classes did.
import java.util.*;
import java.io.Console;
public class KeywordData {
private ArrayList<String> keywords = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
public void create() {
String prompt = "";
boolean isTrue = true;
while (isTrue) {
System.out.println("Enter a string, otherwise type 'n' to exit:");
prompt = reader.next();
if (!prompt.equals("n")) {
boolean alreadyExists = false;
for (String keyword1 : keywords) {
if (keyword1.equals(prompt)) {
alreadyExists = true;
}
}
if (alreadyExists == false) {
keywords.add(prompt);
}else {
System.out.println("You already added that word");
}
} else {
break;
}
}
}
public void displayKeywords() {
System.out.println();
System.out.println("********** Your unique user keywords **********");
for (String keyword : keywords) {
System.out.println(keyword);
}
}
public static void main(String[] args) {
KeywordData kd = new KeywordData();
kd.create();
kd.displayKeywords();
}
}
But the easier way to check is like this
if (!prompt.equals("n")) {
if (keywords.contains(prompt)) {
System.out.println("You already added that word");
}else {
keywords.add(prompt);
}
} else {
break;
}

Need a solution for using method [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
public class WaterHeater{
//public fields set to private
private double water = 1;
private double kilowatts= 2;
private double joules = 3600;
private double temp = 70;
private double jkg = 4200;
private double energy;
private double time;
//Constructor method
public WaterHeater (double water, double kilowatts, double joules, double temp, double jkg) {
}
//Accessors and mutators
//Accessor for Water
public double getWater() {
return water;
}
public void setWater(int water) {
this.water = water;
}
//Accessor for Kilowatts
public double getKilowatts() {
return kilowatts;
}
public void setKilowatts(int kilowatts) {
this.kilowatts = kilowatts;
}
//Accessor for Temperature
public double getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
//Method for Energy used
public double getEnergy() {
energy = water*jkg*temp;
return energy;
}
public void setEnergy() {
this.energy = energy;
}
//Method for Time to boil
public double getTime() {
time = energy/kilowatts;
return time;
}
public void setTime() {
this.time = time;
}
}
public class Kettle extends WaterHeater{
public Kettle(double water, double kilowatts, double joules, double temp, double jkg) {
super(water, kilowatts, joules, temp, jkg);
}
public static void main( String args[] )
{
userInput kettleinput = new userInput();
System.out.println("\nEnergy used: ");
System.out.println("Time to boil: ");
}
}
public class userInput {
public static void main(String args[])
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
double getWater;
// These must be initialised
String strWater = null;
int intWater = 0;
System.out.print("Enter amount of water used: ");
System.out.flush();
// read string value from keyboard
try {
strWater = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intWater = Integer.parseInt(strWater);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
double getKilowatts;
// These must be initialised
String strKilowatts = null;
int intKilowatts = 0;
System.out.print("Enter amount of Kilowatts used: ");
System.out.flush();
// read string value from keyboard
try {
strKilowatts = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intKilowatts = Integer.parseInt(strKilowatts);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
double getTemp;
// These must be initialised
String strTemp = null;
int intTemp = 0;
System.out.print("Enter the temperature of water raised by: ");
System.out.flush();
// read string value from keyboard
try {
strTemp = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTemp = Integer.parseInt(strTemp);
}
catch (NumberFormatException nfe) {
System.out.println("Whoops: " + nfe.toString());
System.exit(1);
}
}
}
Sorry for the long code. I have a problem finding a solution to display the result of the user inputs. I have the methods created in WaterHeater and i want to use them to calculate energy used and time to boil when the user enters Water, Kilowatts and Temp. The methods are already done i just cant find a way to use them. So when the Kettle class is running the user enters Water, Kilowatts and Temp and it will give a result. Any help is appriciated.
I would change the following:
move your code from the userInput main method into the constructor. Then all your variables that you need to use like intWater and intKilowatts i would make member variables. I would then provide public accessor methods.
Then your Kettle class main method you need to instantiate a new kettle and pass through the values from the user input class. Then you can just get the values you need from the kettle class which inherits from that water heater class and provides the required methods to output.
First off, you need to explain yourself a little better. I do not really understand what you really need but here is my try.
WaterHeater
You aren't setting the object's values within the custom constructor.
If some values are constants, just treat them as they are (private static final).
Values such time, energy don't need to be fields as they are calculated every time the user gets them.
Kettle & userInput
Both have a static function called main. That's illegal. I recommend you to move all the code in the latter function into the first one.
Kettle's main function's code do NOT make sense. That wouln't even compile.
userInput is a class so call it UserInput (be consistent).
Please, take a deep breath, get focused and explain better what you need and what you already have. Always try to show a code that, at least, compiles.

Delete else statement but requires else statment

So basically I'm doing a java tutorial but in order to follow along I need to make a class file. Everything was already given to me but it gives me an error. The error is: Delete else statement or something along those lines. But when I delete it it tells me to put another else statement there.
The code is : Is this a problem with eclipse or is there something wrong with the code?
import java.io.*;
import java.text.*;
public class In {
static InputStreamReader r = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(r);
// Read a String from the standard system input
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
return "";
}
}
// Read a number as a String from the standard system input
// and return the number
public static Number getNumber() {
String numberString = getString();
try {
numberString = numberString.trim().toUpperCase();
return NumberFormat.getInstance().parse(numberString);
} catch (Exception e)
{
// if any exception occurs, just return zero
return new Integer(0);
}
}
// Read an int from the standard system input
public static int getInt() {
return getNumber().intValue();
}
// Read a long from the standard system input
public static long getLong() {
return getNumber().longValue();
}
// Read a float from the standard system input
public static float getFloat() {
return getNumber().floatValue();
}
// Read a double from the standard system input
public static double getDouble() {
return getNumber().doubleValue();
}
// Read a char from the standard system input
public static char getChar() {
String s = getString();
if (s.length() >= 1)
return s.charAt(0);
else
return’\ n’;
}
}
What is actually causing the error here is that whatever messed up marks you have around \n are not apostrophes... I have no idea what they are. After rewriting the code exactly as you did, except with apostrophes (plus using curly braces in the if and else statements because I prefer it that way), there were no errors:
public static char getChar ()
{
String s = getString();
if (s.length() >= 1){
return s.charAt(0);
}else{
return '\n';
}
}
Please, in the future, make sure to use correct indentations in your questions to make it much easier for us to read.

My Java Program won't Compile

As I just stated above this program won't compile. In my IDE, TextPad, it gives me 2 errors in the createArray method. It says that both a right bracket and semicolon are expected in my return statement when I indeed have them there. Could someone help me out here?
public class Driver
{
private static int size;
private static String somePromptMessage;
private static boolean validInput;
private static String userData;
public static void main(String[] args) throws IOException
{
validInput = false;
BufferedReader keyboard;
keyboard = new BufferedReader(new InputStreamReader(System.in));
int result;
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
{
return result;
}
}
public static void print(int[]x)
{
System.out.println("The array contains" + size + "elements");
for(int i = 0; i<x.length; i++)
{
System.out.println(x[i]);
}
}
private static int[] createArray(int size)
{
return int[size];
}
You're missing the enclosing } for the class, but I'll assume that one is a copy-paste issue.
The actual problem I see is that you want
return new int[size];
instead of
return int[size];
in your createArray function.
I see an extra simi-colon here:
while(!validInput);
{
return result;
}
Update: It was brought to my attention that this is actually a do while so why the extra braces around the return statement?
remove braces after while across return result; as it is do-while:
do
{
somePromptMessage = "Enter an integer";
System.out.println(somePromptMessage);
String userData;
userData = keyboard.readLine();
System.out.println(createArray(10));
try
{
result = Integer.parseInt(userData);
}
catch(NumberFormatException nfe)
{
System.out.println("Value entered is invalid, try again");
}
}
while(!validInput);
return result;

Categories