Is there a cleaner way of writing same method with different parameters? - java

I need to have multiple methods taking different parameters. Is there a cleaner way of writing those methods instead of declaring each one of them separately? I need 4 the same methods in total. Am I able to write one but let it decide what parameters are passed? Or do I have to end up copying and pasting first one 3 times and changing the parameters. Here are 2 of them
public String findLogNumber(XWPFWordExtractor we) {
int logIndex;
int logIndexEnd;
String logNumber = "";
if (we.getText().contains("Log ")) {
logIndex = we.getText().indexOf("Log ") + 4;
logIndexEnd = logIndex + 5;
logNumber = we.getText().substring(logIndex, logIndexEnd);
}
return logNumber;
}
public String findLogNumber(WordExtractor we) {
int logIndex;
int logIndexEnd;
String logNumber = "";
if (we.getText().contains("Log ")) {
logIndex = we.getText().indexOf("Log ") + 4;
logIndexEnd = logIndex + 5;
logNumber = we.getText().substring(logIndex, logIndexEnd);
}
return logNumber;
}

Both XWPFWordExtractor and WordExtractor extend org.apache.poi.POITextExtractor which defines the getText() method, so you only need a single method for those that takes POITextExtractor as parameter.
// Handles at least the two methods shown.
public String findLogNumber(POITextExtractor we) {
int logIndex;
int logIndexEnd;
String logNumber = "";
if (we.getText().contains("Log ")) {
logIndex = we.getText().indexOf("Log ") + 4;
logIndexEnd = logIndex + 5;
logNumber = we.getText().substring(logIndex, logIndexEnd);
}
return logNumber;
}

Write a method which takes the we.getText() as a String, and call from the other two methods:
public String findLogNumber(XWPFWordExtractor we) {
return common(we.getText());
}
public String findLogNumber(WordExtractor we) {
return common(we.getText());
}
private String findLogNumber(String text) {
// ...
}
Unless, of course, XWPFWordExtractor and WordExtractor implement a common interface or extend the same class. In which case:
public String findLogNumber(CommonInterface we) { ... }

Related

A method that calls another method for Strings

I have this assignment below:
I have two methods that modify strings simultaneously.
I have searched on many posts but couldn't find the answer.
I want the second method to modify (call) the result of the first one.
I am a neophyte to Java so thanks for your patience and understanding.
Assignment:
Part 1 - Normalize Text
Write a method called normalizeText which does the following:
Removes all the spaces from your text
Remove any punctuation (. , : ; ’ ” ! ? ( ) )
Turn all lower-case letters into upper-case letters
Return the result.
The call normalizeText(“This is some \“really\” great. (Text)!?”)
should return
“THISISSOMEREALLYGREATTEXT”
Part 2 - Obfuscation
Write a method called obify that takes a String parameter (the message to be obfuscated) and returns a string in which every vowel (A, E, I, O, U, Y) is preceded by the letters “OB” (be sure to use capital letters).
If we call obify on “THISISSOMEREALLYGREATTEXT”, it should return
“THOBISOBISSOBOMOBEROBEOBALLOBYGROBEOBATTOBEXT”
My code:
public class CryptoAssessment {
public static void main(String[] args) {
normalizeText("This is some \“really\” great. (Text)!?");
}
public static void normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print(Result_after_Normalization);
}
public static void Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print(Result_after_Obfuscation);
}
}
To pass the result of a call to method1() to a call to method2():
method2(method1("foo"))
To complete your assignment:
public static void normalize(String str) {
return str.replaceAll("\\W", "").toUpperCase();
}
public static void obfuscate(String str) {
return str.replaceAll("[AEIOU]", "OB$0");
}
Ah, I get your problem. You don't want to simply pring on the Console System.out - you need to return those strings back to the caller.
public static String normalizeText(String string_to_encrypt){
String upper_string = string_to_encrypt.toUpperCase();
String Capital_Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Result_after_Normalization = "";
for (int i = 0; i < upper_string.length(); i++) {
if (Capital_Letters.contains(Character.toString(upper_string.charAt(i))))
{
Result_after_Normalization = Result_after_Normalization + Character.toString(upper_string.charAt(i));
}
}
System.out.print("After normalization: "+Result_after_Normalization);
return Result_after_Normalization;
}
And lets make the other one return a String as well
public static String Obfuscation(String string_to_Obfuscate){
String Vowel_Letters = "AEIOUY";
String Result_after_Obfuscation = "";
for (int i = 0; i < string_to_Obfuscate.length(); i++) {
if (Vowel_Letters.contains(Character.toString(string_to_Obfuscate.charAt(i))))
{
Result_after_Obfuscation = Result_after_Obfuscation + "OB" + Character.toString(string_to_Obfuscate.charAt(i)) ;
}
else {
Result_after_Obfuscation = Result_after_Obfuscation + Character.toString(string_to_Obfuscate.charAt(i));
}
}
System.out.print("After obfuscation: "+Result_after_Obfuscation);
return Result_after_Obfuscation;
}
And now the main() becomes this:
public static void main(String[] args) {
String result = obfuscate(normalizeText("This is some \“really\” great. (Text)!?"));
System.out.println("Result after doing both: "+result);
}
Was typing this out last night when i ran out of battery, so ergo the delay in answering.
You can use a method's return as another method's argument, as long as the type match.
First change your methods' signature like this(make them to return a value):
public static String normalizeText(String string_to_encrypt){...}
public static String Obfuscation(String string_to_Obfuscate){...}
Then you can use the return value:
String temp = normalizeText("This is some \“really\” great. (Text)!?");
String result = Obfuscation(temp);
Or:
String result = Obfuscation(normalizeText("This is some \“really\” great. (Text)!?"));

Get type of arguments received as input from a file

I have a text file that I pass as an argument to my program. The file contains class names and arguments that I should instantiate:
Home:
SmartMeter:30,false
I want to create the instances, using reflection but I can't figure out how to get the actual type of the arguments I am getting from the file. After I get this I want to compare them to the parameter types of all the constructors for this class and pick the right one. Here is the code I have written so far:
Scanner scan = new Scanner(new File(args[0]));
String[] classNameAndParameters;
String[] parameters;
while (scan.hasNextLine()) {
classNameAndParameters = scan.nextLine().split(":");
Class<?> c = Class.forName(classNameAndParameters[0]);
// i check for the length too because it throws arrayoutofbounds exception
if (classNameAndParameters.length > 1 && classNameAndParameters[1] != null) {
parameters = classNameAndParameters[1].split(",");
// get all constructors for the created class
Constructor<?>[] constructors = c.getDeclaredConstructors();
for(int i = 0; i < constructors.length; i++) {
Constructor<?> ct = constructors[i];
Class<?> pvec[] = ct.getParameterTypes();
for (int j = 0; j < pvec.length; j++) {
System.out.println("param #" + j + " " + pvec[j]);
}
}
//i should match the parameter types of the file with the parameters of the available constructors
//Object object = consa.newInstance();
} else {
// default case when the constructor takes no arguments
Constructor<?> consa = c.getConstructor();
Object object = consa.newInstance();
}
}
scan.close();
You will need to specify the argument type in the text file otherwise it is impossible for Java to solve the ambiguity of some of the arguments in the runtime.
For example if you have class Book:
public class Book {
public Book() {
}
public Book(Integer id, String name) {
}
public Book(String idx, String name) {
}
}
And you supplied Book: 30, Hunger Games
How would the code knows which Constructor to pick since 30 is a legit integer and also legit String?
Assuming none of your constructors are ambiguous, here's how to do it:
String args[] = {"this is id", "this is name"};
Arrays.asList(Book.class.getConstructors()).stream()
.filter(c -> c.getParameterCount() == args.length).forEach(c -> {
if (IntStream.range(0, c.getParameterCount()).allMatch(i -> {
return Arrays.asList(c.getParameterTypes()[i].getDeclaredMethods()).stream()
.filter(m -> m.getName().equals("valueOf")).anyMatch(m -> {
try {
m.invoke(null, args[i]);
return true;
} catch (Exception e) {
return false;
}
});
}))
System.out.println("Matching Constructor: " + c);
});

Type mismatch: cannot convert from String to

I'm getting an error like this: Type mismatch: cannot convert from String to produktas ... I'm looking for the solution everywhere, but It seems too difficult for me. Would appriciate any help
My function is:
public static produktas[] surasti(produktas G[], int n) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
produktas A[] = new produktas[5];
for (int j = 0; j < 5; j++) {
System.out.println("Kokio produkto ieskosime?");
String found = in.readLine();
for (int i = 1; i < n; i++) {
if (found.equals(G[i].gautiPav())) {
A[j] = G[i].gautiPav(); // error line
}
}
}
return A;
} catch(IOException ie) {
ie.printStackTrace();
}
return null;
}
And my array class looks like:
class produktas {
private String pavadinimas;
private String salis;
private Double svoris;
private Double kaina;
produktas() {}
produktas(String pav, String salis, double svoris, double kaina) {
pavadinimas = pav;
this.salis = salis;
this.svoris = svoris;
this.kaina = kaina;
}
public String gautiPav() {
return pavadinimas;
}
}
A is an array of "produktas". You are trying to assign a string into it, that is the String that is returned by your gautiPav() method.
Are you sure you didn't mean to write this instead?
A[j] = G[i]; // error line
If you're seeing strings like this: name.produktas#60e53b93 then you should override the Object.toString() method to return a more human readable string, a typical example might look like this. If you're using any modern IDE such as Eclipse there is a helper for this, for Eclipse: Source, Generate toString()...
#Override
public String toString() {
return String.format("[produktas: %s]", pavadinimas);
}
Following discussion in the chat, it seems like you want to return A as produktas, but write/view the guatiPav() method where you reference A. You either need to override toString() if you want A to be represented differently than a series of "random" output:
class produktas {
private String pavadinimas;
private String salis;
private Double svoris;
private Double kaina;
produktas() {}
produktas(String pav, String salis, double svoris, double kaina) {
pavadinimas = pav;
this.salis = salis;
this.svoris = svoris;
this.kaina = kaina;
}
public String gautiPav() {
return pavadinimas;
}
#Override
public String toString() {
return guatiPav(); // or "return pavadinimas;"
}
}
Or you want to call gautiPav() directly wherever you're referencing the elements of A. I highly recommend the latter approach, as an Object's toString() should be descriptive of the Object, not a single parameter it is comprised of.

Printing Out a hashset to screen

I am attempting to print out a hashset taking in records from a database which are currently stored in two seperate ArrayLists. When I attempt to print out the HashSet the following error shows.
This is your HashSet[nyu.Sorting#378bf509, nyu.Sorting#7b23ec81, nyu.Sorting#15aeb7ab, nyu.Sorting#27d6c5e0, nyu.Sorting#7ef20235, nyu.Sorting#4f3f5b24, nyu.Sorting#6acbcfc0, nyu.Sorting#2d98a335, nyu.Sorting#5fd0d5ae, nyu.Sorting#16b98e56]
And this is my code:
public static HashSet<Sorting> t() {
Sorting s = new Sorting();
int TimeNeededOne = 75;
int TimeNeededTwo = 75;
int assignedTimeOne = 0;
int assignedTimeTwo = 0;
HashSet<Sorting> c = new HashSet<Sorting>();
for(int i=0; i<=i1.size()-1; i++)
{
if((assignedTimeOne < TimeNeededOne) && !(assignedTimeOne+ i1.get(i).getLengthMins() > offensiveTimeInMins) )
{
c.add(i1.get(i));
assignedTimeOne += i1.get(i).getLengthMins();
}
}
for(int i=0; i<=i2.size()-1; i++)
{
if((assignedTimeTwo < TimeNeededTwo) && !(assignedTimeTwo + i2.get(i).getLengthMins() > TimeNeededTwo) )
{
c.add(i2.get(i));
assignedTimeTwo += i2.get(i).getLengthMins();
}
}
System.out.println("Training programme :" + c.size());
System.out.println("This is your training programme" + c.toString());
return c;
}
The c.size is there to confirm that ten entries are made which is correct however the formatting of the records from the hashset obviously contains a problem. Any help with this issue would be greatly appreciated.
Thanks.
One way of doing this would be to override the toString() method of your Sorting class to print its contents:
public class Sorting {
...
#Override
public String toString() {
// Return a String that represents this object
return "...";
}
}
You need override toString() method in the Sorting class, for example:
class Sorting {
...
#Override
public String toString() {
// a string representation of Sorting object
}
}
java.util.Iterator runs through the whole collection and for each element invokes a toString() method. The data recorded in the java.lang.StringBuilder, which returns of its string representation at the end.

Setting up the Structure of a Polynomial

I'm trying to evaluate the structure of a polynomial by simply listing the coefficients and displaying them with a variable with its respected power. I'm not evaluating, I'm just trying to get the equation out there.
public class TestPolynomialBackup{
public static void main(String[] args){
Polynomial p1 = new Polynomial(4);
System.out.println(p1);
}
public static class Polynomial
{
private int[] coef;
private int power=3;
public Polynomial(int a ){
coef = new int []{4,3,2,1};
}
public String toString() {
for(int i=0;i<coef.length-1;i++){
String s = coef[2] + "x^" + power;
return s;
}
}
}
}
Output: TestPolynomialBackup.java:38: error: missing return statement
}
I keep getting that error at the toString() method. All i'm trying to do is to make a for-loop that will go down the array of coefficents with some conditions that will determine if the character "x" (variable) will appear as well as the power.
You might wanna get more familiar with Java and think about what you want this method to do:
public String toString() {
for (int i = 0; i < coef.length - 1; i++) {
String s = coef[2] + "x^" + power;
return s;
}
}
This is propably what you want:
public String toString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < coef.length; i++) {
if (i != 0)
s.append(" + ");
s.append(coef[i]);
s.append("x^");
s.append(i);
}
return s.toString();
}
Changes:
put return outside of loop
accumulate result instead of somehow always creating a new string
actually use your index i inside of the loop
let the loop go from 0 to coef.length - 1
added " + " as a delimiter
You should add a return after your for loop.
The compiler can't compile because if your loop is not executed, your method would return nothing.
But you should review the way your loop is working, since you have a return in it, it is executed only once.

Categories

Resources