how many letter occur in a text? - java

I got it working but it is also counting the spaces between the words that are being typed.
All i care is for the letters to be count and not the spaces.
How or what can i do to change this? where am i messing up or missed something
import java.util.Scanner;
public class LetterCount
{
public static void main (String[] args)
{
System.out.println("Type something ");
Scanner n = new Scanner (System.in);
String s = "";
s = n.nextLine();
char []c = s.toCharArray();
int sz = c.length;
int i =0, j=0, counter=0;
for (i=0; i<sz; i++){
counter =0;
for(j=0; j<sz; j++)
{
if (j< i&& c[i] == c[j])
{
break;
}
if (c[j] == c[i])
{
counter++;
}
if (j==sz-1)
{
System.out.println("the character "+c[i]+" is present "+counter+" times");
}
}
}
}
}

What you'd want to do is remove the whitespace from the string before you count the letters;
Removing whitespace from strings in Java

Related

How can i make my Programm accept Palindrom with capital letter or space between? [duplicate]

This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 1 year ago.
import java.util.Scanner;
public class palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.next();
String org_word = word;
word = word.replace(" ","");
String reverse = "";
for (int i = word.length()-1; i >=0; i--) {
reverse += word.charAt(i);
}
boolean palindrome = true;
for (int i= 0; i < word.length(); i++){
if(word.charAt(i) != reverse.charAt(i)){
palindrome = false;
}
}
if (palindrome) {
System.out.println("Your word is a palindrome!");
}
else System.out.println("Your word is not a palindrome!");
}
}
If I put a Palindrome in my Program like "racecar" it does it correctly, but if I type "race car" with a space, it doesn't work. Neither does it when I start a word with a capital letter.
You are using scanner.next() to read in your arguments. In the case of a race car, this means it will read in the first word: race. Which is indeed not a palindrome. To solve this, you need to use scanner.nextLine() to read everything until the next line.
For ignoring case sensitivity, you could change all input to lower case. The string method has a very usefull out of the box method: toLowerCase()
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word = sc.nextLine();
word = word.replace(" ", "");
word = word.toLowerCase();
String reverse = "";
for (int i = word.length() - 1; i >= 0; i--) {
reverse += word.charAt(i);
}
boolean palindrome = true;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != reverse.charAt(i)) {
palindrome = false;
}
}
if (palindrome) {
System.out.println("Your word is a palindrome!");
} else {
System.out.println("Your word is not a palindrome!");
}
}

Count letter in a word from scanner, java

My code is looking like this right now, it's counting the letters in the word but I would like my code to count every letter in the word so if I write banana or nine, the code will ask which letter to count, and if I choose "N", it will print 2 "N". Please help me out.
System.out.println("Ange ordet du vill leta i: ");
String str1 = sc.nextLine();
System.out.println("Ange bokstaven du vill leta efter: ");
String str2 = sc.nextLine();
int count = 0;
for(int i = 0; i < str2.length(); i++) {
if(str2.charAt(i) != ' ')
count++;
}
System.out.println("Antal bokstäver i ditt ord: " + count);
You don't need to count every letter at first. You should count after getting the letter to count. But depending on the scenario. I assume that you need to get the count of the letter in a particular string.
You can wrap counting logic inside a while() to do this over and over again.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter word");
String s = scanner.next();
System.out.println("enter letter");
char a = scanner.next().charAt(0);
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == a){
count++;
}
}
System.out.println(count);
}
}

I am generating a series of numbers delimited with space but I want to remove the space at end

I am generating the series of numbers using for loop, delimited with space but I want to remove trailing space at last. Unable to use trim() for the output.
import java.util.*;
public class Main {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int str = s.nextInt();
for(int i=1; i<=str; i++) {
System.out.printf("%d", i);
System.out.print(" ");
}
}
}
1 2 3 4 5(space here)
but I want output without the space after 5.
int i;
for(i = 1; i < str.length(); i++) {
System.out.print(i + " ");
}
System.out.println(i);
Do an if test inside the for-loop like this
if (i == str) {
System.out.printf("%d", i);
} else {
System.out.printf("%d", i);
System.out.print(" ");
}
The logic you want is to print a space behind every number, except for the last number. You should have this conditional logic in your code somewhere. Like,
if (i < str)
System.out.print(" ");
Note: it's very confusing to call a variable str if it contains a number; everyone will assume that it's a String instead of a number. You could change code to something like this:
public static void main(String [] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
for(int i = 1; i <= n; i++) {
System.out.print(i);
if (i < n)
System.out.print(" ");
}
}

Unable to accept two strings in first iteration but works fine during successive iterations

I'm scanning 2 strings during each iteration and storing it in s and t. Only during the first iteration, the first string that I scan is getting stored in t and not in s (I got to know this by debugging in eclipse). During successive iterations the piece of code works fine. I'm not able to understand what is going on during the first iteration. Please help me. Thanks.
import java.io.*;
import java.util.*;
public class ResidentInfo {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int i,n;
n = scan.nextInt();
for(i=0 ; i<n ; i++)
{
int sl,tl,j,k;
String s, t;
boolean flag = false;
s = scan.nextLine();
t = scan.nextLine();
sl = s.length();
tl = t.length();
char[] sa = new char[sl];
char[] ta = new char[tl];
sa = s.toCharArray();
ta = t.toCharArray();
for(j=0 ; j<sl ; j++)
{
for(k=0 ; k<tl ; k++)
{
if(sa[j]==ta[k])
{
flag = true;
break;
}
}
if(flag)
{
break;
}
}
if(flag)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
The first thing this code does is determine if the two strings' lengths are equal. If the strings' lengths are not equal, the code prints no. If the lengths are equal, the code then checks each character in the exact same index in the strings, to see if they are equal. If the characters at a specific index is not equal, the code breaks the loop and prints no. If all of the characters at each index are equal the code prints yes.
You asked a question about next() and nextLine().
Try: Question asked already.
Scanner scan = new Scanner(System.in);
System.out.print("enter a number: ");
int n = scan.nextInt();
for(int i=0; i < n; i++)
{
boolean flag = true;
System.out.print("enter something for s: ");
String s = scan.next();
System.out.print("enter something for t: ");
String t = scan.next();
if(s.length() == t.length())
{
for(int j = 0; j < s.length(); j++)
{
if(s.charAt(j) != t.charAt(j))
{
flag = false;
break;
}
}
if(flag)
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}
}
else
{
System.out.println("NO");
}

Finding all uppercase letters of a string in java

So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}

Categories

Resources