Java counting program - java

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.

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

swapping two letters in an unknown string in java

i am writing a program that must scramble a word. First I read in the word backwards using .reverse. Then I turned the string into a charArray.I am suppose to create a for loop to figure out if the First letter is "A" and if it is then i have to see if the next letter is not an "A". if its not then i am suppose to swap the two letters. If any of the two letters have a;ready been swapped than they cannot be swapped again.
Some examples are
Input: “TAN” Output: “ATN”
Input: “ALACTRIC” Output:“AALCTRIC”
Input: "Fork" Output:"Fork"
Here is my code so far: i cannot figure out what to put in the for loop. Thank you!
import java.util.Scanner;
public class scrambleWordRetry {
public static void main(String[] args)
{
}
public static String scramble( Random random, String inputString)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word to scramble.");
inputString = scan.nextLine();
char a[] = inputString.toCharArray();
for( int i=0 ; i<a.length-1 ; i++ )
{
}
return inputString;
}
}
I hope this code is useful for you
Scanner x = new Scanner(System.in);
String str = x.next();
System.out.println("Before Swapping" + str);
str = scramble(str);
System.out.println("After Swapping " + str);
}
public static String scramble(String inputString) {
char s[] = inputString.toCharArray();
for (int i = 1; i < s.length; i++) {
if (s[i] == 'A' || s[i] == 'a') {
char temp = s[i - 1];
s[i - 1] = s[i];
s[i] = temp;
}
}
return new String(s);
}
then if you input 'ALACTRIC' the output will be 'AALCTRIC',
'Tan = aTn',
'fork = fork'.

How to count each word in a string without .split()?

Given a String sentence entered by the user. Print each word on a separate line with the word #. For example, If the sentence "The cat in the hat" was entered, the following would be the output
word #1: The
word #2: cat
word #3: in
word #4: the
word #5: hat
Scanner input = new Scanner (System.in);
String sentence;
String words = "";
int count = 1;
sentence = input.nextLine();
for (int i = 1; i < sentence.length(); i++)
{
if (sentence.charAt(i) == ' ')
count++;
}
{
words = sentence.substring(0,sentence.indexOf(' '));
System.out.println(words);
}
String s = "The cat in the hat";
Scanner scan = new Scanner(s);
int wordNum = 1;
while(scan.hasNext()){
String temp = scan.next();
System.out.println("word#" + wordNum + ": \t" + temp);
wordNum++;
}
or
System.out.print("word#" + wordNum + ": \t" + temp + "\t");
if you want all on the same line
In your for loop, keep track of the starting index of each word (e.g. store it in a variable). Whenever you hit a new space, print out the word using substring with the number appended to it.
A few cases you may want to handle. If the sentence begins or ends with a bunch of spaces, you need to handle this without printing anything or incrementing your word count. You will need to do the same if there are multiple spaces between words.
The following code separates the word of given string
import java.util.Scanner;
import java.util.StringTokenizer;
public class StringTokenDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String sentence=sc.nextLine();
StringTokenizer tokenizer=new StringTokenizer(sentence," ");
int i=1;
while (tokenizer.hasMoreTokens())
{
String token=(String)tokenizer.nextToken();
System.out.println("#word"+i+" "+token);
i++;
}
}
}
This is not the right place to post homework, anyway the below code do what you want. If you want to print the words you need to store them, for example in a list or in an array.
List<String> words = new ArrayList<>();
String sentence = "The cat in the hat ";
int pos = 0;
int lastCharIndex = sentence.length() - 1 ;
for (int i = 0; i < sentence.length(); i++){
char cur = sentence.charAt(i);
//start to collect char for word only if
//the starting char is not a space
if(sentence.charAt(pos) == ' ' ){
pos+=1;
continue;
}
//continue the cycle if the current char is not a space
// and it isn't the last char
if(cur != ' ' && i != lastCharIndex){
continue;
}
//last word could not terminate with space
if(i == lastCharIndex && cur != ' '){
i+=1;
}
String word = sentence.substring(pos,i);
pos=i;
words.add(word);
}
System.out.println(words);
the code also take care if extra space between word or at the end of the sentence. Hope this can help.
did you try stringbuilder, or you can add all the elements in a arraylist and then count them. or count the chars.
Scanner input = new Scanner (System.in);
String sentence;
String words = "";
int count = 0;
for(char c : input.toCharArray()){
count++;
}
System.out.println("The word count is "+ count);

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

Reading the number of non-blank characters within string

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

Categories