Reading the number of non-blank characters within string - java

This is my simple code.
import java.util.Scanner;
public class WordLines
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
If I were to enter a sentence such as "Good Morning World!" (17 non-blank characters in this line)
How could I be able to display my text and on top of that print out the number of non-blank characters present.

Use a regex to delete all whitespace (spaces, newlines, tabs) and then simply take the string length.
input.replaceAll("\\s+", "").length()

Try this:
System.out.println(s);
System.out.println(s.replace(" ", "").length());

Do something like:
public static int countNotBlank(String s) {
int count = 0;
for(char c : s.toCharArray()) {
count += c == ' ' ? 0 : 1;
}
return count;
}

you can calculate non blank characters from a String as follow:
int non_blank_counter = 0;
//your code to read String
for(int i=0;i<s.length();i++){
// .. inside a loop ..//
if ( myStr.charAt( i ) != ' ' )
non_blank_counter++;
}
System.out.println("number of non blank characters are "+non_blank_counter);

Another way to deal with it
import java.util.Scanner;
public class WordLines {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String s;
System.out.println("Enter text from keyboard");
s = myScan.nextLine();
String[] splitter = s.split(" ");
int counter = 0;
for(String string : splitter) {
counter += string.length();
}
System.out.println("Here is what you entered: ");
System.out.println(counter);
}
}

import java.util.Scanner;
public class WordLines
{
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String s="";
System.out.println("Enter text from keyboard");
while(myScan.hasNextLine()) s = s+myScan.nextLine();
System.out.println("Here is what you entered: ");
System.out.println(s.replace(" ", "\n"));
}
}
u need to user CTRL+C at last when u want to exit from input.

Hope this will help you if you just want to know the number of non blank character.
String aString="Good Morning World!";
int count=0;
for(int i=0;i<aString.length();i++){
char c = aString.charAt(i);
if(c==' ') continue;
count++;
}
System.out.println("Total Length is:"+count);

Related

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");
}
}
}

Sentence Capitalizer with specific requirement

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);
}
}

Java string to array and replace a certain word from user to uppercase

Here is the full Question:
...
My Code
import java.util.Scanner;
import java.lang.StringBuilder;
public class javaAPIString {
public static void main(String[]args)
{
String SentenceFromUser = "";
String IndiWordFromUser = "";
/// String upper = IndiWordFromUser.toUpperCase();
//String[] words = SentenceFromUser.split("\\s+");
char ans;
Scanner keyboard = new Scanner(System.in);
do
{
final StringBuilder result = new StringBuilder(SentenceFromUser.length());
String[] words = SentenceFromUser.split("\\s");
System.out.println("Enter a sentence :");
SentenceFromUser = keyboard.nextLine();
System.out.println("Enter a word : ");
IndiWordFromUser = keyboard.next();
/// IndiWordFromUser = upper;
for(int i =0; i > words.length; i++ )
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
// System.out.println("The Output is : " + SentenceFromUser);
System.out.println("Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.");
ans = keyboard.next().charAt(0);
}
while ((ans == 'Y') || (ans == 'Y'));
}
}
My Output/ problem of my code :
Enter a sentence :
i like cookies
Enter a word :
cookies
The Output is : i like cookies
Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.
it returns the same original sentence without changing to Uppercase of the second input to replace to all CAPS.
I hope my solution will help you out! :)
import java.util.Scanner;
public class Solution {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
getTextFromUser();
}
private static void getTextFromUser() {
print("Enter Sentence Here: ");
String text = in.nextLine();
print("\nDo you want to capitalize words in sentence? Y/N: ");
while (in.nextLine().equalsIgnoreCase("y")) {
print("Enter Word: ");
print("Modified Text: " + changeWord(text, in.nextLine()));
print("\n\nDo you want to capitalize words in sentence? Y/N");
}
}
private static String changeWord(String text, String word) {
return text.replaceAll("\\b" + word + "\\b" /* \\b Means word
boundary */, word.toUpperCase()); // No validations done.
}
private static void print(String message) {
System.out.print(message);
}
}
Just some things:
please use java naming conventions for variables name
when you execute your code this instruction will overwrite the user input with an empty string.
IndiWordFromUser = upper;
String[] words = SentenceFromUser.split("\\s");... you are splitting an empty string the first time and the old sentence the other runs
The variable IndiWordFromUser is never read

By using while/for loop, how to subtract ONLY the uppercase of a line input by users?

Here is my code, i used is.upperCase to check but it doesn't seem to work. And i have trouble concatenating all the uppercases together. Any suggestion and help would be appreciated!
import java.util.Scanner;
public class UpperCase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
int i = 0;
while (i < str.length() - 1) {
if(Character.isUpperCase(i)) {
char upperLetter = str.charAt(i);
}
Object outputLetter = str.charAt(0) + str.charAt(i++);
char upperLetter = str.charAt(i++);
}
System.out.println("The uppercase letters are:" );
}
}
I guess below would solve your problem.
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.nextLine();
char[] cr = str.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
for(int i=0;i<cr.length;i++){
if(Character.isUpperCase(cr[i])){
stringBuffer.append(cr[i]);
}
}
System.out.println("The uppercase letters are:" + stringBuffer);
First, your idea is correct, but the way you did implement has some mistakes
1. isUperCase of i -> Wrong
2. outputLetter should be declare outside the loop to advoid re-init data
3. outputLetter should be something like outputLetter += anUpperCase
4. finally, refer this bellow code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please input a random line that contain uppercase letters in any positions: ");
String str = in.next();
in.close();
int i = 0;
String result = "";
while (i < str.length() - 1) {
char aChar = str.charAt(i);
if (Character.isUpperCase(aChar)) {
result += aChar;
}
i++;
}
System.out.println("The uppercase letters are: " + result);
}

Java counting program

I want to make a program to count characters, words and lines from an input text and stops when read a point(.)
This i what i have done so far...
import java.util.Scanner;
import java.io.*;
public class HelloWorld {
public static void main(String[] args) throws FileNotFoundException {
System.out.print ("Enter your text: ");
Scanner input=new Scanner(System.in);
String str=input.nextLine();
int ch=0;
int nlines=0;
int nwords=0;
while(!str.equals("."))
{
ch+=str.length();
nlines++;
String[] words = str.split(" ");
nwords = words.length;
str=input.next();
}
System.out.println("Number of words :"+nwords);
System.out.println("Number ofcharacters: "+ch);
System.out.println("Number of lines: "+nlines);
}
}
What is wrong with my program?
Let's go:
1- do you want to count a blankspace as a character? This line will count everything from your String:
ch+=str.length();
So a way to count only characters could be removing the blank spaces, like:
ch+=str.replace(" ", "").length();
2- The number of words, according to the line above, is not counting the words... it is just replacing the old value by the new value
nwords = words.length;
So, what you could do is add the values
nwords += words.length;
3- You are not counting the first line accordingly, if you do it in your way and the first String is like "My name is John.", your program will finish.
I did a very quick fix for you code, have a look on it:
public static void main(String[] args) {
System.out.print ("Enter your text: \n");
try(Scanner input=new Scanner(System.in)) {
String str=input.nextLine();
int ch=0;
int nlines=0;
int nwords=0;
boolean stopCount = false;
while(true)
{
if(str.contains(".")) {
String[] split = str.split(".");
if(split.length > 1) {
str = split[0];
break;
}
stopCount = true;
}
ch+=str.replace(" ", "").length();
nlines++;
String[] words = str.split(" ");
nwords += words.length;
if(stopCount) {
break;
}
str=input.nextLine();
}
System.out.println("Number of words :"+nwords);
System.out.println("Number ofcharacters: "+ch);
System.out.println("Number of lines: "+nlines);
}
}
You are using next() instead of nextLine(). Plus, you are not adding to nwords but overriding the previous value at each iteration. This code will work if you have a last consisting in a single ".".
String str = input.nextLine();
int ch=0;
int nlines=0;
int nwords=0;
while(!str.equals(".")) {
nlines++;
ch += str.length();
nwords += str.split("\\s+").length;
str = input.nextLine();
}
System.out.println("Number of words :"+nwords);
System.out.println("Number ofcharacters: "+ch);
System.out.println("Number of lines: "+nlines);
This should be your code:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
System.out.print("Enter your text: ");
Scanner input = new Scanner(System.in);
String str = input.nextLine();
int ch = 0;
int nlines = 0;
int nwords = 0;
while (!str.equals(".")) {
ch += str.length();
nlines++;
String[] words = str.split(" ");
nwords += words.length;
str = input.nextLine();
}
System.out.println("Number of words :" + nwords);
System.out.println("Number ofcharacters: " + ch);
System.out.println("Number of lines: " + nlines);
}
}
Sample input and output:
Enter your text: my name is 1
my name is 2
my name is 3
.
Number of words :12
Number ofcharacters: 36
Number of lines: 3
Try this solution;
int ch=0;
int nlines=0;
int nwords=0;
String str;
while(input.hasNextLine()) {
str = input.nextLine();
nlines++;
for (char c : str.toCharArray()) {
if(ch == ' ') // you need to check for tabs and new line
nwords++;
else if(ch == '.')
break;
else ch++;
}
}
System.out.println("Number of words :"+nwords);
System.out.println("Number ofcharacters: "+ch);
System.out.println("Number of lines: "+nlines);
int i = 0;
while(str.charAt(i) != '.')
{
ch++;
if(i == 0)
{
nlines++;
String[] words = str.split(" ");
nwords += words.length;
}
i++;
if(i >= str.length())
{
i = 0;
if(!input.hasNextLine())
{
break;
}
str = input.nextLine();
}
}
Something like this should help you. There are different ways of accomplishing this but this is one that is similar to what you were trying to do I think.

Categories