Sentence Capitalizer with specific requirement - java

It's hard to explain but I'm trying to create a program that only capitalizes the letter of every word that ends with a period, question mark, or exclamation point. I have managed to receive a result when inputting any of the marks but only when it is entered the second time. In other words I have to hit enter twice to get a result and I'm not sure why. I am still working on it on my own but I'm stuck at this problem.
import java.util.*;
public class SentenceCapitalizer
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
String wrong = keyboard.nextLine();
String[] check = {".!?"};
String upper_case_line="";
Scanner lineScan = new Scanner(line);
for (String sent : check)
{
if (sent.startsWith(wrong))
{
System.out.println("cant use .?!");
}
else
{
/* if (line.startsWith(" "))//if starts with space
System.out.println("good");
else
System.out.println("bad");
*/
//if (int i = 0; i < line.length; i++)
//{char c = line.chartAt(i);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) +
word.substring(1) + " ";
}
System.out.println(upper_case_line.trim());
}
}
}
}

Solution
Hey just a quick solution for your question. Converts the string to character array and then checks the character array for '.!?' if it finds the value then it will make the next letter a capital!
public class SentenceCapitalizer {
public static void main(String[] args) {
//Scanner, Variable to hold ouput
Scanner keyboard = new Scanner(System.in);
System.out.print("Input a sentence: ");
String line = keyboard.nextLine();
//Char array, boolean to check for capital
char [] lineChars = line.toCharArray();
boolean needCapital = false;
//String to hold output
String output = "";
//Check for period in line
for (int i = 0; i < lineChars.length; i++) {
//Make sure first char is upper case
if (i == 0) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
}
//Check for uppercase if char is not space
if (needCapital && Character.isLetter(lineChars[i])) {
lineChars[i] = Character.toUpperCase(lineChars[i]);
needCapital = false;
}
if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
needCapital = true;
}
//Add character to string
output += lineChars[i];
}
//Output string
System.out.println (output);
}
}

Related

Palindrome Checker with nested loops thats checks the input and then flips its to compare

Im stuck on this, I need a code that use 2 nested loops for this assignment (there are other solutions, but I need to demonstrate my understanding of nested loops). But I just dont get it. The outer loop repeats the entire algorithm and the inner loop iterates half-way (or less) through the string. I am not sure on what I need to put inside the for loops. This is what I have so far. Any Assistance would be pleasured.
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String x = 0;
String y = input.length-1;
for (String i = 0; i < line.length-1; i ++){
for (String j = 0; j < line.length-1; j ++){
if (input.charAt(x) == input.charAt(y))
{
x++;
y--;
}
}
}
}
Example Output:
Enter a string: 1331
1331 is a palindrome.
Enter a string: racecar
racecar is a palindrome.
Enter a string: blue
blue is NOT a palindrome.
Enter a string:
Empty line read - Goodbye!
Your algorithm is flawed, your nested loop should be to prompt for input - not to check if the input is a palindrome (that requires one loop itself). Also, x and y appear to be used as int(s) - but you've declared them as String (and you don't actually need them). First, a palindrome check should compare characters offset from the index at the beginning and end of an input up to half way (since the offsets then cross). Next, an infinite loop is easy to read, and easy to terminate given empty input. Something like,
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string: ");
System.out.flush();
String line = input.nextLine();
if (line.isEmpty()) {
break;
}
boolean isPalindrome = true;
for (int i = 0; i * 2 < line.length(); i++) {
if (line.charAt(i) != line.charAt(line.length() - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.printf("%s is a palindrome.%n", line);
} else {
System.out.printf("%s is NOT a palindrome.%n", line);
}
}
System.out.println("Empty line read - Goodbye!");
import java.util.Scanner;
public class pali
{
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
String reversedText ="";
for(int i=line.length()-1/* takes index into account */;i>=0;i++) {
reversedText+=line.split("")[i]; //adds the character to reversedText
}
if(reversedText ==line){
//is a palidrome
}
}
Your code had lot of errors. I have corrected them and used a while loop to check if its a palindrome or not. Please refer below code,
import java.util.Scanner;
public class Post {
public static void main(String[] args) {
String line;
boolean isPalindrome = true;
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a String to check if it's a Palindrome");
line = input.nextLine();
int x = 0;
int y = line.length() - 1;
while (y > x) {
if (line.charAt(x++) != line.charAt(y--)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(line + " is a palindrome");
} else {
System.out.println(line + "is NOT a palindrome");
}
System.out.println();
}
}
}

Java - moving first letter of string to the end, and determining if word is the same when spelled backwards

I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.
e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.
Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.
Thank you in advance for any help.
Jack
This is what I've got so far, but I don't think it works properly.
public class WordPlay {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word;
String palindrome = "";
String quit = "quit";
do {
System.out.print("Enter a word: ");
word = scanner.nextLine().toUpperCase();
int length = word.length();
for (int i = length - 1; i >= 0; i--) {
palindrome = palindrome + word.charAt(i);
}
if (word.equals(palindrome)) {
System.out.println("Is the word + palindrome + " same as " + word + "?", true);
} else {
System.out.println(false);
}
} while (!word.equals(quit));
System.out.println("Good Bye");
scanner.close();
}
}
Here it is.
public static void main(String[] args) {
// To take input.
Scanner scan = new Scanner(System.in);
System.out.print("Enter Word: ");
String word = scan.next(); // taking the word from user
// moving first letter to the end.
String newWord = word.substring(1) + word.charAt(0);
// reversing the newWord.
String reversed = new StringBuffer(newWord).reverse().toString();
// printing output.
System.out.println("You have entered '"+word+"'. "
+ "Is "+newWord+" same as "+word+"? "
+reversed.equals(word)+".");
// closing the input stream.
scan.close();
}
This works:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner scan = new Scanner(System.in);
String s1 = scan.next();
char s2 = s1.charAt(0);
String s3 = s1.substring(1) + s2;
s3 = new StringBuilder(s3).reverse().toString();
if(s1.equals(s3))
System.out.println("They are same");
else
System.out.println("They are not the same");
}
}
This is very simple with some of observation. Your question is you have to move the first latter to the end and check reverse if the new string is same or not.
My ovservation:
For BANANA new string is ANANAB. Now reverse the string and check weather it is same as the first one.
Now If you ignore the first char B the string will be ANANA. As you have to reverse the string and check this one is same as the first one so this is like palindrome problem. For the input BANANA ANANA is palindrome. We are moving the first char to the end so there is no impact of it on checking palindrome. So I ignore the first char and check the rest is palindrome or not.
The Method is like:
private static boolean getAns(String word) {
int st = 1;
int en = word.length() - 1;
while (st < en) {
if (word.charAt(en) != word.charAt(st)) {
return false;
}
st++;
en--;
}
return true;
}
The main function is:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input your String:");
String word = scanner.nextLine();
boolean ans = getAns(word);
System.out.println("You have entered " + word + ". Is " + word.substring(1) + word.charAt(0) + " same as " + word + "? : " + ans + ".");
}
The Runtime for this problem is n/2 means O(n) and no extra memory and space needed,
I have tried to code it. See if it helps
import java.util.Scanner;
class StringCheck
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
String tempstr = new String();
System.out.println("Enter your String ");
str = sc.next();
int len = str.length();
//putting first character of str at last of tempstr
for (int i = 1 ; i<len; i++)
{
tempstr += str.charAt(i);
}
tempstr += str.charAt(0);
//reversing tempstr
char[] tempchar = tempstr.toCharArray();
int j = len-1;
char temp;
for ( int i = 0; i<len/2 ; i++)
{
if(i<j)
{
temp = tempchar[i];
tempchar[i] = tempchar[j];
tempchar[j]= temp;
j--;
}
else
break;
}
//reversing completed
tempstr = new String(tempchar);
// System.out.println("the reversed string is "+tempstr);
if(str.compareTo(tempstr)==0)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
}
}

How do you check if a string is a palindrome in java?

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.
Here is my code:
...
Scanner console = new Scanner (System.in);
String str = console.next();
Printpalindrome(console, str);
}
public static void Printpalindrome(Scanner console, String str) {
Scanner in = new Scanner(System.in);
String original, reverse = "";
str = in.nextLine();
int length = str.length();
for ( int i = length - 1; i >= 0; i-- ) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse))
System.out.println("Entered string is a palindrome.");
}
}
Because of this line:
n = in.nextLine();
your program is waiting for a second input, but you already got one before entering the function.
Remove this line and it works.
Here's your program, cleaned (and tested) :
public static void main(String[] args){
Scanner console = new Scanner (System.in);
String n = console.next();
Printpalindrome(n);
}
public static void Printpalindrome(String n){
String reverse = "";
for ( int i = n.length() - 1; i >= 0; i-- ) {
reverse = reverse + n.charAt(i);
System.out.println("re:"+reverse);
}
if (n.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is NOT a palindrome.");
}
Of course, this isn't the best algorithm, but you already know there are many QA on SO with faster solutions (hint: don't build a string, just compare chars).
Remove
Scanner in = new Scanner(System.in);
and
n = in.nextLine();
from Printpalindrome function
and it should work.
This can be implemented in a far more efficient manner:
boolean isPalindrom(String s){
if (s == null /* || s.length == 0 ?*/) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
The argument for PrintPalindrom is ignored. You read another value with `in.nextLine()'. Which is the reason for your issues.
Ur code with some correction:-
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
I tried your code and what i observed was that :
first of all you are making a string to enter on the line 2 of your code:
String n=console.next();
next the the program again goes to waiting when this line gets executed:
n = in.nextLine();
actually this particular line is also expecting an input so that is why the program halt at this point of time.
If you enter your String to be checked for palindrome at this point of time you would get the desired result .
But I would rather prefer you to delete the line
n = in.nextLine();
because, with this, you would have to enter two words which are ambiguous.

Trying to Convert a string to another string from array in a file on only the first space

Disclaimer, I've been at java for about a month. I'm completely lost on this. I'm trying to have a user input a phrase and if any strings in that phrase is found on the array, it returns the corresponding string in one line. if the string isn't found, it would just skip it.
so if someone typed in "dog eat my fish"
and the array holds:
dog perro
eat munched
fish yellow trout
it would return:
perro munched yellow trout
I haven't written the code to print out what I've got yet, but I know this code isn't working.
any help would be greatly appreciated.
import java.io.*;
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args)
throws java.io.IOException {
Scanner input = new Scanner(System.in);
String userString = " ";
userString = englishString();
String[][] wordList = new String[10][2];
loadEnglishString(wordList);
}
public static String englishString() {
Scanner input = new Scanner(System.in);
String s1 = " ";
System.out.println("Please enter a phrase to translate: ");
s1 = input.nextLine().trim().toUpperCase();
return s1;
}
public static void loadEnglishString(String[][] wordList)
throws java.io.IOException {
String filName = " ";
filName = ("/home/chrism/ArrayTest2.txt");
Scanner input = new Scanner(new File(filName));
while(input.hasNextLine()) {
String line = input.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
boolean stop = false;
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++)
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
break;
}
}
}
input.close();
}
}
You'll definitely want to change your for loop. Brackets are your friend.
for(int i = 0; i < wordList.length; i++) {
if(stop)
break;
for(int j = 0; j < wordList[i].length; j++) {
if(input.hasNextLine())
wordList[i][j] = input.nextLine();
else {
stop = true;
}
}
}
The way you had it, both increments were registering as dead code because your second break would always called the first time through the loop, and your else was registering as coupled with the first if(stop).
Edit: don't know for sure about how the else would couple, but the break is definitely called after the first run through.
//package com.myjava.stokenizerr;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String a[]){
/* your code for user input string */
/* assume input as dog eat my fish */
String input = "dog eat my fish";
String msg = "dog perro eat munched fish yellow trout";
StringTokenizer st1 = new StringTokenizer(msg," ");
StringTokenizer st2 = new StringTokenizer(input," ");
while(st1.hasMoreTokens()){
System.out.println(st1.nextToken()); // Store this one(first) string array
}
while(st2.hasMoreTokens()) {
System.out.println(st2.nextToken()); // Store in another(second) array
}
/* Now Compare both the arrays */
/* If the strings are equal then remove string from second array */\
/* If equal just skip it */
}
}
See the above code st1.nextToken() and st2.Tokens() will give you the values
For comparing take two loops
for(i==0;i<array1length();i++) {
for(j==0;j<array2length();j++) {
// Your code for comparsion
}
}

Java program on name Initials

I am writing a program that will give the Initials of the name(String) user gives as input.
I want to use the Space function while writing the name as the basis of the algorithm.
For eg:
<Firstname><space><Lastname>
taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before.
Can someone tell me how to implement this?
I'm trying this but getting one error.
Any help is dearly appreaciated..
P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding
public class Initials {
public static void main(String[] args) {
String name = new String();
System.out.println("Enter your name: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("You entered : " + name);
String temp = new String(name.toUpperCase());
System.out.println(temp);
char c = name.charAt(0);
System.out.println(c);
for (int i = 1; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '') {
System.out.println(name.charAt(i - 1));
}
}
}
}
EDIT:
Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..
for (int i = 1; i < temp.length(); i++) {
char c1 = temp.charAt(i);
if (c1 == ' ') {
System.out.print(temp.charAt(i + 1));
System.out.print(".");
}
}
Thanks a lot guys :)
This works for me
public static void main(String[] args) {
Pattern p = Pattern.compile("((^| )[A-Za-z])");
Matcher m = p.matcher("Some Persons Name");
String initials = "";
while (m.find()) {
initials += m.group().trim();
}
System.out.println(initials.toUpperCase());
}
Output:
run:
SPN
BUILD SUCCESSFUL (total time: 0 seconds)
Simply use a regex:
keep only characters that are following a whitespace
remove all remaining whitespace and finally
make it upper case:
" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();
=> FBM
I will do something like this:
Remember, you only need the inicial characters
public staticvoid main (String[] args){
String name;
System.out.println("Enter your complete name");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("Your name is: "+name);
name=" "+name;
//spacebar before string starts to check the initials
String ini;
// we use ini to return the output
for (int i=0; i<name.length(); i++){
// sorry about the 3x&&, dont remember the use of trim, but you
// can check " your name complete" if " y"==true y is what you want
if (name.charAt(i)==" " && i+1 < name.length() && name.charAt(i+1)!=" "){
//if i+1==name.length() you will have an indexboundofexception
//add the initials
ini+=name.charAt(i+1);
}
}
//after getting "ync" => return "YNC"
return ini.toUpperCase();
}
If you care about performance (will run this method many times), the extra charAt(i+1) isn't needed and is relatively costly.
Also, it'll break on texts with double spaces, and will crash on names that end with a space.
This is a safer and faster version:
public String getInitials(String name) {
StringBuilder initials = new StringBuilder();
boolean addNext = true;
if (name != null) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == ' ' || c == '-' || c == '.') {
addNext = true;
} else if (addNext) {
initials.append(c);
addNext = false;
}
}
}
return initials.toString();
}
public String getInitials() {
String initials="";
String[] parts = getFullName().split(" ");
char initial;
for (int i=0; i<parts.length; i++){
initial=parts[i].charAt(0);
initials+=initial;
}
return(initials.toUpperCase());
}

Categories