public class reverserapp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter a word");
String str = scan.nextLine();
String reverse = "";
for( int i = str.length() - 1; i >= 0; i--)
reverse += str.charAt(i);
if(reverse.equalsIgnoreCase(str))
System.out.println("Palindrome");
else System.out.println("Not Palindrome");
}
}
This is my palindrome code. I'm doing this for a small assignment. I can get single words to work but if I write a something like "Don’t nod" it shows up as not palindrome. How can I achieve this? I'd like for my code to ignore punctuation's and white space.
So in the end result should be like "dontnod"
Thanks in advance for any help, complete noob at this.
Remove all non-letter characters, then put the resulting String to lower case .
str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();
You can use the replace function from StringUtils.
Example:
StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa
You can define a regex to remove punctuation and space, and perform a String replace on input, e.g.:
String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));
Related
I am currently in a computer programming class and at a dead end for "creating a template" for this 2-person hang man game.
First, person#1 is prompted for a phrase (contains all lowercase)
Then, I must take whatever phrase they choose and turn it into a template with all ?'s.
Then, as person#2 guesses letters, I must "reveal" the phrase and have the ?'s turn into the phrase letters.
I can't get past turning it into the template though. An example is:
person#1's phrase: "hello world"
desired template outcome: "????? ?????"
This is what I have so far... I'm having trouble at public static String createTemplate(String sPhrase)
import java.util.Scanner;
public class Program9
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
Scanner stdIn = new Scanner (System.in);
int cnt = 0; //counter is set to zero
String sPhrase;
boolean def;
System.out.print("Enter a phrase consisting of only lowercase letters and spaces: ");
sPhrase = scanner.nextLine(); //reads into variable set to Scanner.nextLine()
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String template = createTemplate(sPhrase); //will run through "createTemplate" and show whatever on there.
do
{
char guess = getGuess(stdIn); //will run through "getGuess" and show whatever SOP and return from that. WORKS.
cnt = cnt + 1; //counts the guess
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String updated = updateTemplate(template, sPhrase, guess); //runs throuhgh and prints updated template
} while (!exposedTemplate(sPhrase)); //will loop back if updated template still has ?'s
System.out.println("Good job! It took you " + cnt + " guesses!");
}
public static String createTemplate(String sPhrase)
{
String template = null;
String str;
sPhrase.substring(0, sPhrase.length()+1); //not sure if +1 needed.
sPhrase.equals(template);
//THIS IS WHERE IM HAVING PROBLEMS
}
public static char getGuess(Scanner stdIn)
{
//repeatedly prompts user for char response in range of 'a' to 'z'
String guess;
do
{
System.out.print("Enter a lowercase letter guess : ");
guess = stdIn.next();
} while (Character.isDigit(guess.charAt(0)));
char firstLetter = guess.charAt(0);
return firstLetter;
}
public static String changeCharAt(String str, int ind, char newChar)
{
return str.substring(0, ind) + newChar + str.substring(ind+1);
//freebie: returns copy of str with chars replaced
}
public static String updateTemplate(String template, String sPhrase, char guess)
{
//will have to include changeCharAt
}
public static boolean exposedTemplate(String template)
{
// returns true exactly when there are no more ?'s
}
}
A simple solution would be:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll("[a-zA-Z]", "?");
}
the replaceAll method of the String class in Java replaces all parts of the string that match the supplied regular expression with a string (in this case ?)
Learning regular expressions (known as regexes) may not be in the scope of this assignment, but is a very useful skill for all computer programmers. In this example I've used the regular expression [a-zA-Z] which means replace any upper or lower case character, however you could also use a character class like \\w.
There is an excellent tutorial on Java regexes here: https://docs.oracle.com/javase/tutorial/essential/regex/
You'll need a for-loop, you'll need to check each character of the phrase, String#charAt should help. If the character is not a space, you would append an ? to the template, otherwise you'll need to append a space...
See The for Statement for more details...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (int index = 0; index < sPhrase.length(); index++) {
if (sPhrase.charAt(index) != ' ') {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
Equally you could use...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (char c : sPhrase.toCharArray()) {
if (c != ' ')) {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
But I thought the first one would be easier to understand...
Just use a regex and String.replaceAll() method:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll(".", "?");
}
In this example, the first parameter is a regex, so "." matches all characters. The second parameter is the string to replace all regex matches with, a "?".
I have a question regarding making String arrays in Java. I want to create a String array that will store a specific word in each compartment of the string array. For example, if my program scanned What is your deal? I want the word What and your to be in the array so I can display it later.
How can I code this? Also, how do I display it with System.out.println();?
Okey so, here is my code so far:
import java.util.Scanner;
import java.util.StringTokenizer;
public class OddSentence {
public static void main(String[] args) {
String sentence, word, oddWord;
StringTokenizer st;
Scanner scan = new Scanner (System.in);
System.out.println("Enter sentence: ");
sentence = scan.nextLine();
sentence = sentence.substring(0, sentence.length()-1);
st = new StringTokenizer(sentence);
word = st.nextToken();
while(st.hasMoreTokens()) {
word = st.nextToken();
if(word.length() % 2 != 0)
}
System.out.println();
}
}
I wanted my program to count each word in a sentence. If the word has odd numbers of letter, it will be displayed.
Based on what you've given alone, I would say use #split()
String example = "What is your deal?"
String[] spl = example.split(" ");
/*
args[0] = What
args[1] = is
args[2] = your
args[3] = deal?
*/
To display the array as a whole, use Arrays.toString(Array);
System.out.println(Arrays.toString(spl));
To read and split use String.split()
final String input = "What is your deal?";
final String[] words = input.split(" ");
To print them to e.g. command line, use a loop:
for (String s : words) {
System.out.println(s);
}
or when working with Java 8 use a Stream:
Stream.of(words).forEach(System.out::println);
I agree with what the others have said, you should use String.split(), which separates all elements on the provided character and stores each element in the array.
String str = "This is a string";
String[] strArray = str.split(" "); //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
if((strArray[i].length() % 2) == 0) { //if there is an even number of characters in the string
System.out.println(strArray[i]); //print the string
}
}
Output:
This is string
If you want to print the string when it has an odd number of characters, simply change if((strArray[i].length() % 2) == 0) to if((strArray[i].length() % 2) != 0)
This will give you just a as the output (the only word in the string with an odd number of characters).
Let input be your input string. Then:
String[] words = input.split(" ");
I have to use methods to test a sentence for palindromes and I have got most of it done but it will only do the first word in the string and won't move on to the next one. I believe its something got to do with the spaces, if anyone could help that'd be great. Also I haven't studied arrays so I'd appreciate if arrays were not used.
class palindromeTesting
{
public static void main(String[] args)
{
String userInput;
String goodWords;
String palindromes;
System.out.println("Please enter a sentance to be tested for palindrome: ");
userInput = EasyIn.getString();
userInput += " " ;
goodWords = charsCheck(userInput); //Calling a method to check if any word contains more than letters.
palindromes = palinCheck(goodWords); //Checking the good words to see if they're palindromes.
System.out.println("The valid palindromes are " + palindromes);
} //Main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
public static String charsCheck(String userInput)
{
String validWords;
String firstWord;
Boolean goodWord;
int spacePos;
char letter;
spacePos = userInput.indexOf(" ");
validWords = "";
while(spacePos > 0)
{
firstWord = userInput.substring(0 , spacePos);
goodWord = true;
for(int index = 0 ; index < firstWord.length() && goodWord == true ; index++)
{
spacePos = userInput.indexOf(" ");
letter = Character.toUpperCase(firstWord.charAt(index));
if(letter < 'A' || letter > 'Z' )
{
goodWord = false;
}
} //for
if(goodWord == true)
{
firstWord = firstWord + " ";
validWords = validWords + firstWord;
}
userInput = userInput.substring(spacePos + 1);
spacePos = userInput.indexOf(" ");
} //While
return validWords;
} //charsCheck main
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
public static String palinCheck(String goodWords)
{
String firstWord;
String validPalins = "";
String backward = "";
int spacePos;
spacePos = goodWords.indexOf(" ");
while(spacePos > 0)
{
firstWord = goodWords.substring(0 , spacePos);
for(int i = firstWord.length()-1; i >= 0; i--)
{
backward = backward + firstWord.charAt(i);
}
if(firstWord.equals(backward))
{
validPalins = validPalins + firstWord;
}
goodWords = goodWords.substring(spacePos + 1) ;
spacePos = goodWords.indexOf(" ") ;
}//While
return validPalins;
} //palinCheck main
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
} //Class
If you believe the issue are spaces, you could always remove all spaces (and any other unwanted characters) with the replaceAll() method (check out the API). Say you have word1 and word2 you'd like to compare to see if they are palindromes, then do the following:
String word1 = "du mb";
String word2 = "b,mu d";
word1 = word1.replaceAll(" ", "");//replace it with empty string
word1 = word1.replaceAll(",", "");//even if the comma doesn't exist, this method will be fine.
word2 = word2.replaceAll(" ", "");
word2 = word2.replaceAll(",", "");
Once you've gotten ridden of unnecessary characters or spaces, then you should do the check. Also, you could always use Regex expressions for this kind of task, but that may be a bit difficult to learn for a beginner.
Also, I recommend using for loops (can probably be done in one for loop, but nested loops will do) instead of while loop for this task. Check out this example.
Sidenote:
Also I haven't studied arrays so I'd appreciate if arrays were not
used.
Strings are essentially char arrays.
The problem you described is actually not what is happening; your code does indeed move on to the next word. For my test, I used the test input Hi my name is blolb.
The problem is in your palinCheck method. You are using the backward variable to reverse the word and check whether it and firstWord, are equal. However, you aren't resetting the backward variable back to a blank string in the loop. As a result, you're constantly adding to whatever was in there before from the previous loop. At the end of the method, if I examine the content of backward using my test string above, it actually looks like iHymemansiblolb.
To solve this, simply declare String backward inside the while loop, like so:
while(spacePos > 0) {
String backward = "";
// rest of loop
Quick side note:
During the run of the palinCheck method, you're changing the goodWords parameter each iteration when you do this:
goodWords = goodWords.substring(spacePos + 1) ;
While this is technically acceptable (it has no effect outside of the method), I wouldn't consider it good practice to modify the method parameter like this. I would make a new String variable at the top of the method, perhaps call it something like currentGoodWords or something like that, and then change your line to:
currentGoodWords = goodWords.substring(spacePos + 1) ;
Also, I assume this is homework, so if you are allowed to use it, I would definitely take a look at the StringBuilder#reverse() method that Elliot Frisch mentioned (I admit, I never knew about this method before now, so major +1s to Elliot).
I had this code written as a personal project quite a while ago on palindrome using the shortest amount of code. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}
Here is SS of the whole question. http://prntscr.com/1dkn2e
it should work with any sentence not just the one given in the example
I know it has to do something with strings. Our professor has gone over with these string methods
http://prntscr.com/1dknco
This is only a basic java class so don't use any complicated stuff
here is what I have, don't know what to do after this
any help would be appreciated.
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
}
}
You can use public String[] split(String regex):
splitted = sentence.split("\\s+");
splitted[0] Is the first word.
splitted[splitted.length - 1] Is the last word.
Since your'e not allowed to use String#split, you can do this trick:
myString = myString.substring(0, myString.lastIndexOf(" ")) + firstWord;
By doing this, you'll have a substring which contains the sentence without the last word. (For extracting the first word, you can use String#indexOf.
firstWord is the first word you extracted before (I'll not solve the whole problem for you, try to do it by yourself, it should be easy now)
Well as it seem your looking for very simple string arithmetic.
So that's the simplest i could do:
// get the index of the start of the second word
int index = line.indexOf (' ');
// get the first char of the second word
char c = line.charAt(index+1);
/* this is a bit ugly, yet necessary in order to convert the
* first char to upper case */
String start = String.valueOf(c).toUpperCase();
// adding the rest of the sentence
start += line.substring (index+2);
// adding space to this string because we cut it
start += " ";
// getting the first word of the setence
String end = line.substring (0 , index);
// print the string
System.out.println(start + end);
try this
String str = "Java is the language";
String first = str.split(" ")[0];
str = str.replace(first, "").trim();
str = str + " " + first;
System.out.println(str);
Here is Another way you can do this.
UPDATED: Without Loops
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a line of text. No punctuaton please");
String sentence = keyboard.nextLine();
System.out.println(sentence);
int spacePosition = sentence.indexOf(" ");
String firstString = sentence.substring(0, spacePosition).trim();
String restOfSentence = sentence.substring(spacePosition, sentence.length()).trim();
String firstChar = restOfSentence.substring(0, 1);
firstChar = firstChar.toUpperCase();
restOfSentence = firstChar + restOfSentence.substring(1, restOfSentence.length());
System.out.println(restOfSentence + " " + firstString);
keyboard.close();
What is the best way to extract the integer part of a string like
Hello123
How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?
As explained before, try using Regular Expressions. This should help out:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
And then you just convert that to an int (or Integer) from there.
I believe you can do something like:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
EDIT: Added useDelimiter suggestion by Carlos
Why don't you just use a Regular Expression to match the part of the string that you want?
[0-9]
That's all you need, plus whatever surrounding chars it requires.
Look at http://www.regular-expressions.info/tutorial.html to understand how Regular expressions work.
Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).
Assuming you want a trailing digit, this would work:
import java.util.regex.*;
public class Example {
public static void main(String[] args) {
Pattern regex = Pattern.compile("\\D*(\\d*)");
String input = "Hello123";
Matcher matcher = regex.matcher(input);
if (matcher.matches() && matcher.groupCount() == 1) {
String digitStr = matcher.group(1);
Integer digit = Integer.parseInt(digitStr);
System.out.println(digit);
}
System.out.println("done.");
}
}
I had been thinking Michael's regex was the simplest solution possible, but on second thought just "\d+" works if you use Matcher.find() instead of Matcher.matches():
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String input = "Hello123";
int output = extractInt(input);
System.out.println("input [" + input + "], output [" + output + "]");
}
//
// Parses first group of consecutive digits found into an int.
//
public static int extractInt(String str) {
Matcher matcher = Pattern.compile("\\d+").matcher(str);
if (!matcher.find())
throw new NumberFormatException("For input string [" + str + "]");
return Integer.parseInt(matcher.group());
}
}
Although I know that it's a 6 year old question, but I am posting an answer for those who want to avoid learning regex right now(which you should btw). This approach also gives the number in between the digits(for eg. HP123KT567 will return 123567)
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.print("Enter alphaNumeric: ");
String x = scan.next();
String numStr = "";
int num;
for (int i = 0; i < x.length(); i++) {
char charCheck = x.charAt(i);
if(Character.isDigit(charCheck)) {
numStr += charCheck;
}
}
num = Integer.parseInt(numStr);
System.out.println("The extracted number is: " + num);
This worked for me perfectly.
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("string1234more567string890");
while(m.find()) {
System.out.println(m.group());
}
OutPut:
1234
567
890
String[] parts = s.split("\\D+"); //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}
We can simply use regular expression to extract the integer value from string
String str= "HEll1oTe45st23";
String intValue = str.replaceAll("[^0-9]", "");
System.out.print(Integer.parseInt(intValue));
Here, you can replaceAll string values with empty values and then parse the string to integer value. Further, you can use integer values.