Converting a user input word into a unicode array in Java - java

So I am having a problem figuring out how to convert a word that the user input into a int array that has each of the letters of the word in their own unicode values (so something like "A" would turn into 65 in the array). I was thinking of one way that this could be done is that first I have the word input by the user split up into separate chars (so the String "And" would first be split up into chars "A", "n", "d", and then would turn into ints 65, 110, 100 when they are put into the int array). The problem is that I am lost on where to go. I am not sure how I would split the word up into separate chars, and then have those chars be converted, and go into an int array. Any help is greatly appreciated! Also just as I side note I need to be able to find the maximum, minimum, and average of all the values as well.

Try this:
public static void stringToArray (){
Scanner in = new Scanner(System.in);
System.out.print("Input String: ");
String input = in.nextLine();
Integer[] lista = new Integer[input.length()];
for(int i=0;i<input.length();i++) {
lista[i] = input.codePointAt(i);
System.out.print(lista[i] + " ");
}
System.out.print("\nArray descending order: ");
Arrays.sort(lista, Collections.reverseOrder());
for(int i=0;i<input.length();i++)
System.out.print(lista[i] + " ");
if (lista.length>0) {
int min=lista[0];
int max=lista[0];
int sum=0;
int avg;
for(int i=0;i<lista.length;i++){
if (lista[i]> max) max=lista[i];
if (lista[i]< min) min=lista[i];
sum += lista[i];
}
avg=sum/lista.length;
System.out.println("\nThe maximun value is: "+max);
System.out.println("The minimun value is: "+min);
System.out.println("The average value is: "+avg);
}
}

This will add each character to an integer array:
public static int[] codepoints(String str) {
int[] arr = new int[str.length()];
for (int i = 0; i < arr.length; i++) {
arr[i] = str.charAt(i);
}
return arr;
}
DEMO

One possible solution would be to iterate the characters in your String and copy them into a new int array like,
public static int[] getPoints(String str) {
if (str == null) {
return null;
}
char[] chars = str.toCharArray();
int[] out = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
out[i] = chars[i];
}
return out;
}
And then you might test it like,
public static void main(String[] args) {
System.out.println(Arrays.toString(getPoints("And")));
}
Output is (as requested)
[65, 110, 100]

Related

I want to display the occurrence of a character in string. How can I improve my code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a program that will display the number of occurrences of a character in a string and also count them. Right now the code just counts the characters.
I want to make the following changes:
1) How do I make this program only count one type of a character, like a or c in a string I love ice cream.
2) How do I also print the character in a string, let's say there are two d my program will then display 2 d first.
3) For the Scanner input = new Scanner(System.in); part I get error in my eclipse, says scanner cannot be resolved to a type.
Also feel free to comment on anything need to be improved in the code. Basically just want a simple program to display all the C in a string and then count the string's occurrence. I want to then mess around the code on my own, change it so I can learn Java.
So this is my code so far:
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str);
}
}
Try this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// Whatever is the input it take the first character.
char searchKey = input.nextLine().charAt(0);
countString(str, searchKey);
}
public static void countString(String str, char searchKey) {
// The count show both number and size of occurrence of searchKey
String count = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count += str.charAt(i) + "\n";
}
System.out.println(count + "\nNumber of Occurrence of "
+ searchKey + " is " + count.length() + " in string " + str);
}
You could utilize the fact that each char can be used as an index into an array and use an array to count up each character.
public class Count {
static final int MAX_CHAR = 256;
private static void countString(String str, Character character) {
int [] counts = new int[MAX_CHAR];
char [] chars = str.toCharArray();
for (char ch : chars) {
if (character!=null && character!=ch) {
continue;
}
counts[ch]++;
}
for (int i=0; i<counts.length; i++) {
if (counts[i]>0) {
System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
countString(str, 'e');
}
}
you can take input from user "which character he/she wants to count".
To show the occurrence of character see code below.
You need to import java.util.Scanner class.
Here is your code:
import java.util.Arrays;
import java.util.Scanner;
public class Count {
public static void countString(String str)
{
if(str!=null) {
int length = str.length();
// Create an array of given String size
char ch[] = str.toCharArray();
Arrays.sort(ch);
if(length>0) {
char x = ch[0];
int count = 1;
for(int i=1;i<length; i++) {
if(ch[i] == x) {
count++;
} else {
System.out.println("Number of Occurrence of '" +
ch[i-1] + "' is: " + count);
x= ch[i];
count = 1;
}
}
System.out.println("Number of Occurrence of '" +
ch[length-1] + "' is: " + count);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();//"geeksforgeeks";
countString(str);
}
}
See the snippet below for a way to do it in Java8
public static void main(String[] args) {
// printing all frequencies
getCharacterFrequency("test")
.forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));
// printing frequency for a specific character
Map<Character, Long> frequencies = getCharacterFrequency("test");
Character character = 't';
System.out.println("Frequency for t: " +
(frequencies.containsKey(character) ? frequencies.get(character): 0));
}
public static final Map<Character, Long> getCharacterFrequency(String string){
if(string == null){
throw new RuntimeException("Null string");
}
return string
.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
You just have to modify this line of code:
using for loop, print str.charAt(i) for count[str.charAt(i) times in your if statement.
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
Edit: modified based on your comment, if you want the whole code
import java.util.*;
public class Count {
static final int MAX_CHAR = 256; //is this part even needed?
public static void countString(String str)
{
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int length = str.length();
// Initialize count array index
for (int i = 0; i < length; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < length; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j]){
//System.out.println(str.charAt(i));
find++;
}
}
if (find == 1) {
for(int k=0;k< count[str.charAt(i)];k++)
System.out.print(str.charAt(i)+",");
System.out.println(count[str.charAt(i)]);
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksfeorgeeks";
str = input.nextLine();
countString(str);
}
}
output
g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1
I know you are beginner but if you want to try new version java 8 features which makes our coding life simple and easier you can try this
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
List<String> l = Arrays.asList(str.split(""));
// prints count of each character occurence in string
l.stream().forEach(character->System.out.println("Number of Occurrence of " +
character + " is:" + Collections.frequency(l, character)));
if(!(Character.toString(value).isEmpty())) {
// prints count of specified character in string
System.out.println("Number of Occurrence of " +
value + " is:" + Collections.frequency(l, Character.toString(value)));
}
}
And this is the code with requirements mentioned in comments
public class Count {
static final int MAX_CHAR = 256;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = "geeksforgeeks";
countString(str, 'e');
}
public static void countString(String str, char value)
{
String[] arr = str.split("");
StringBuffer tempString = new StringBuffer();
for(String s:arr) {
tempString.append(s);
for(char ch:s.toCharArray()) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString.chars().filter(i->i==ch).count());
}
}
if(!(Character.toString(value).isEmpty())) {
StringBuffer tempString2 = new StringBuffer();
for(String s:arr) {
tempString2.append(s);
for(char ch:s.toCharArray()) {
if(ch==value) {
System.out.println("Number of Occurrence of " +
ch + " is:" + tempString2.chars().filter(i->i==ch).count());
}
}
}
}
}
}
You can use this code below;
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char key = input.nextLine().charAt(0);
countString(str, key);
}
public static void countString(String str, char searchKey) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == searchKey)
count++;
}
System.out.println("Number of Occurrence of "
+ searchKey + " is " + count + " in string " + str);
for (int i = 0; i < count; i++) {
System.out.println(searchKey);
}
if (count > 0) {
System.out.println(count);
}
}
}
I would create a method such as the one below:
public static String stringCounter(String k) {
char[] strings = k.toCharArray();
int numStrings = strings.length;
Map<String, Integer> m = new HashMap<String, Integer>();
int counter = 0;
for(int x = 0; x < numStrings; x++) {
for(int y = 0; y < numStrings; y++) {
if(strings[x] == strings[y]) {
counter++;
}
}m.put(String.valueOf(strings[x]), counter);
counter = 0;
}
for(int x = 0; x < strings.length; x++) {
System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
}
return m.toString();
}
}
Obviously as you did, I would pass a String as the argument to the stringCounter method. I would convert the String to a charArray in this scenario and I would also create a map in order to store a String as the key, and store an Integer for the number of times that individual string occurs in the character Array. The variable counter will count how many times that individual String occurs. We can then create a nested for loop. The outer loop will loop through each character in the array and the inner loop will compare it to each character in the array. If there is a match, the counter will increment. When the nested loop is finished, we can add the character to the Map along with the number of times it occurred in the loop. We can then print the results in another for loop my iterating through the map and the char array. We can print the number of times the character occurred as you mentioned doing, along with the value. We can also return the String value of the map which looks cleaner too. But you can simply make this method void if you don't want to return the map. The output should be as follows:
I tested the method in the main method by entering the String "Hello world":
System.out.println(stringCounter("Hello World"));
And here is our final output:
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
You get the number of times each character occurs in the String and you can use either the Map or print the output.
Now for your scanner. To add the Scanner to the program here is the code that you will need to add at the top of your code to prompt the user for String input:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
You have to create the Scanner Object first, adding System.in to the constructor to get input from the keyboard. You can then prompt the user with a print statement to enter a String. You can then create a String variable which will store the String by calling the "Scanner.nextLine()" method as the value. This will grab the next line of userinput from the keyboard. Now you can pass the userinput to our method and it will operate the same way. Here is what it should look like to the user:
Please enter a String:
Hello World
1H
1e
3l
3l
2o
1
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}

Counting upper-case characters in array with strings

So i'm trying to count the number of upper-case characters in a array with strings. I'm at a brick wall here. If someone could shed some light on my problem that would be fantastic.
I assume the same loop can be done with just Character.isLowerCase(item) as well right?
After this is completed I also have to tell the user the longest string in the array and how many characters the longest string has as well which I really don't know how to do.
Professor really threw a curve ball at us with this one..
So here's my code so far:
// Program3.java
// Brandin Yoder
// 2/23/18
// Store strings in an array and tell user number of upper-case and lower-case characters,
// and spaces
import java.util.Scanner;
public class Program3
{
public static void main(String[] args)
{
// Set up keyboard.
Scanner keyboard = new Scanner(System.in);
// Input number of strings to store.
System.out.print("Number of strings to input: ");
int nrStrings = keyboard.nextInt();
// Clear keyboard buffer.
keyboard.nextLine();
// Set up array to hold strings.
String[] strings = new String[nrStrings];
// Input strings from keyboard.
System.out.println("\nInput strings:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.print("String #" + (ctr+1) + " :");
strings[ctr] = keyboard.next();
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
}
// Set up variables for upper-case, lower-case and white space calculator.
int UpperNr = 0;
int LowerNr = 0;
int Spaces = 0;
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < nrStrings; ctr++)
{
char item = strings[ctr].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
System.out.println(UpperNr);
}
}
You need to create variables to hold the data that you want to print out at the end. In this case you need to maintain an array that has the number of Uppercases for each string as well as the index and length of the longest string. You have to use a nested for loop to iterate through the array of strings that you have and also the strings themselves in order to check how many Uppercase characters you have. I have modified/commented the last part of your code below.
//array that contains number of uppercase letters in each string
int[] upperAmount = new int[nrStrings];
//index of the longest string
int maxLenIndex = 0;
//length of longest string
int maxLength = 0;
//array that iterates through all the strings in the array strings[]
for(int i = 0; i<strings.length;i++){
//if the new string is the longest
if(strings[i].length() > maxLength){
//set maxlength to the new length and record index of string
maxLength = strings[i].length();
maxLenIndex = i;
}
// For loop that determines amount of Upper-Case numbers.
for(int ctr = 0; ctr < strings[i].length(); ctr++)
{
char item = strings[i].charAt(ctr);
if(Character.isUpperCase(item))
UpperNr++;
}
//add number of uppercases to upperAmount array indexes will be the same
upperAmount[i] = UpperNr;
//reset upper number
UpperNr = 0;
}
// Print back strings input.
System.out.println("\nStrings input:");
for(int ctr = 0; ctr < nrStrings; ctr++)
{
System.out.println("String #" + (ctr+1) + ": " + strings[ctr]);
System.out.println("Number of Uppercase Letters: " + upperAmount[ctr]);
}
System.out.println("MaxStringLength: " + maxLength);
System.out.println("Max String: " + strings[maxLenIndex]);
}
I hope this solves your problem
//after you finish printing the strings
String strMax="";
int ctr=0;
for(String str :strings ){
strMax = str.length()>strMax.length()?str:strMax;
if(!str.equals(str.toLowerCase())){
for(char c : str.toCharArray()){
if(Character.isUpperCase(c))
ctr++;
}
}
}
System.out.println("Longeset String"+strMax );
System.out.println("total Upper case chars" +ctr);
Is it neccesarry to input the count of strings? I think you can accept one whole string and convert it into array of chars
char[] charArray = acceptedString.toCharArray;
Then go throw all chars, and where charArray[n] > 64 && charArray[n] < 91 increase your variable to counting UpperCases. Hope you understand) Ask if you have questions.
Scanner keyboard = new Scanner(System.in);
String inString = keyboard.nextLine();
char[] symbol = inString.toCharArray();
int count =0;
for(int i =0; i < symbol.length; i++){
if(symbol[i] > 64 && symbol[i] < 91){ //cause every char has its own number in Unicode. 'A' = 65 and 'Z' = 90
count++;
}
}
System.out.print(count);

Separate odd even from string

The below is the question:
Get comma separated String of numbers from user and print the set of odd numbers and even numbers.
sample input:
1,2,3,4,5,6,7,8,9,10
Sample output:
Odd Numbers:
1,3,5,7,9
Even Numbers:
2,4,6,8,10
Sample input:
20,30,40
Sample output:
Even Numbers:
20,30,40
My code:
class OddEv{
public static void main(String args[]){
String s;
Scanner in=new Scanner(System.in);
s=in.nextLine();
for(int i=0;i<s.length();i++){
if(s.charAt(i)%2==0){
System.out.print(s.charAt(i));
}
if(s.charAt(i)%2!=0){
System.out.print(s.charAt(i));
}
}
but I am not getting the right answer. What changes should I bring to get the right output according to the question
actually I don't know java very well so I don't know what to do here
You can try this simple solution, without using any other concepts like regex. For this, you can split your string and store it in a string array, and than iterating over an array you can check whether the number is odd or even. Following code will store all the even and odd numbers from your string into the array named even and odd.
String s = "1,2,3,4,5,6,7,8,9,10";
int even[] = new int[10];
int odd[] = new int[10];
String ar[] = s.split(",");
int j=0,k=0,oddChecker=0,evenChecker=0;
for(int i=0;i<ar.length;i++){
if(Integer.parseInt(ar[i])%2 == 0){
even[j] = Integer.parseInt(ar[i]);
++j;
evenChecker = 1;
}
else{
odd[k] = Integer.parseInt(ar[i]);
++k;
oddChecker = 1;
}
}
if(oddChecker == 0){
System.out.println("even");
System.exit(0);
}
if(evenChecker == 0){
System.out.println("odd");
System.exit(0);
}
System.out.println("Even numbers:");
for(int i=0;i<j;i++){
if(i!=j-1){
System.out.print(even[i]+",");
}
else{
System.out.print(even[i]);
}
}
System.out.println();
System.out.println("Odd numbers:");
for(int i=0;i<k;i++){
if(i!=k-1){
System.out.print(odd[i]+",");
}
else{
System.out.print(odd[i]);
}
}
Output:
Even numbers:
2,4,6,8,10
Odd numbers:
1,3,5,7,9
Don't forget to convert String to Integer when checking the condition and adding numbers to arrays. For that I've used Integer.parseInt(your_string).
use two ArrayList of Integer for odds and evens, and change String s to String []s then use userInput.split(",") to separate numbers. parse strings in s to integer using Integer.parseInt(str) method then use if statement to determine number is odd or even and add them to arraylists.
public static void main(String args[]) {
String s[];
Scanner in = new Scanner(System.in);
s = in.nextLine().split(",");
ArrayList<Integer> odds = new ArrayList<>();
ArrayList<Integer> evens = new ArrayList<>();
for (String item : s) {
int number = Integer.parseInt(item);
if (number % 2 == 0) {
evens.add(number);
} else {
odds.add(number);
}
}
}
you can use following code to print results in output:
System.out.println("Even Numbers:");
System.out.println(Arrays.toString(evens.toArray()).replaceAll("[\\p{Ps}\\p{Pe}]", ""));
System.out.println("Odd Numbers:");
System.out.println(Arrays.toString(odds.toArray()).replaceAll("[\\p{Ps}\\p{Pe}]", ""));
sample input:
10,11,12,13,14,15,16,17,18,19,20
sample output:
Even Numbers:
10, 12, 14, 16, 18, 20
Odd Numbers:
11, 13, 15, 17, 19
hope this solves your problem
public class CommaSeperatedNum {
public static void main(String args[]){
String s;
Scanner in=new Scanner(System.in);
s=in.nextLine();
String numarray[] = s.split(",");
int odd[] = new int[20];
int oddcnt=0;
int even[] = new int[20];
int evencnt =0;
for(int i=0;i<numarray.length;i++)
{
if( Integer.parseInt((numarray[i]).trim())%2 ==0){
odd[oddcnt] = Integer.parseInt(numarray[i].trim());
oddcnt++;
}
{
even[evencnt] = Integer.parseInt(numarray[i].trim());
evencnt++;
}
}
System.out.print("Odd Numbers : " );
for (int i = 0; i < odd.length && odd[i] != 0; i++) {
System.out.print(odd[i]+" " );
}
System.out.println();
System.out.print("Even Numbers : " );
for (int i = 0; i < even.length && even[i] != 0; i++) {
System.out.print(even[i]+" " );
}
}
Following is a more functional solution with less moving parts:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String[] split = in.nextLine().split(",");
String evens = Arrays.stream(split)
.filter(number -> Integer.parseInt(number) % 2 == 0)
.collect(Collectors.joining(","));
String odds = Arrays.stream(split)
.filter(number -> Integer.parseInt(number) % 2 != 0)
.collect(Collectors.joining(","));
System.out.println("Even Numbers:\n" + evens);
System.out.println("Odd Numbers:\n" + odds);
}
Yeah, it's quite inefficient, I know. There's probably a better way to do it, but I just wanted the OP to get a hint of how descriptive and simple a code can be.
a lambda with partitioningBy does the separation
it depends only on the last digit whether a string represents an even or odd number
a conversion into a numerical value is not necessary
String inp = "1,2,3,4,5,6,7,8,9,10";
String[] nums = inp.split( "," );
Map<Boolean, List<String>> map = Arrays.stream( nums ).collect(
partitioningBy(s -> "02468".indexOf(s.charAt(s.length() - 1)) >= 0));
System.err.println( "even: " + map.get( true ) );
System.err.println( "odd: " + map.get( false ) );
even: [2, 4, 6, 8, 10]
odd: [1, 3, 5, 7, 9]

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

recognized a numbers and letters in a inputted string

so far i have no problem in getting the length but the recognizing the numbers from letters is hard can any one help me here Thanks for the helps heres the new code my new problem is in counting the elements in the string in will not count the numbers inputted like a Address Example 99 San pedro st philippines ..... it will only count San pedro st philippines .........
import java.util.Scanner;
public class Exercise3
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
System.out.println("Enter String:");
String s=scan.nextLine();
s = s.replace(" ","");
System.out.println("Total of Elements is: " + s.length());
int nDigits =0,nLetters =0,sum =0;
for(int i =0;i<s.length();i++)
{
Character ch = s.charAt(i);
if(Character.isDigit(ch)){
nDigits++;
sum += Integer.parseInt(ch.toString());
}
else if (Character.isLetter(ch)){
nLetters++;
}
}
System.out.println("The sum of numbers in the string: " + sum);
}
}
}
It looks like your problem is with the line sum += Integer.parseInt(s.toString());. You're taking the string value of the entire InputStream, which is almost certainly what you don't want. I assume you intended to do sum += Integer.parseInt(s.charAt(i).toString());, which will give you just the value of each individual digit. Take in mind in the string hello43world, it would return 7 (4+3), not 43.
EDIT: To do what you actually want - which is the number of letters in the string, try
public static int getSum(String s)
{
int sum = 0;
for(int i = 0; i < s.length(); i++)
{
if(Character.isLetter(s.charAt(i)))
{
sum ++;
}
}
return sum;
}
This will only count the characters in the string - much easier than trying to not count everything that isn't a character.

Categories

Resources