Java: Identifying Ints and Non Ints in a string - java

Hello I'm trying to fix a bug in my code. When reading an incoming phrase this code doesn't seems to count integers. It counts the number of non integer words no problem.
For example if I have the following sentence :
"I love my 4 cats"
It should show that I have 4 Non integer words an 1 integer. But this is not the case with the integer, it seems to identify it as a word
Any ideas?
String[] stra = phrase.split(" ");
int numInts = 0;
int numNonInts = 0;
for (String s : stra) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException nfe) {
numNonInts++;
continue;
}
numInts++;
}

String[] stra = phrase.split("\\W+"); // + for sequences
int numInts = 0;
int numNonInts = 0;
for (String s : stra) {
try {
Integer.parseInt(s);
numInts++;
}
catch (NumberFormatException nfe) {
numNonInts++;
}
}
Two spaces would have counted as one word.
Also \\W includes all non-word chars.

Try using:
Integer.valueOf(s);
instead of
Integer.parseInt(s);

To avoid unexpected separators (like tabs, double spaces or line break), replace you split by:
phrase.split("\\s+");
And maybe you got numbers that exceed the limit of Integer.
Replace your loop by:
for (String s : stra) {
if(s.matches("\\d+"))
numInts++;
else
numNonInts++;
}

Related

How would I go about using an integer delimiter? (Java)

So I am trying to read a file using a scanner. This file contains data where there are two towns, and the distance between them follows them on each line. So like this:
Ebor,Guyra,90
I am trying to get each town individual, allowing for duplicates. This is what I have so far:
// Create scanner for file for data
Scanner scanner = new Scanner(new File(file)).useDelimiter("(\\p{javaWhitespace}|\\.|,)+");
// First, count total number of elements in data set
int dataCount = 0;
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.println();
dataCount++;
}
Right now, the program prints out each piece of information, whether it is a town name, or an integer value. Like so:
Ebor
Guyra
90
How can I make it so I have an output like this for each line:
Ebor
Guyra
Thank you!
Assuming well-formed input, just modify the loop as:
while(scanner.hasNext())
{
System.out.print(scanner.next());
System.out.print(scanner.next());
System.out.println();
scanner.next();
dataCount += 3;
}
Otherwise, if the input is not well-formed, check with hasNext() before each next() call if you need to break the loop there.
Try it that way:
Scanner scanner = new Scanner(new File(file));
int dataCount = 0;
while(scanner.hasNext())
{
String[] line = scanner.nextLine().split(",");
for(String e : line) {
if (!e.matches("-?\\d+")) System.out.println(e);;
}
System.out.println();
dataCount++;
}
}
We will go line by line, split it to array and check with regular expression if it is integer.
-? stays for negative sign, could have none or one
\\d+ stays for one or more digits
Example input:
Ebor,Guyra,90
Warsaw,Paris,1000
Output:
Ebor
Guyra
Warsaw
Paris
I wrote a method called intParsable:
public static boolean intParsable(String str)
{
int n = -1;
try
{
n = Integer.parseInt(str);
}
catch(Exception e) {}
return n != -1;
}
Then in your while loop I would have:
String input = scanner.next();
if(!intParsable(input))
{
System.out.print(input);
System.out.println();
dataCount++;
}

Number of line breaks in String

I have a text which is on a website. I am scanning that page and counting the number of several characters, including spaces caused by a line break or "enter press" and "tabs".
I have found an answer for counting the number of lines and such.
How can I do this in java? Counting whitespace is easy, there's a method for it, but not the line breaks or tabs as far as I know.
The website is this http://homepage.lnu.se/staff/jlnmsi/java1/HistoryOfProgramming.txt and I'm counting uppercase and lowercase letters, as well as spaces of any sort.
So far my output is correct for upper and lowercases but not spaces. I'm missing 15, which is exactly the number of line breaks.
public class CountChar
{
public static void main(String[] args) throws IOException
{
int upperCase = 0;
int lowerCase = 0;
int whitespace = 0;
int others = 0;
String url = "http://homepage.lnu.se/staff/jlnmsi/java1/HistoryOfProgramming.txt";
URL page = new URL(url);
Scanner in = new Scanner(page.openStream());
while (in.hasNextLine())
{
whitespace++; // THIS IS THE SOLUTION FOR THOSE WHO COME LATER <<<<<
String line = in.nextLine();
for (int i = 0; i < line.length(); i++)
{
if (Character.isUpperCase(line.charAt(i)))
{
upperCase++;
}
else if (Character.isLowerCase(line.charAt(i)))
{
lowerCase++;
}
else if (Character.isWhitespace(line.charAt(i)))
{
whitespace++;
}
else
{
others++;
}
}
}
System.out.print(lowerCase + " " + upperCase + " " + whitespace + " " + others);
}
}
You can use the Pattern and Matcher classes in the standard library to create a regular expression to search for all the characters you are looking for and count the number of occurrences using find() but don't know if this is more complex than what you require and you could just split the string on all required whitespace characters you need... (similar to Krishna Chikkala's answer)
If we assume that your data is stored in a String called data:
String[] arrayOfLines= data.split("\r?\t?\n");
int length=arrayOfLines.length-1;
length would give the number of newline characters in data.

Adding contents of a String,where string s="12 computer 5 7"

In an interview they asked me this question.There is a string like "12 computer 5 7". You need to add integers within that string and answer should be 24.How can i solve this can anyone help me please.
string s="12 computer 5 7"
output should be:24
Can i use sub-string or some other process to solve it
Try this,
String input = "12 computer 5 7";
String[] splittedValue = input.split(" "); // splitted the values by space
int result = 0;
for (String s : splittedValue)
{
if (s.matches("\\d+")) // check while the input is number or not
{
result = result + Integer.parseInt(s); // parse it and add it to the count
}
}
System.out.println("Result : "+result);
Use split("[ ]") to convert the string into an array of strings separated by space and then add the integers present in each position of the array. Add it to sum if it is an integer like :-
String ar[] = s.split("[ ]");
int sum = 0;
for(int i=0;i<ar.length;i++){
try{
sum += Integer.parseInt(ar[i]);
}catch(NumberFormatException){
//not an integer.
}
}
System.out.println("Sum of integers : "+sum);
public class Main{
public static void main(String []args){
String s="12 computer 5 7";
String [] candidateNumbers = s.split(" ");
int sum = 0;
for (String num:candidateNumbers) {
try {
sum+=Integer.parseInt(num);
} catch (Exception e) {
//
}
}
System.out.println(sum);
}
}
Using Java 8 you could also write:
int sum = Arrays.stream(s.split("\\D+"))
.mapToInt(Integer::parseInt)
.sum();
Splitting on non digit characters returns an array containing the 3 numbers as strings. Note that this assumes that the input string is well formed.

In Java, how do I take a string that a user enters and count the number of times 2 specific lowercase letters come up in order?

So like if a string is, "I am going fishing"
So the number of times the lowercase letters "ng" come up in that specific order in this string is 2 times. And they have to be right next to each other, like no space between them.
So how do I do that? Please help. So whatever string a user enters, it must count the number of times "ng" comes up. Please help. Thanks!
JAVA
If you use regex, you only need one line:
int count = input.replaceAll("[^n]|n(?!g)", "").length();
This works by removing (by replacing with a blank), all characters that are either:
not an "n"
an "n" not followed by a "g"
The resulting String will contain one "n" for every "ng" in the original String, so the count is simply its length.
public int value()
{
String str = "I am going fishing";
String findStr = "ng";
int lastIndex = 0;
int count =0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1){
count ++;
lastIndex+=findStr.length();
}
}
return count;
}
count is number of occurrence.
Try this. Use Common Lang jar in your library :
try {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the user String");
String userString=br.readLine();
System.out.println("Enter the search String");
String searchString=br.readLine();
int count = StringUtils.countMatches(userString, searchString);
System.out.println("Value "+ count);
} catch (IOException ex) {
System.out.println("No Input");
}
Output :
Enter the user String
Hello Mango Hello
Enter the search String
Hello
Value 2
String s="I am going fishing";
System.out.println(s.length());
int j=0;
int cnt=0;
for(int i=0;i<s.length();i++)
{
char i1=s.charAt(i);
j=i+1;
if((i1=='n')||(i1=='N'))
{
if((s.charAt(j)=='g')||((s.charAt(j)=='G')))
{
cnt=cnt+1;
i=j;
}
}
}
System.out.println("Count of 'ng' is "+cnt);

Writing a program to count spaces in a phrase

I'm trying to write a program where a user would enter a phrase, and the program would count the blank spaces and tell the user how many are there. Using a for loop but i'm stuck, could someone help me out?
import java.util.Scanner;
public class Count
{
public static void main (String[] args)
{
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.print ("Enter a sentence or phrase: ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a for loop to go through the string character by character
for(ch=phrase.charAt()
// and count the blank spaces
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ();
}
}
The for loop for counting spaces would be written as follows:
for(int i=0; i<phrase.length(); i++) {
if(Character.isWhitespace(phrase.charAt(i))) {
countBlank++;
}
}
It reads as follows: “i is an index, ranging from the index of the first character to the index of the last one. For each character (gotten with phrase.charAt(i)), if it is whitespace (we use the Character.isWhitespace utility function here), then increment the countBlank variable.”
Just wondering, couldn't you just split the string entered by blank spaces and take the length of the array subtracted by 1?
In C# it would be as trivial as
string x = "Hello Bob Man";
int spaces = x.Split(' ').Length - 1;
Pretty sure java has a split? Works even if you have two contiguous spaces.
You have probably problem with that for each loop
char[] chars = phrase.toCharArray(); Change string into array of chars.
for(char c : phrase.toCharArray()) { //For each char in array
if(Character.isWhitespace(c) { //Check is white space.
countBlank++; //Increment counter by one.
}
}
or
for(int i =0; i <phrase.lenght(); i++) {
if(Character.isWhitespace(phrase.charAt(i)) { //Check is the character on position i in phrase is a white space.
countBlank++; //Increment counter by one.
}
}
You have to complete for cycle and count spaces
//replace this lines
for(ch=phrase.charAt()
// and count the blank spaces
//to this lines
for (int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == ' ') countBlank++;
}
Loop through the characters in the string.
Check if the character is a space (char value = 32 or ch == ' ')
If space, add to countBlank, otherwise continue
Display the results.
You might look at the String and Character classes in the Java documentation for assistance.
I'm not very familiar with java, but if you can access each character in the string.
You could write something like this.
int nChars = phrase.length();
for (int i = 0; i < nChars; i++) {
if (phrase.charAt(i) == ' ') {
countBlank++;
}
}
This is at the following Java Tutorials
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SplitDemo2 {
private static final String REGEX = "\\d";
private static final String INPUT = "one9two4three7four1five";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
String[] items = p.split(INPUT);
for(String s : items) {
System.out.println(s);
}
}
}
OUTPUT:
one
two
three
four
five
The regex for whitespace is \s
Hope that helps.

Categories

Resources