String helper method - java

I need a little help on how i could put in a helper method. This is the helper method I wrote.
public static String helper(String help) {
help = help.toLowerCase();
help = help.replaceAll("\\s+", "");
}
and this is how i used it in main method.
String help = RecursivePalindrome.helper(x);
If I keep it like this then on the helper method they ask me for a return value but if i put the return help; then the method doesn't execute correctly. If I change the helper method to void then i cant put String help on my main method.
This is what happens when i run the program:
Enter a word to test whether it is a palindrome or not(press quit to end.): RaceCar
'RaceCar' is not a palindrome.
See i put the helperclass to ignore the upper cases but it wont. RaceCar would be a palindrome but the uppercase makes the program say its not.

I think you need this:
public static String helper(String help) {
help = help.toLowerCase();
help = help.replaceAll("\\s+", "");
help = help.replaceAll("\\p{Punct}", "");
return help;
}
Calling helper will return a String with all characters lowercased and every occurrence of whitespace or punctuation characters removed.
Example: helper("Race Car#") will return "racecar"

Your method should return String. Also String in Java is immutable, any modification of string returns new string. Try this:
public static String helper(String help) {
return help.toLowerCase().replaceAll("\\s+", "");
}

Here is a quick palindrom calculator I created that works for RaceCar.....using ako's helper method.
public class Main {
public static void main(String [] args){
System.out.println(palindrom(helper("RaceCar")));
}
public static String helper(String help){
return help.toLowerCase().replaceAll("\\s+", "");
}
public static boolean palindrom(String pal)
{
int end = pal.length()-1;
for(int i = 0; i<=pal.length()/2;i++)
{
if(pal.charAt(i)== pal.charAt(end-i));
else
{
return false;
}
}
return true;
}
}

Related

Java String... question regarding multiple inputs for a method

is it possible to create a class and have a String ... attribute that takes as many or as little strings as you put?
example:
please excuse my rough pseudocode, this is for java.
//this is the method:
public void getXXXX(String ...) {
//random code executes in a loop with as many as strings that are inputted
}
//this code calls it
getXXXX("Benjamin","Jordan","Steve")
getXXXX("Pengu","No")
getXXXX("hi")
Yes, what you entered will more or less work, you just need a parameter name after your type.
class StringDecorator {
public static String join(final String... strings) {
final var builder = new StringBuilder();
for (final var string : strings) {
builder.append(string);
}
return builder.toString();
}
}
Then invoke this somewhere
StringDecorator.join("Hello, ", "World!"); // "Hello, World!"

Return value of og the method is never used

public class prime {
public static String method(int n){
int cnt = 0;
for (int i = 2; i <n-1 ; i++) {
if (n%i==0)
++cnt;
}
if (cnt==0)
return "YES";
else
return "NO";
}
public static void main(String[] args) {
method(10);
}
}
IntelliJ is saying to me when i hover over name of my method that Return value of og the method is never used and when i hover over name of this method in main i get this message Result of 'prime.method()' is ignored and i dont know why. Any help? Also in console i get nothing. Just Process finished with exit code 0
You called method(), and it will return a String(YES or NO), but the return value was ignored. So IntelliJ IDEA reminds you to use it.
For example, print it:
String result = method(10);
System.out.println(result);
You are calling "method". It is returning a String. You do not assign it to a variable, i.e.
String value = method(10);
Methods can return values in Java, meaning they give a value back to the calling method. Your method "method(int)" returns a String to the main method.
However, the main method doesn't use the returned value.
If you want to print the value, you can use the following main method:
public static void main(String[] args) {
System.out.println(method(10));
}

String.replace result is ignored?

So i'm using IntelliJ and the replace buzzword is highlighted. Most of the tips are over my head so i ignore them, but what i got for this one was that the result of string.replace is ignored. Why?
would i need something like ( string = string.replace(string.charAt(i));)?
import java.util.Scanner;
public class PhoneNumberDecipher {
public static String phoneNumber;
public static String Decipher(String string) {
string = phoneNumber;
for(int i =0; i<=phoneNumber.length(); i++) {
if(string.equalsIgnoreCase("A")
||string.equalsIgnoreCase("B")
||string.equalsIgnoreCase("C")) {
string.replace(string.charAt(i),'2')
}
else if(string.equalsIgnoreCase("D")
||string.equalsIgnoreCase("E")
||string.equalsIgnoreCase("F")) {
string.replace(string.charAt(i),'3');
}
else if(string.equalsIgnoreCase("G")
||string.equalsIgnoreCase("H")
||string.equalsIgnoreCase("I")) {
string.replace(string.charAt(i),'4');
}
else if(string.equalsIgnoreCase("J")
||string.equalsIgnoreCase("K")
||string.equalsIgnoreCase("L")) {
string.replace(string.charAt(i),'5');
}
else if(string.equalsIgnoreCase("M")
||string.equalsIgnoreCase("N")
||string.equalsIgnoreCase("O")) {
string.replace(string.charAt(i),'6');
}
else if(string.equalsIgnoreCase("P")
||string.equalsIgnoreCase("Q")
||string.equalsIgnoreCase("R")
|| string.equalsIgnoreCase("S")) {
string.replace(string.charAt(i),'7');
}
else if(string.equalsIgnoreCase("T")
||string.equalsIgnoreCase("U")
||string.equalsIgnoreCase("V")) {
string.replace(string.charAt(i),'8');
}
else if(string.equalsIgnoreCase("W")
||string.equalsIgnoreCase("X")
||string.equalsIgnoreCase("Y")
||string.equalsIgnoreCase("Z")) {
string.replace(string.charAt(i),'9');
}
}
return string;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please Enter a Phone Number you Wish to Decipher...");
phoneNumber = input.nextLine();
System.out.print(Decipher(phoneNumber));
}
}
String objects are immutable.
From the docs:
public String replace(char oldChar,char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
Hope this helps.
IntelliJ is complaining that you're calling a method whose only effect is to return a value (String.replace) but you're ignoring that value. The program isn't doing anything at the moment because you're throwing away all the work it does.
You need to use the return value.
There are other bugs in there too. You might be able to progress a little further if you use some of this code:
StringBuilder convertedPhoneNumber = new StringBuilder();
// Your loop begins here
char curCharacter = phoneNumber.charAt(i);
if (curCharacter == 'a') {
convertedPhoneNumber.append("2");
}
// More conditional logic and rest of loop goes here.
return convertedPhoneNumber.toString();
I had the same problem, but i did it like this:
String newWord = oldWord.replace(oldChar,newChar);
use that statement
string = string.replace(string.charAt(i));
Why? String is an immutable object. Look at this thread to get a complete explanation. This a fundemental part of Java, so make sure you learn it well.
string = string.replace(string.charAt(i), '<The char to replace>') will work.
Refer to this article you might understand better:
https://alvinalexander.com/blog/post/java/faq-why-isnt-replace-replaceall-replacefirst-not-working/
Since string is immutable, you have to reassign the a string with the string.replace() string.

How to pass a String value to another class in Java

Currently, I am running into a problem in my Java code. I am somewhat new to Java, so I would love it if you kept that in mind.
My problem is with passing a String value from one class to another.
Main Class:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
Second:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
When I call the first class I am trying to grab the value of the second.
Disclaimer* the strings in this class were not meant to harm anyone. It was a joke between myself and my roommate from China, thanks.
It seems as if you want to obtain the character in your main class after the survey has completed, so it can be printed out in the main method.
You can simply change your void survey method to a String survey method, allowing you to return a value when that method is called:
class CharacterSurvey {
public String takeSurvey() {
//ask questions, score points
String character = null;
if(firstPerson == outcome) {
character = "First Person";
}
return character;
}
}
Now, when you call this method, you can retrieve the value returned from it:
class Main {
public static void main(String[] args) {
CharacterSurvey survey = new CharacterSurvey();
String character = survey.takeSurvey();
System.out.println(character);
}
}
There are several mistakes here.
First off, in your main class as you write you call the method survey() on the CharacterSurvey object but the survey itself the way it is implemented needs a String parameter to work
public void survey(String character)
Also this method returns void. If you want somehow to grab a string out of that method you need to declare the method as
public String survey() {}
this method returns a string now.
If i were to give a general idea, declare a String variable in the second class which will be manipulated inside the survey method and once the survey is declared as a String method return the value at the end inside the method.
By doing that you'll be able to receive the String value by calling the method on the characterSurvey object (and of course assign the value to a string variable or use it however).
Hope this helped

I have to test Java

I was told in my class that I have to write and test my code in the main method, I wrote it, but I dont know how to test it. How I am supposed to test my methods? I am supposed to take user input, and then get the get the first letter, last letter, etc.
import java.util.Scanner;
public class Word
{
public static void main(String[] args)
{
}
public String word;
public void Word()
{
String word = "";
}
public void Word(String word1)
{
String word = word1;
}
public String getWord()
{
return word;
}
public void setWord(String newWord)
{
String word = newWord;
}
public void getFirstLetter()
{
String firstLetter = word.substring(0, 1);
}
public void getLastLetter()
{
String lastLetter = word.substring(word.length() - 1, word.length());
}
public void removeFirstLetter()
{
String noFirstLetter = word.substring(1, word.length());
}
public void removeLastLetter()
{
String noLastLetter = word.substring(0, word.length() - 1);
}
public int findLetter (String parameter)
{
word.indexOf(parameter);
return 1;
}
}
You test your methods by calling them with some defined input and compare the results with your expected output.
Example:
Suppose you have a method like this:
public static int add(int a, int b) {
return a + b;
}
You'd test it like this:
int result = add( 3, 5);
if( result != 8 ) {
//method is wrong
}
So basically you define a "contract" of what input the method gets and what the result should be (in terms of return value or other changed state). Then you check whether you get that result for your input and if so you can assume the method works correctly.
In order to be quite sure (you often can't be perfectly sure) you'd test the method several times with different types of input (as many as reasonable, to test different cases, e.g. short words, long words).
You often also test how your method handles wrong input, e.g. by passing null or empty strings.
You should have a look at tools like junit.
You can create a simple Test class and test your class and its behavior.
imports ...;
public class MyTest{
#Test
public void testMyClass(){
Word w= new Word();
w.setWord("test");
Assert.assertEquals(w.getFirstLetter(), "t");
}
}
With tools like Eclipse you could nicely run such a test.
Just a hint: you're very close you need an instance of Word, than you can call your methods
public static void main(String[] args) {
Word test = new Word();
test.setWord("something");
// here you might read javadoc of the String class on how to compare strings
}
EDIT:
I overlooked this:
public void setWord(String newWord)
{
String word = newWord;
}
The code you've written creates a variable word and newWord is assigned to it and then disappears.
If you (obviously) want to set a member of a class you should use this wich references the instance (you created in main()).
public void setWord(String newWord) {
this.word = newWord;
}
Since I would say this is homework, I will try not to explicitly give the answer. In the main method, you should set your word, then call each method and print the output to verify it is correct.
Agree with Jason. If you wanna test something, simply System.out.println() it. In your methods though, your return type is not a String but a void, so you could change that, and print it out on the main program run.
If not, just put the System.out.println() in your void methods. Shouldn't have much of a problem!

Categories