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)!?"));
Related
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) { ... }
I have string and i need to print all the combination of the string Char's
Example
For the string "123" the output is:
1,2,3,12,13,21,23,31,32,123,132,213,231,312,321
It must be without loops, only with recursion.
Thanks!
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
I think just giving you the full code would be a little to easy for you. This is the simple set up for the code that you would want. The recurse method is not completely finished, the return statement being one of the things that you will need to fix first. By answer the question, this way, I hope that I am still answering the question, but also still allowing you to fully learn and understand recursion on your one. By the way,
for the public static void main(String [] args) part
You would also put that in a separate class like so:
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public class CharacterRecursionClient
{
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
That would work just as well if you are required to have a client class. I hope that this help and cleared up at least a couple of things.
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.
I have an abstract class that contains a variable of type String declared moneyString
String moneyString;
It contains data something like $123,456,789
So inside the abstract class I have function
void convertToInt(){
remove(',');
remove('$');
empMoney = Integer.parseInt(moneyString.substring(0, moneyString.length()) );
}
And my remove function
void remove(char character){
boolean moreFound = true;
String tempString;
int index;
do{
index = moneyString.indexOf(character);
tempString = moneyString;
if(index!=-1){
//From beggining to the character
moneyString = moneyString.substring(0,index);
//After the character to the end
tempString = tempString.substring(index,tempString.length());
moneyString += tempString;
}
else{
moreFound = false;
}
} while(moreFound);
} //END remove()
Isn't it supposed to get out of the loop when when moreFound = false?
The issue with your code is here,
tempString = tempString.substring(index,tempString.length());
Should be index + 1 because you don't want to include that character.
tempString = tempString.substring(index + 1,tempString.length());
But, I suggest you use a DecimalFormat and parse(String) the value. Like,
public static int convertToInt(String money) throws ParseException {
NumberFormat df = new DecimalFormat("$#,###");
return df.parse(money).intValue();
}
Then you can call it like
public static void main(String[] args) {
try {
System.out.println(convertToInt("$123,456,789"));
} catch (ParseException e) {
e.printStackTrace();
}
}
Output is
123456789
Indeed you have to change the line:
tempString = tempString.substring(index,tempString.length());
to:
tempString = tempString.substring(index+1,tempString.length());
The assignment could be done to a variable of type Long:
moneyString="$123,456,789,101";
long empMoney;
remove('$');
remove(',');
empMoney = Long.parseLong(moneyString.substring(0, moneyString.length()) );
I want the user to input a DNA sequence, if it doesn't have the letters A, C, T, or G then it should print out an error. But how can I scan the string entered for those specific characters in the constructot method DNASequence?
heres what I have so far.
import java.util.*;
public class DNASequence {
private String DNASequence;//create a private static variable that can be accessed
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please input a sequence of DNA: ");
String DNAInput = input.nextLine();
}
public DNASequence(String DNAStrand){//Constructor Method that takes parameter a string and checks to see if its only A, T, C, G.
DNASequence = DNAStrand;
// Invoke the countLetters method to count each letter
int[] counts = countLetters(DNAStrand.toUpperCase());
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0)
System.out.println((char)('a' + i) + " appears " +
counts[i] + ((counts[i] == 1) ? " time" : " times"));
}
}
/** Count each letter in the string */
public static int[] countLetters(String s) {
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
counts[s.charAt(i) - 'a']++;
}
return counts;
}
public String toString(){//Method that just returns the stored sequence
return DNASequence;
}
private static char NucleotideBaseCount(char BaseCount){//Method to count bases
}
private static boolean isSubsequenceOf(String DNAStrand){
}
}
You could use the following regular expression for this: ^[ACTG]+$.
To match the input string against the regex, use String.matches().
Here in a sample implementation based on #NPE 's comment:
import java.util.*;
public class DNASequence
{
private String DNASequence = null; //create a private static variable that can be accessed
public static void main(String[] args)
{
System.out.println("Please input a sequence of DNA: ");
DNASequence dnaS = new DNASequence((new Scanner(System.in)).nextLine().toUpperCase());
}
//Constructor Method that takes parameter a string and checks to see if its only A, T, C, G.
public DNASequence(String DNAStrand) throws IllegalArgumentException
{
if (DNAStrand.matches("^[ATCG]+$"))
{
DNASequence = DNAStrand;
}
else
{
throw new IllegalArgumentException("DNA Sequences should only contain A, T, C, G charaters");
}
}
/** Count each letter in the string */
public int[] countLetters() throws IllegalArgumentException
{
int[] counts = new int[4];
if (DNASequence != null)
{
for (int i = 0; i < DNASequence.length(); i++)
{
switch (DNASequence.charAt(i))
{
case 'A':
counts[0]++;
break;
case 'T':
counts[1]++;
break;
case 'C':
counts[2]++;
break;
case 'G':
counts[3]++;
break;
default:
throw new IllegalArgumentException("DNA Sequences should only contain A, T, C, G charaters, found: " + DNASequence.charAt(i));
}
}
}
return counts;
}
//Method that just returns the stored sequence
public String toString()
{
return DNASequence;
}
private char NucleotideBaseCount(char BaseCount){//Method to count bases
return 'a'; // replace with real implementation
}
private boolean isSubsequenceOf(String DNAStrand)
{
return false; // repalce with real implementation
}
}