recognized a numbers and letters in a inputted string - java

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.

Related

How can I get my output to be separated by commas based on user input from scanner?

I have a class which takes keyboard input, how could I go about making it so that it can take multiple double and char inputs on one line e.g. 1 2 a a a to then get the output:
"1","2","a","a","a" by splitting it into separate strings? this is what I've done so far:
public class MyInputInfo implements Comparable <MyInputInfo> {
public static double numeric;
public static char symbol;
public MyInputInfo(double numeric, char symbol) {
this.numeric = numeric;
this.symbol = symbol;
}
public static char getSymbol() {
int asciiValue = 97;
for (int i = asciiValue; i <= 122; i++) {
String convertedChar = Character.toString ((char) i);
System.out.println (convertedChar);
}
return symbol;
}
#Override
public int compareTo(MyInputInfo o) {
if (this.numeric < o.numeric) {
return 1;
} else if (this.getSymbol( ) < o.getSymbol ( )) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return "Numeric " + numeric + " Symbol " + symbol;
}
}
the class im working on right now
import java.util.*;
public class MyKeyboardInput {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
MyInputInfo.numeric = s.nextDouble();
MyInputInfo.symbol = s.next ( ).charAt (0);
System.out.println (MyInputInfo.numeric+ "," + MyInputInfo.symbol);
}
}
I'm new to java so apologies for coming off as slow. All help is appreciated!
There are two options:
Obtain numbers and chars in predictable order
Obtain numbers and chars in random order
Obtain numbers and chars in predictable order
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of iterations: ");
int count = scanner.nextInt();
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
System.out.print("\nEnter a floating point number: ");
buffer.append(scanner.nextDouble() + " ");
System.out.print("\nEnter a character: ");
buffer.append(scanner.next().charAt(0) + " ");
}
scanner.close();
String output = buffer.toString().trim().replaceAll(" ", ", ");
System.out.println(output);
}
If you enter 1 a 2 b 3 c 4 d 5 e, the output will look like this
1.0, a, 2.0, b, 3.0, c, 4.0, d, 5.0, e
It's really that simple. The key is to use StringBuilder to "stage" the input and then convert all of the individual inputs into a single String output. To make it easier to remove the last comma, I just separated the entries by spaces, trimmed the string to remove the last space, and then prepended the remaining spaces with a comma.
Obtain numbers and chars in random order
This solution is similar, but in this case, just capture the input as a String and then figure out if the input is numeric or not. If it is not numeric, then it is a character.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of iterations: ");
int count = scanner.nextInt();
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
System.out.print("\nEnter a number or character: ");
String s = scanner.next();
try {
Double num = Double.parseDouble(s);
buffer.append(num + " ");
} catch (NumberFormatException nfe) {
buffer.append(s.charAt(0) + " ");
}
}
scanner.close();
String output = buffer.toString().trim().replaceAll(" ", ", ");
System.out.println(output);
}
Caveats
You need to figure out what to do when something like "character" is provided as input. As you can see in the code, the code captures only charAt(0). This might or might not be correct for your use. But, this is typically how it is portrayed on the web how to get character from Scanner in Java.
Also, there is no error handling on the first solution if the input is not a number. You could try to prompt again if the character entered is not a number. Likewise, when prompted to enter a character, what happens if the input is a number? You will need to tweak the code to do what you want. With the second approach, you don't have to worry about this.

Using a for loop to call a character method multiple times. The for loop will then convert each character to a string

The output should look like the attached screenshot. I am stuck on the very last step. Using a for loop to call the getCharacter method 10 times and converting the characters to a string using the Character.toString() method.
``
public static void main(String[] args) {
int count = countNumbers();
countPlay(count);
String word = getCharacter();
stringOf10(word);
}
public static double getRealNumber(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a real number, one that has a decimal point: ");
double realNumber = sc.nextDouble();
return realNumber;
}
public static int countNumbers(){
int count = 0;
do{
if (getRealNumber() == -1.0)
break;
count++;
} while(true);
System.out.println("The count is " + count);
return count;
}
public static int countPlay(int count){
int exponent = 4;
double result = 0;
result = Math.pow(count, exponent);
System.out.println(count + "^" + exponent + " is " + result );
return count;
}
public static char getCharacter(){
Scanner input = new Scanner(System.in);
System.out.println("You will be asked to enter 10 characters.");
System.out.print("Enter a character: ");
char character = input.next().charAt(0);
return character;
}
public static char stringOf10(String word){
char i = getCharacter();
i = Character.toString(word) ;
for (i = 0; i < 10; i++){
}
return word;
}
}
``
Consider the following block of code which will run in the main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = "";
//Print the instructions before the loop
System.out.println("You will be asked to enter 10 characters.");
//request characters inside the loop
for (int i = 0; i < 10; i++){
System.out.print("Enter a character: ");
word += input.next().charAt(0);
}
//print the result (or return from a method)
System.out.println("The word is: " + word);
//return word;
}
Besides the corrections in comments, note how we create a local variable word, and simply update/append that inside the for loop word += input.next().charAt(0);.
You can easily move this code to fit your needs and return the value to be printed:
public static void main(String[] args) {
//Call the method to get our word and save the result
String result = stringOf10();
//Print the result
System.out.println("The word is: " + result);
}
public static String stringOf10(){
//Creater a scanner once before the loop
Scanner input = new Scanner(System.in);
//Create a local variable to store the word as it is updated
String word = "";
//Print the instructions once before the loop
System.out.println("You will be asked to enter 10 characters.");
//Create a loop that will run 10 times "for (int i = 0; i < 10; i++)"
//The loop starts by creating an int that is 0 "int i=0"
//Each time the loop ends it will do "i = i+1"
//The loop will run until i is no longer less than 10 "i < 10"
//Once that happens the loop will end and the code after the loop will run
for (int i = 0; i < 10; i++){
//Dach time the loop will call this method and update the word
word += getCharacter(input);
}
return word;
}
public static char getCharacter(Scanner input){
//Each time this method is called we prompt the user to enter a character
System.out.print("Enter a character: ");
//We then return the character to the previous method
return input.next().charAt(0);
}

Trying to write code that calculates the average length of words in a sentence

The code needs to have a method averageLength with the parameter String s. The method needs to return, as a double value, the average length of the words in s. Assuming s consists of only words separated by single blanks, without any leading or trailing blanks. I have a code below that finds the average length of words but it doesn't have the method averageLength:
import java.util.Scanner;
class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please type in your sentence, then press enter: ");
String words = sc.nextLine();
int count = 0;
double sum = 0;
double average = 0;
sc = new Scanner(words);
while (sc.hasNext()) {
String userInput = sc.next();
double charNum = userInput.length();
sum = charNum + sum;
count++;
if (count > 0) {
average = sum / count;
}
}
System.out.println("Average word length = " + average);
}
}
First, declare a method that returns a double and accepts a parameter of String
private static double returnAverageLength(String sentence){
With the help of the split() method, we split the sentence into words
String [] words = sentence.split(" ");
With a for loop we count all characters of the sentence
for(int i=0;i<words.length;i++){
countCharacters+= words[i].length();
}
And we return the average result
return countCharacters / words.length;
Full code
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Write sentence");
String s = scanner.nextLine();
double average = returnAverageLength(s);
System.out.println("AVERAGE IS " + average);
}
private static double returnAverageLength(String sentence){
String [] words = sentence.split(" ");
double countCharacters = 0;
for(int i=0;i<words.length;i++){
countCharacters+= words[i].length();
}
return countCharacters / words.length;
}
}
OUTPUT
Write sentence
Hello From Stackoverflow
AVERAGE IS 7.33
Since Java 8 you can use DoubleStream#average method for this purpose:
public static double averageLength(String words) {
return Arrays
// split a string into an array of
// words by spaces, returns Stream<String>
.stream(words.split(" "))
// take a word's length, returns DoubleStream
.mapToDouble(String::length)
// returns OptionalDouble
.average()
// if a value is not present, returns 0.0
.orElse(0.0D);
}
public static void main(String[] args) {
String words = "Not all questions benefit from including code " +
"but if your problem is with code you've written you " +
"should include some But don't just copy in your entire " +
"program Not only is this likely to get you in trouble " +
"if you're posting your employer's code it likely includes " +
"a lot of irrelevant details that readers will need to " +
"ignore when trying to reproduce the problem";
System.out.println(averageLength(words)); // 4.671875
}
See also: Sort semantic versions in a given array as a string

Converting a user input word into a unicode array in 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]

out of bounds error with word count

I'm trying to write my own Java word count program. I know there may already be a method for this, but I'd like to get it work. I'm getting an out of bounds error at line 14. I'm trying to use an input word to count how many times it appears in an input string. So I'm looping up to stringlength - wordlength, but that's where the problem is.
Here is the code:
import java.util.Scanner;
public class wordcount {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print( "Enter word : " );
String word = s.nextLine();
Scanner t = new Scanner(System.in);
System.out.print("Enter string: ");
String string = t.nextLine();
int count = 0;
for (int i = 0; i < string.length()-word.length(); i = i+1){
String substring = string.substring(i,i+word.length());
if (match(substring, word)==true){
count += 1;
}
}
System.out.println("There are "+count+ " repetitions of the word "+word);
}
public static boolean match(String string1, String string2){
for (int i=0; i<string1.length(); i+=1){
if (string1.charAt(i)!=string2.charAt(i)){
return false;
}
}
return true;
}
}
First of all, two Scanners are not necessary, you can do many inputs with the same Scanner object.
Also, this if condition
if (match(substring, word) == true)
can be rewritten like
if (math(substring, word))
I would also recommend you to use i++ to increase the loop variable. Is not strictly necessary but is "almost" a convention. You can read more about that here.
Now, about theIndexOutOfBoundsException, I've tested the code and I don't find any input samples to get it.
Besides, there is an issue, you are missing one iteration in the for:
for (int i = 0; i < string.length() - word.length() + 1; i++) { // Add '+ 1'
String substring = string.substring(i, i + word.length());
// System.out.println(substring);
if (match(substring, word)) {
count++;
}
}
You can test it by putting a print statement inside the loop, to print each substring.
I'm not getting an out of bounds error, can you tell me what values you were using for word and string?
I have identified a bug with your program. If word is equal to string, it still returns count 0. I suggest adding one more iteration and using regionMatches instead. RegionMatches makes your match method obsolete and will return false if word.length() + i is equal or greater than string.length(), avoiding out of bounds issues.
As you can see I also moved the calculations to a seperate method, this will make your code more readable and testable.
And as Christian pointed out; you indeed do only need one Scanner object. I've adapted the code below to reflect it.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter word : ");
String word = sc.nextLine();
System.out.print("Enter string: ");
String string = sc.nextLine();
int count = calculateWordCount(word, string);
System.out.println("There are " + count + " repetitions of the word " + word);
}
private static int calculateWordCount(String word, String string) {
int count = 0;
for (int i = 0; i < string.length() - word.length() + 1; i++) {
if (word.regionMatches(0, string, i, word.length())) {
count++;
}
}
return count;
}

Categories

Resources