This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?
public class Capitalize
{
public static void capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println(scanner.next());
}
}
Problems as I see them:
The code as it stands will only print the first word typed in once the user presses enter
The method doesn't return anything, so effectively it does all that work and discards it.
So here is what I might do:
I'm going to put everything in main for the sake of concision
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String sentence = Scanner.nextLine();
StringBuilder ans = new StringBuilder(); // result
for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
if(str.Length>0) // can happen if there are two spaces in a row I believe
str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
ans.Append(str); // add modified word to the result buffer
ans.Append(' '); // add a space
}
System.out.println(ans);
}
}
You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight
I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.
`public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext())
System.out.println(scanner.next());
}`
I would probably do this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { // While there is input.
String line = scanner.nextLine(); // read a line.
int i = 0;
for (String s : line.split(" ")) { // split on space... word(s).
if (i != 0) {
System.out.print(" "); // add a space, except for the first word on a line.
}
System.out.print(capCase(s)); // capCase the word.
i++; // increment our word count.
}
System.out.println(); // add a line.
System.out.flush(); // flush!
}
}
public static String capCase(String theString) {
if (theString == null) {
return ""; // Better safe.
}
StringBuilder sb = new StringBuilder(theString
.trim().toLowerCase()); // lowercase the string.
if (sb.length() > 0) {
char c = sb.charAt(0);
sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
}
return sb.toString(); // return the word.
}
Problem :
1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.
Solution
1.use the below statement to read complete Line
String str=scanner.nextLine();
2.Change return type of capCase() from void to char[] as below:
public static char[] capCase(String theString)
you should return the char[] variable chars from capCase() function as below:
return chars;
Complete Code:
public static char[] capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
return chars;
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
System.out.println(capCase(str));
}
Try,
public static void main(String[] args) {
System.out.println(capCase("hello world"));
}
public static String capCase(String theString) {
StringBuilder res = new StringBuilder();
String[] words=theString.split(" +");
for (String word : words) {
char ch=Character.toUpperCase(word.charAt(0));
word=ch+word.substring(1);
res.append(word).append(" ");
}
return res.toString();
}
Try this code it worked for me:
import java.util.Scanner;
public class Capitalize {
/**
* This code should allow the user to input a sentence, change it to lower
* case, and then capitalize the first letter of each word. But I can't get
* the scanner to work, it just prints nothing. Any suggestions?
*
* #param theString
*/
public static void capCase(String theString) {
String source = theString.trim();
StringBuffer res = new StringBuffer();
String lower = theString.toLowerCase();
String[] split = lower.split(" ");
for (int i = 0; i < split.length; i++) {
String temp = split[i].trim();
if (temp.matches("^[a-zA-Z]+")) {
split[i] = temp.substring(0, 1).toUpperCase()
+ temp.substring(1);
}
res.append(split[i] + " ");
}
System.out.println(res.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
capCase(scanner.nextLine());
// System.out.println(scanner.next());
}
}
I've tested it. It works.
import java.util.Scanner;
import org.apache.commons.lang3.text.WordUtils;
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
System.out.println(WordUtils.capitalize(s.nextLine()));
}
}
}
Related
newbie here. Any help with this problem would be appreciated:
You are given a String variable called data that contain letters and spaces only. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by +. An example is shown below: I Like Java becomes I+L???+J???.
What I have so far:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.
You can do it in two steps by chaining String#replaceAll. In the first step, replace the regex, [a-z], with ?. The regex, [a-z] means a character from a to z.
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+L???+J???
Alternatively, you can use a StringBuilder to build the desired string. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases. The logic of building the desired string is simple:
Loop through all characters of the string and check if the character is a lowercase letter. If yes, append ? to the StringBuilder instance else if the character is whitespace, append + to the StringBuilder instance else append the character to the StringBuilder instance as it is.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+L???+J???
If the requirement states:
The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
Second character onwards can be any word character which needs to be replaced with ?.
All whitespace characters of the string need to be replaced with +.
you can do it as follows:
Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\p{L})\w, with ?. The regex, (?<=\p{L})\w means:
\w specifies a word character.
(?<=\p{L}) specifies a positive lookbeghind for a letter i.e. \p{L}.
In the second step, simply replace one or more whitespace characters i.e. \s+ with +.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+l???+J???
Alternatively, again like the earlier solution you can use a StringBuilder to build the desired string. Loop through all characters of the string and check if the character is a letter. If yes, append it to the StringBuilder instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered. If a whitespace character is encountered, append + to the StringBuilder instance else append ? to it.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:
i Love YouU
?+L???+Y??U
Firstly, you are trying to make changes to String object which is immutable. Simple way to achieve what you want is convert string to character array and loop over array items:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code. To include multiple regex put the char within square brackets:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can use String.codePoints method to get a stream over int values of characters of this string, and process them:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string
package school;
import java.util.*;
public class PalindromeWords {
boolean palindrome(String S) {
String check="";
for(int i = S.length()-1;i>=0;i--) {
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)) {
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++) {
if(S.charAt(i)==' ') {
word = S.substring(flag,i);
if(ob.palindrome(word)) {
System.out.println(word);
flag =i+1;
}
}
}
}
}
I have been given an assignment in which I have to Write a Java Program to Print all the Palindrome words in a sentence. This is the code I wrote and I am not getting the correct output.
As you can see the output in the console gives no query in result.
You should move the step which increase flag outside if statement. Otherwise, it only works if the first word is palindrome.
if(ob.palindrome(word)) {
System.out.println(word);
}
flag = i+1;
Use the flag outside the loop.
if(ob.palindrome(word)==true) {
System.out.println(word);
}
flag =i+1;
This code should work.
Here is another solution as follows:
code:
import java.util.*;
public class PalindromeWords
{
boolean isPalindrome(String S)
{
boolean result = false;
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S))
{
result = true;
}
return result;
}
public static void main(String args[])
{
PalindromeWords ob = new PalindromeWords();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String str = sc.nextLine();
String[] words = str.split(" ");
for(int i=0; i < words.length; i++)
{
if(ob.isPalindrome(words[i]))
{
System.out.println(words[i]);
}
}
}
}
output:
Enter the sentence.
hello mAdam
mAdam
boolean palindrome(String S){
String check="";
for(int i = S.length()-1;i>=0;i--)
{
check = check+S.charAt(i);
}
if(check.equalsIgnoreCase(S)==true)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
Para ob = new Para();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence.");
String S=sc.nextLine();
S = S + ' ';
int flag = 0,i=0;
String word;
for(i=0;i<S.length();i++)
{
if(S.charAt(i)==' ')
{
word = S.substring(flag,i);
if(ob.palindrome(word)==true)
{
System.out.println(word);
}flag =i+1;
}
}
}
I am unable to terminate my java program which takes some strings as input, below is the code I used to process the input
import java.util.Scanner;
public class EPALIN {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while((p=sc.nextLine())!=null)
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i =0;
int j = st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
Even using
while((p=sc.nextLine())!="")
didn't work, its a problem from SPOJ problemId EPALIN
Do something like this
while(!(p=sc.nextLine()).equals("")) {
// ...
}
I try your code with the while i'm using and it's seems to work.
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while(!(p=sc.nextLine()).equals(""))
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i=0;
int j=st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
You should use hasNext()
String delimiter = "\r\n|\r"; //Or try System.getProperty("line.separator");
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(delimiter);
while (scanner.hasNext()) {
String p = scanner.next();
// ...
}
}
See the Scanner documentation. Scanner.nextLine() won't return null. If the input ends (for instance, the judge has piped a file to stdin, and the file ends), it will instead throw NoSuchElementException. If it doesn't, nextLine() will block.
Ordinarily what you could do here, because the the problem description states that each test case will be on its own line is (similar to what CandiedOrange suggested):
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
However, the problem also states:
Large I/O. Be careful in certain languages.
In contest problem lingo, this means "don't use Scanner." For fast I/O, you have a couple of options, but something like the following should work fine while keeping you under the time limit:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String line;
while ((line = in.readLine()) != null)
doSomething(line); // etc
}
Note that you will most likely also have to collect all of your output and print it at the end, rather than making a bunch of System.out.println(), which have overhead that you can avoid by only printing once.
Main Class (required)
import java.util.*;
public class FindingPalindrome {
private String inputString;
private Stack<Character> stack = new Stack<Character>();
public FindingPalindrome(String str)
{
inputString = str;
fillStack();
}
public void fillStack()
{
for(int i = 0; i < inputString.length(); i++)
{
stack.push(inputString.charAt(i));
}
}
public String reverseString()
{
String result = new String();
while(!stack.isEmpty())
{
result = result.concat(Character.toString(stack.pop()));
}
return result;
}
public boolean isPalindrome()
{
if(inputString.equalsIgnoreCase(reverseString()))
return true;
else return false;
}
}
Tester Class (required)
import java.util.*;
public class TestPalindrome
{
private static Scanner s;
public static void main(String args[])
{
s = new Scanner(System.in);
System.out.println("Enter the string");
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]","");
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
}
}
Whenever I add "Stop! pots" the code terminates itself and doesn't print the output. I also added the replaceAll(), but it didn't work either. Simple palindrome works "ada", "Kayak", but palindrome with spaces and characters is not working
You are doing it in the wrong order:
// Read the data
String st1=s.nextLine();
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1);
// Reverse the letters
sb.reverse();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<<<<< too late.
// You created sb with the original
// including punctuation
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
Replace with
// Read the data
String st1=s.nextLine();
st1 = st1.toLowerCase().replaceAll("[^a-z]",""); // <<<< moved this
// Create StringBuffer obj for st1
StringBuffer sb=new StringBuffer(st1); // <<<< now this is a copy without punctuation
// Reverse the letters
sb.reverse();
// Check & Print if palindrome
if(st1.equals(sb.toString()))
System.out.println("Palindrome String");
Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
// Will recognize a space in words
if(Character.isWhitespace(welcome.charAt(i))) {
Character a = welcome.charAt(i);
}
}
What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string.
Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
Here is the way you can reversed the word in entered string:
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if(!s.trim().contains(' ')) {
return s;
}
else {
StringBuilder reversedString = new StringBuilder();
String[] sa = s.trim().split(' ');
for(int i = sa.length() - 1; i >= 0: i - 1 ) {
reversedString.append(sa[i]);
reversedString.append(' ');
}
return reversedString.toString().trim();
}
Hope this helps.
If you wanted to reduce the number of line of code, I think you can look into my code :
package com.sujit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StatementReverse {
public static void main(String[] args) throws IOException {
String str;
String arr[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string:");
str = br.readLine();
arr = str.split("\\s+");
for (int i = arr.length - 1;; i--) {
if (i >= 0) {
System.out.print(arr[i] + " ");
} else {
break;
}
}
}
}
public class StringReverse {
public static void main(String[] args) {
String str="This is anil thakur";
String[] arr=str.split(" ");
StringBuilder builder=new StringBuilder("");
for(int i=arr.length-1; i>=0;i--){
builder.append(arr[i]+" ");
}
System.out.println(builder.toString());
}
}
Output: thakur anil is This
public class ReverseWordTest {
public static String charRev(String str) {
String revString = "";
String[] wordSplit = str.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
String revWord = "";
String s2 = wordSplit[i];
for (int j = s2.length() - 1; j >= 0; j--) {
revWord = revWord + s2.charAt(j);
}
revString = revString + revWord + " ";
}
return revString;
}
public static void main(String[] args) {
System.out.println("Enter Your String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(charRev(str));
}
public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
if(count==0||count==x.length) //that's for two edges.
one=s+one;
else
one=s+" "+one;
count++;
}
System.out.println(one); //reverse.
}