Reverse and compare String - java

I have started to learn java and I've run into some trouble. Just wondering why my compare string function is not working and always returning true;
The purpose of the program is to take an input of a string, reverse the string and see if the string is the same as the original input (palindrome).
import java.util.Scanner;
public class palinedromeString {
private static Scanner keyboard;
public static void main(String[] args) {
System.out.println("Please enter a Palindrome");
keyboard = new Scanner(System.in);
String input = keyboard.next();
String original = input;
System.out.println("You entered: " + original);
System.out.println("Your String reversed is:" + " " + stringReverse(input));
System.out.println(checkString(input, original));
}
public static String stringReverse(String a) {
String result = "";
for(int i = a.length()-1; i>=0; i--){
result = result + a.charAt(i);
}
return result;
}
public static boolean checkString(String a, String b){
if(b.equals(a)){
return true;
}
else{
return false;
}
}
}

stringReverse returns the reversed String (it doesn't operate in place). Update input and your code should work as expected. Something like,
input = stringReverse(input);
System.out.println("Your String reversed is:" + " " + input);
Also, checkString is equivalent to
return b.equals(a);

Because you are passing input and original to the checkString() method. those two hold the same values. It's obvious you get true always.
checkString(stringReverse(input), original);
You have to use the above instead.

You have different options.
Assign the
stringReverse(input)
to a variable like
input=stringReverse(input);
before checking
Imesha Sudasingha's answer.
The thing is you are reversing the string into a different variable and it doesnot get reflected in the String you pass unless you explicitly assign it.

Here in checkString(input, original) method, both the parameter has same value, Hence it always returns true.
You have to pass original and reversed string like this:
String reversedStr = stringReverse(input);
checkString(reversedStr , original);

Related

How do I convert a String into doubles to compute average in Java?

I need help with an assignment. There are many similar questions on here, but those answers are not working for me so I don't know what I'm doing wrong.
The assignment is "The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the program calculates the average of those numbers, and displays the numbers and their average to the user."
We need to call to different methods to do this. The part that's giving me problems is converting the String to doubles and finding the average. We also need to validate that there are between 5-10 numbers in the String (I can validate it once I get it to count properly). I've tried a few things, including answers to similar questions on here (shown in code below), but the only output I get is 0.0.
Here is my code:
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.next();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
Thank you so much for any help!
It seems you have an error in your main method and need to set the getNumbers equal to the getNumbers method and the same with the calcaverage double with the calcaverage method.
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers();
calcAverage(getNumbers);
System.out.println(calcAverage);
}
should be
public static void main(String[] args) {
String getNumbers = "";
double calcAverage = 0;
getNumbers =getNumbers();
calcAverage =calcAverage(getNumbers);
System.out.println(calcAverage);
}
You can use streams to make it more readable and avoid and external iterations
import static java.util.Arrays.stream;
import java.util.OptionalDouble;
class Scratch {
public static void main(String[] args) {
OptionalDouble optAvg = calcAverage("2 5 6 7 8 9 0 1");
if (optAvg.isPresent()) {
System.out.println("optAvg.getAsDouble() = " + optAvg.getAsDouble());
}
}
public static OptionalDouble calcAverage(String userNumbers) {
String[] inputArr = userNumbers.split(" ");
int count = inputArr.length;
System.out.println("count = " + count);
if (count < 5 || count > 10) {
throw new IllegalArgumentException("Or do some other this here!");
}
return stream(inputArr)
.mapToDouble(
Double::parseDouble) // throws a NumberFormatException if it can't convert to Double
.average();
}
}
Or even simpler
import static java.util.Arrays.stream;
import java.util.DoubleSummaryStatistics;
class Scratch {
public static void main(String[] args) {
DoubleSummaryStatistics doubleSummaryStatistics = calcAverage("2 5 6 7 8 9 0 1");
System.out.println("count = " + doubleSummaryStatistics.getCount());
System.out.println("average = " + doubleSummaryStatistics.getAverage());
}
public static DoubleSummaryStatistics calcAverage(String userNumbers) {
return stream(userNumbers.split(" "))
.mapToDouble(Double::parseDouble)
.summaryStatistics();
}
}
Here you go:
public static void main(String[] args) {
String numberString = getNumbers();
double averageNum = calcAverage(numberString);
System.out.println(averageNum);
}
public static String getNumbers() {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter 5 to 10 numbers separated by spaces: ");
String getNumbers = scnr.nextLine();
return getNumbers;
}
public static double calcAverage(String userNumbers){
double calcAverage = 0.0;
double i = 0;
double count = 0.0;
Scanner str = new Scanner(userNumbers);
while (str.hasNextDouble()){
count++;
i = i + str.nextDouble();
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i/count;
return calcAverage;
}
A few changes, but you had it right for the most part. Going from the top of the file:
Removed getNumbers and calcAverage
Added numberString and averageNum (when you call functions with return, you need to store the value that it returns into a variable)
changed line:
String getNumbers = scnr.next();
to:
String getNumbers = scnr.nextLine();
Let me know if you have any questions.
Here is one way to do it with supplied values validation :
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNext()) {
String val = str.next();
// Is the supplied numerical value valid?
if (!val.matches("-?\\d+(\\.\\d+)?")) {
//No...
System.out.println("Supplied value of " + val +
" is ignored since it is not a valid numerical value!");
continue;
}
count++; // count now that we know the value is indeed valid.
i += Double.parseDouble(val);
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}
Since you are processing a supplied whitespace delimited string of hopefully numerical values you can merely utilize the the Scanner#hasNext() method in conjunction with the Scanner#next() method.
Preparing the Scanner object:
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
Here we take the string contained within the supplied userNumbers string variable and trim off any possible leading and trailing white-spaces, we don't want these if there are any. We also replace any portion of the supplied string that may contain more than a single whitespace with just a single whitespace. We want to enforce this format before we proceed so as to help with eliminating any possible type of conflict later on in method code. You can't always rely on the User to provide everything perfectly all the time so if you can help then it's worth it.
Retrieving each supplied value from the supplied String:
while (str.hasNext()) {
String val = str.next();
// ... other code ...
}
The hasNext() method will allow the loop to continue for as long as there is another whitespace delimited string token to process. In this case we're hoping that each token will be a string representation of a numerical value.
Because the hasNext() method has let us get this far into the loop we know there is another String token available. The str.next() call retrieves that available token and in this case, is placing that string token into the string variable named val. This is done upon each iteration of the while loop until there are no more tokens remaining to process.
Validating a retrieved string token:
if (!val.matches("-?\\d+(\\.\\d+)?")) { ... }
Validation of each string token is done here utilizing the String#matches() method along with a specific Regular Expression (regex) of "-?\\d+(\\.\\d+)?". When passed in the matches() method, this regex checks to see if the string it is played against is indeed a string representation of a signed or unsigned integer or floating point numerical value:
-? Optional. Value is prefixed with '-'.
\\d+ One or more digits.
(\\.\\d+)? Optional. Value is post-fixed with a decimal point
and one or more digits.
In this case we're checking to see if the token is invalid and if it is we supply a message to the console window indicating as such and the fact that this token value will be ignored. We ignore it by using the continue keyword which forces the while loop into it's next iteration and bypassing the remaining code within the loop.
Converting a String numerical value to a Double data type:
count++; // count now that we know the value is indeed valid.
i+= Double.parseDouble(val);
We do the count after knowing the value provided is indeed valid. i was previously declared as a double type and sums the token numerical value after it is converted to double with the Double.parseDouble() method. Using i += is the very same as i = i +.
Another shorter way:
public static double calcAverage(String userNumbers) {
double calcAverage = 0.0;
double i = 0;
int count = 0;
Scanner str = new Scanner(userNumbers.trim().replaceAll("\\s+", " "));
while (str.hasNextDouble()) {
double val = str.nextDouble();
count++;
i+= val;
}
System.out.println("count=" + count); //test to check it is counting properly
calcAverage = i / count;
return calcAverage;
}

Passing over values from one method to another on

The purpose of my code is to determine if a string entered by a user is a palindrome (meaning that the spelling of the word backwards and normally is the same). I am supposed to do this using 2 methods, the first one (reverse) which reverses the word. In this method, the string of the reversed word is returned, but I need to use it on the other method (isPalindrome) to compare if both the original text and the reversed word are spelled the same. How do I use the string being returned in the reverse method on the method isPalindrome?
import java.util.Scanner;
public class Palindromes
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Type in your text:");
String palindrome = input.nextLine();
reverse(palindrome);
if(isPalindrome(palindrome))
{
System.out.println("Your word is a palindrome!");
}
else
{
System.out.println("Your word isn't a palindrome!");
}
}
public static boolean isPalindrome(String text)
{
boolean value = false;
if(reverse.equals(text))
{
value = true;
}
return value;
}
public static String reverse(String text)
{
String reverse = "";
for(int i = text.length()-1; i>=0; i--)
{
reverse = reverse + text.substring(i, i+1);
}
return reverse;
}
}
In your isPalindrome() method, you just need to call:
return text.equals(reverse(text));
No need for the intermediate boolean value.
And to take it one step further, no need for the reverse logic either, since you can just use StringBuilder.reverse().

I need to convert a void out put into a string so that i can compare the two strings

My program is supposed to generate a pattern of letters based on the input of the user. I have to use recursion to set each output to be different. I've already done this. Next i have to compare the two outputs in another method and use recursion to find the length of the longest common sub sequence between the two. The problem is i dont know how to compare them. Since they are void results i dont know how to convert them to strings.
import java.util.Scanner;
public class patternOfLetters {
private static String letter;
public static void printLetterPattern(char letter){
char [] pattern = new char[1];
int patternLength= pattern.length;
String result="";
char start=letter;
if(start=='A'){
System.out.print('A');
result+='A';
}else if(start=='B'){
printLetterPattern('A');
System.out.print('B');
printLetterPattern('A');
}
else if(start=='C'){
printLetterPattern('B');
System.out.print('C');
printLetterPattern('B');
}
else if(start=='D'){
printLetterPattern('C');
System.out.print('D');
printLetterPattern('C');
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
Scanner otherIn = new Scanner(System.in);
System.out.println("Enter a character to start the pattern: ");
String input = in.nextLine();
String upper = input.toUpperCase();
char letter=upper.charAt(0);
System.out.println("");
System.out.println("Your first pattern of letters is:");
printLetterPattern(letter);
System.out.println("");
System.out.println("");
System.out.println("Enter another character to generate your second pattern: ");
String input2 = in.nextLine();
String upper2 = input2.toUpperCase();
char letter2=upper2.charAt(0);
System.out.println("");
System.out.println("Your second pattern of letters is:");
printLetterPattern(letter2);
in.close();
otherIn.close();
}
}//fin.
You cant, return type "void" means there is no result returned, so there is nothing you could convert.
Your methods just print their output to the console, you will need to rewrite them so they actually return a result.
One way could be like this (pseudocode):
public String produceLetterPattern(String pattern, char letter) {
...
if(start=='A') {
pattern+="A";
return pattern;
} else if (start=='B') {
pattern = produceLetterPattern(pattern, 'A');
pattern +="B";
pattern = produceLetterPattern(pattern, 'A');
return pattern;
} ...
}
That's the general idea, you should be able to work it out from there. Important part is that you need a result returned, in the above example a String, returned via
return pattern;

Verify the palindrome in Java. Can you help me to find what's the issue with this code

Can you help me to find the bug in this code. When I test this with a string that is not a palindrome, I get the message that it is a palindrome.
import java.util.*;
public class Main{
public static void main(String args[]){
String input = "";
System.out.println("Enter the string to verify palindrome");
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
Main m = new Main();
if(m.palindrome(input))
System.out.println(" The string " + input + " is a palindrome ");
else System.out.println(" The string " + input + " is not a palindrome ");
}
private boolean palindrome(String input){
String reverse = input;
int j;
for(int i=0;i<=reverse.length()-1;i++){
for( j=reverse.length()-1;j>=0;){
if(reverse.charAt(i)== reverse.charAt(j)){
return true;
}
else{
return false;
}
}j--;
}
return false;
}
}
if(reverse.charAt(i)== reverse.charAt(j)){
return true;
}
You are returning true if the first and the last character are the same without going on to check any other character.
I'd say the better approach is to continue stepping through the word until you find a character that does not match or until you finish. If you find a character that does not match, return false. If you finish, return true.

Java static method can't compile

the following messege appears when I compile this code.
ExtractChars(java.lang.String,int) in
Question2 cannot be applied to ()
What should I fix?
Thanks.
import java.util.Scanner;
public class Question2
{
public static void main (String[] args)
{
ExtractChars();
}
public static String ExtractChars(String sOrg, int startPos)
{
Scanner scan = new Scanner (System.in);
String value = "";
System.out.print("Enter a string: ");
sOrg = scan.next();
System.out.print("/nEnter an integer: ");
startPos = scan.nextInt();
if (sOrg.length()<=startPos)
{
value = "";
}
else
{
for (int i=startPos; i<sOrg.length();i=i+2)
{
value = value + sOrg.charAt(i);
}
}
return value;
}
}
This is because the function ExtractChars expects two arguments but you are not passing any.
EDIT:
Looks like you are reading input sOrg and startPos and there is no need to pass them as arguments, you can make them local variables.
So change:
public static String ExtractChars(String sOrg, int startPos)
{
....
to
public static String ExtractChars()
{
String sOrg;
int startPos;
....
Also, you are just discarding the return value of the function ExtractChars in main. You might want to print the extracted characters returned by the function (as a string) as:
System.out.println("Extracted Characters = " + ExtractChars());
in your main in place of
ExtractChars();
You've defined your method to expect two arguments, but you're really using them as though they were local variables, prompting the user to enter values for them.
You should probably rewrite your method something like this
public static String ExtractChars()
{
String sOrg;
int startPos;
Scanner scan = new Scanner (System.in);
String value = "";
System.out.print("Enter a string: ");
sOrg = scan.next();
System.out.print("/nEnter an integer: ");
startPos = scan.nextInt();
if (sOrg.length()<=startPos)
{
value = "";
}
else
{
for (int i=startPos; i<sOrg.length();i=i+2)
{
value = value + sOrg.charAt(i);
}
}
return value;
}
so that sOrg and startPos are local variables in your method instead of arguments to it.
The method call as you have it will then compile.
You're also not doing anything with the return value of this function, so it may seem like nothing is happening. But this might get you on your way.
You have to use arguments when you call ExtractChars. ExtractChars wants a String and an int. When you call it, you're passing nothing.
its the arguments. You're calling a function which expects 2 arguments. The compiler generated message atlest points to that.

Categories