I am making a palindrome tester, but I do not know how to get rid of punctuation. The program runs to show that words like "bob" and "yeetteey" are palindromes but does not recognize that m-a-m is a palindrome. How do I get it to work?
import java.util.Scanner;
//this is a palindrome tester
/**
* YUHHHHHHHH YUHHHHHHH
* #author its your boi, J. BACK at it again with another programming project
*
*/
public class PalindromeTester {
public static void main(String[] args) {
//YOUR CODE HERE
String word;
int z;
int y = 0;
int i = 0;
char letter;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a word: ");
word = sc.nextLine();
word = word.replaceAll("\\s+", "");
word = word.toLowerCase();
z = word.length()-1;
while (i <= z){
if ((letter = word.charAt(i)) == (letter = word.charAt(z-i))){
y += 1;
}
i += 1;
}
if (y == (z+1)){
System.out.println("The word IS a palindrome");
}
else{
System.out.println("The word is NOT a palindrome");
}
}
}
You already try to ignore punctuation characters with this line
word = word.replaceAll("\\s+", "");
where \s+ matches any whitespace. Instead, you probably want to match any character that's not a letter.
Luckily, this is just a quick RegEx change:
word = word.replaceAll("[^A-Za-z]+", "")
replaces anything in the negated set of all lower case and all upper case letters; e.g. everything that's not a letter.
If you want different behaviour, e.g. for you wish for some other characters to count as characters in a palindrome, you can just add them to the set e.g. [^A-Za-z0-9] lets numbers through, and if you wanted, [^A-Za-z\\-] would let dashes through.
Related
I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
So first of all, hello everyone this is my first time stackoverflow as a question asker and I know you folks don't like people asking homework questions on here but I've been struggling with this for about a week now and have given it several reasonable attempts so I actually need help here and am not just trying to mooch answers off you amazing coders :)
So my task at hand is I'm trying (the language is java btw) to find the number of times a letter (which the user inputs) occurs in a word (which the user also picks, and then to output the number of time that word occurs, for example: the word hello has two 'l's in it.. it should be pretty easy but for some reason I can't get it :/
I believe using my current code the variable "let" gets turned into an ascii character and idk what to do with that, or rather how I should compare it with all the other characters in the word.
Please help :)
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = "";
String letter;
int limit = 0;
String input = null;
String let;
int count = 0;
int j = 0;
while(limit == 0){
System.out.println("Type a word.");
word = scan.nextLine();
System.out.println("Type a single letter.");
letter = scan.nextLine();
let = letter.substring(0,1);
char car;
while(j<word.length()){
car = word.charAt(j);
for(int x=1; x==j; x++){
if(let.charAt(0)==car){
count ++;
}
}
j+=1;
}
System.out.println(count + " " + "occurances.");
}
}
}
Here is a sample code that should work
import java.util.Scanner;
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type a word.");
String word = scan.nextLine();
System.out.println("Type a single letter.");
String letter = scan.nextLine();
char let = letter.charAt(0);
int count = 0;
for (char char1: word.toCharArray()) {
if (char1 == let) {
count++;
}
}
System.out.println(count + " " + "occurrences.");
}
}
Here is the test output
Type a word.
letter
Type a single letter.
t
2 occurrences.
import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you
So I've been making a small piece of code in Java that takes input from the user counts the uppercase, lowercase and other parts (such as spaces, numbers, even brackets) and then returns how much there are of each to the user.
The problem I have is that say I put in "Hello There" it stops counting spots after the "o" in Hello. So after the first word.
Code
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int upper = 0;
int lower = 0;
int other = -1;
int total = 0;
String input;
System.out.println("Enter the phrase: ");
input = scan.next();
for (int i = 0; i < input.length(); i++) {
if (Character.isUpperCase(input.charAt(i))) upper++;
if (Character.isLowerCase(input.charAt(i))) lower++;
else other++;
total = upper + lower + other;
}
System.out.println("The total number of letters is " + total);
System.out.println("The number of upper case letters is " + upper);
System.out.println("The number of lower case letters is " + lower);
System.out.println("The number of other letters is " + other);
}
}
Scanner#next:
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern.
The problem is that next doesn't see the word "There" since "Hello World" is not a complete token.
Change next to nextLine.
Advice: Use the debugger and you'll find the problem quickly, and when you have doubts refer to the docs, they're there for you.
Problem is that next() only returns the line before a space but nextLine() will read the whole line.
So Change
scan.next();
to
scan.nextLine();
You need to change next() to nextLine()- it will read all the line
As others have said. You should change from scn.next to scn.nextLine(). But why? This is because scn.next() only read until it encounters a space, and it stops reading. So whatever input after a space will not be read.
scn.nextLine() reads until a newline (i.e. enter) is encountered.
You can try with regular expressions:
public static void main(String[] args) {
String input = "Hello There";
int lowerCase = countMatches(Pattern.compile("[a-z]+"), input);
int upperCase = countMatches(Pattern.compile("[A-Z]+"), input);
int other = input.length() - lowerCase - upperCase;
System.out.printf("lowerCase:%s, upperCase:%s, other:%s%n", lowerCase, upperCase, other);
}
private static int countMatches(Pattern pattern, String input) {
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
I'm trying to write a program where a user would enter a phrase, and the program would count the blank spaces and tell the user how many are there. Using a for loop but i'm stuck, could someone help me out?
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for(ch=phrase.charAt()
// and count the blank spaces
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
The for loop for counting spaces would be written as follows:
for(int i=0; i<phrase.length(); i++) {
if(Character.isWhitespace(phrase.charAt(i))) {
countBlank++;
}
}
It reads as follows: “i is an index, ranging from the index of the first character to the index of the last one. For each character (gotten with phrase.charAt(i)), if it is whitespace (we use the Character.isWhitespace utility function here), then increment the countBlank variable.”
Just wondering, couldn't you just split the string entered by blank spaces and take the length of the array subtracted by 1?
In C# it would be as trivial as
string x = "Hello Bob Man";
int spaces = x.Split(' ').Length - 1;
Pretty sure java has a split? Works even if you have two contiguous spaces.
You have probably problem with that for each loop
char[] chars = phrase.toCharArray(); Change string into array of chars.
for(char c : phrase.toCharArray()) { //For each char in array
if(Character.isWhitespace(c) { //Check is white space.
countBlank++; //Increment counter by one.
}
}
or
for(int i =0; i <phrase.lenght(); i++) {
if(Character.isWhitespace(phrase.charAt(i)) { //Check is the character on position i in phrase is a white space.
countBlank++; //Increment counter by one.
}
}
You have to complete for cycle and count spaces
//replace this lines
for(ch=phrase.charAt()
// and count the blank spaces
//to this lines
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
}
Loop through the characters in the string.
Check if the character is a space (char value = 32 or ch == ' ')
If space, add to countBlank, otherwise continue
Display the results.
You might look at the String and Character classes in the Java documentation for assistance.
I'm not very familiar with java, but if you can access each character in the string.
You could write something like this.
int nChars = phrase.length();
for (int i = 0; i < nChars; i++) {
if (phrase.charAt(i) == ' ') {
countBlank++;
}
}
This is at the following Java Tutorials
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
String[] items = p.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
OUTPUT:
one
two
three
four
five
The regex for whitespace is \s
Hope that helps.