Dot Counter issue - java

I have a homework assignment that requires me to write a program that counts the dots in an input line. So far this is what I have came up with it works (sort of)except that it is counting everything instead of only the dots. I am stuck with how to make the program to only count the dots.
import javax.swing.*;
import java.lang.Character;
public class Assign5_Polk {
public static void main(String[] args) {
String string = JOptionPane.showInputDialog("Give me dots and i will count them : ");
int count = 0;
for (int i = 0; i< string.length(); i++) {
char c = string.charAt(i);
if (string.contains(".")) {
count++;
}
}
System.out.println("There are" + " "+ count + " " + "dots" +" " + "in this string. " + string);
}
}

if (string.contains("."))
This line is checking the whole string and returning true if there is a . anywhere in it.
Instead, you want to test if c is a .

Change the if condition as below :
if (string.contains(".")) { // Check whole String contain dot
count++;
}
to
if (c == '.') { //Check single char of String contain dot
count++;
}

In your for loop, you repeatedly test if the entire string has dots, and increment the counter each time. You need something like if (c == '.') instead, to determine if the character you are looking at is a dot.

Solution without loop ;-)
count = string.replaceAll("[^.]","").length();
This makes your program pretty short:
public static void main(String[] args) {
String string = JOptionPane.showInputDialog("Give me dots and i will count them : ");
int count = string.replaceAll("[^.]","").length();
System.out.println("There are "+ count + " dots in this string: " + string);
}

Related

Whitespace Location Finding

So the instructions I have are as follows:
Write code to print the location of any space in the 2-character string passCode. Each space detected should print a separate statement followed by a newline. Sample output for the given program:
Space at 1
The code I currently have written is:
import java.util.Scanner;
public class FindSpaces {
public static void main (String [] args) {
String passCode = "";
passCode = "A ";
if (Character.isWhitespace(passCode.charAt(0))){
System.out.println("Space at " +passCode.indexOf(" "));
}
else if (Character.isWhitespace(passCode.charAt(1))){
System.out.println("Space at " +passCode.indexOf(" ", 1));
}
else{
}
return;
}
}
Now this works sometimes but if I have more than one space in my input, it only ever prints one line. If it helps anyone, it is from zyBooks and I have no idea how to make it bring a second line showing a second whitespace.
When you do
if ( condition1 ) {
doSomething();
}
else if ( condition2 ) {
doSomethingElse();
}
the else means that you will only test condition2 (and so only have a chance of calling doSomethingElse()) if condition1 is false. You just need to remove that else from your code.
While the length might be limited to two, I still guess a for loop would fit better:
String passCode = "";
passCode = " ";
for (int i = 0; i < passCode.length(); i++) {
if (passCode.charAt(i) == ' ') {
System.out.println("Whitespace at index " + (i + 1));
}
}
To look at your solution: Your code can't enter any output for more than one time. You have if() else() - simply remove the else, and you should be fine:
String passCode = "";
passCode = " ";
if (Character.isWhitespace(passCode.charAt(0))) {
System.out.println("Space at " + passCode.indexOf(" "));
}
if (Character.isWhitespace(passCode.charAt(1))) {
System.out.println("Space at " + passCode.indexOf(" ", 1));
}
To find and print the location of each whitespaces in a string, you simply iterate through the string and check if the current character is a whitespace:
String str = "Find the space location";
for(int i = 0; i < str.length(); i++) {
if(Character.isWhitespace(str.charAt(i)) {
System.out.println("Space at " + i);
}
}

Working on a java program to find the distance of two words in a dictionary file

EDIT: Problem solved! I was just blind :)
As the title says, I've been working on finding the distance between two inputted words. The dictionary file is just a file with words separated by a space. Every time that I run the program, it says that I have 0 words between the two inputted. I'm not sure what I am doing wrong.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class wordDistance {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
Scanner sfile = new Scanner(new File("C:/Users/name/Desktop/Eclipse/APCS/src/dictionary.txt"));
int count = 0;
System.out.print("Type two words: ");
String start = s.next();
String end = s.next();
while (sfile.hasNextLine()) {
String line = sfile.nextLine();
String[] words = line.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i] == start) {
for (int j = i + 1; j < words.length; j++) {
if (!(words[j] == end)) {
count++;
}
if (words[j] == end) {
break;
}
}
}
}
}
System.out.println("There are " + count + " words between " + start + " and " + end);
}
}
the == operator checks whether the references to the objects are equal, use the method String.equals(String); instead.
For example:
if (words[j].equals(end))
if (!(words[j].equals(end)))
if (words[i].equals(start))
you should compare strings with equals() rather than ==
For example,
if (words[j].equals(end)) {
break;
}
if you change your comparisons you should get the correct output.
You cannot use the == operator to equate strings. Use the equals(String string) function instead.
if (!words[j].equals(end)) {
count++;
}
if (words[j].equals(end)) {
break;
}

How to print out the number of capital letters in a string - java

So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();

Slicing a string

I'm trying to slice a string for the first time.
With this code, if I input, for example 'one two three' it works fine until the last word.
This is the last few lines of the output:
Current word is thr
Sentence is now e
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.substring(String.java:1907)
at TestCurr.main(testCurrentWord.java:18)
Has anyone any idea why it does that to the last word?
class TestCurr
{
public static void main (String []args)
{
String s;
int i;
String currentWord;
int length;
int spacePos;
System.out.println("Enter a sentence ");
s = EasyIn.getString();
spacePos = s.indexOf(" ");
length = s.length();
for (i = length -1; i >= 0; i--)
{
currentWord = s.substring(0,spacePos);
s = s.substring(spacePos +1);
System.out.println("Current word is " + currentWord);
System.out.println("Sentence is now " + s);
}
}
}
First of all, you call
spacePos = s.indexOf(" ");
length = s.length();
only once, but these values should change with each iteration of the loop. Furthermore,
s.substring(spacePos +1);
with
spacePos == s.length()-1
means you are passing an index beyond the end of the string as the start index for substring(). Once you fix the first error, this will be your next exception.
Your problem is that you only get the index of the space once. This causes the program to cut the string every three characters, as the first word is three letters long. You need to update spacePos after each iteration.
I believe your problem is in your usage of your spacePos variable.
Outside the loop, you initialize the variable like so:
spacePos = s.indexOf(" ");
Which in your example string of "one two three", yields 3.
But then inside your loop, you never set the variable again, based on what whatever is left that you haven't processed.
Try re-calculating spacePos's value inside the loop and your problem should go away.
Your current approach is too error prone.
And you have too many variables.
Try this just as an idea.
class TestCurr {
public static void main(String[] args) {
String s = null;
System.out.println("Enter a sentence: ");
s = " one two three ";
System.out.println("|" + s + "|");
int i = 0;
int j = 0;
while (true){
while (i<s.length() && s.charAt(i)==' ') i++;
j = i;
if (i>=s.length()) break;
while (i<s.length() && s.charAt(i)!=' ') i++;
System.out.println("Current word is: [" + s.substring(j, i)+ "]");
System.out.println("Sentence is now: [" + s.substring(i) + "]");
if (i>=s.length()) break;
}
}
}
As others have stated, you only get the index once. But I'm curious, why re-invent the wheel?
String s = "one two three";
String[] split = s.split(" ");
for (String out : split) {
System.out.println("Word: " + out);
}

For loop only loop 1 time JAVA?

I have a trouble with the for loop method that only loop 1 times whats is the problem? In the array was no problem at all, it able to print the value I want to.
here is my code:
public static void main(String[] args){
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++){
if(word[y].toString().equals("Apple2") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple3") ){
total++;
//str.append(word[y].toString());
}else if(word[y].toString().equals("Apple4") ){
total++;
//str.append(word[y].toString());
}
else if(word[y].toString().equals("Apple1") ){
total++;
//str.append(word[y].toString());
}
}
System.out.println( word[0] + word[1] + word[2] + word[3] + word[4] + word.length);
System.out.println(str + "hihi" + total);
}
The others have nailed the cause of your problem. However, the fix they suggest is rather too specific ... and fragile. (Splitting with split("\\s*,\\s*") is better but it won't cope with whitespace at the start / end of the entire string.)
I suggest that you continue to use split(","), but trim the words before testing; e.g.
for (int y = 0; y < word.length; y++) {
String trimmed = word[y].trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
or better still:
String[] words = s.split(",");
for (String word : words) {
String trimmed = word.trim();
if (trimmed.equals("Apple2")) {
total++;
//str.append(trimmed.toString());
} else if (trimmed.equals("Apple3")) {
// etcetera
That will make your code work irrespective of the whitespace characters around the commas and at the start and end of the string. Robustness is good, especially if it costs next to nothing to implement.
Finally, you could even replace the if / else if / ... stuff with a Java 7 String switch statement.
Try splitting on ", " (with space)
String[] word = s.split(", ");
without that space in split word[1] would look like " Apple1" instead "Apple1"
Other option would be calling word[y].trim().equals("Apple2") to get rid of that additional space, but I would say including it in split is better. If you aren't sure how many white-spaces can be near comma you can split this way split("\\s*,\\s*") to include all white-spaces around comma.
Also as Matt Ball pointed in his comment you don't need to call toString() on word[y] since it is already String.
you ignore the space during split. String[] word = s.split(", ");
You'are split by "," but your String contains ", ".
You can change the s.split(","); to s.split(", ");
Or trim the split's result like this :
public static void main(String[] args) {
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
String[] word = s.split(",");
StringBuffer str = new StringBuffer();
Integer total = 0;
for (int y = 0; y < word.length; y++) {
if (word[y].trim().equals("Apple2")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple3")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple4")) {
total++;
// str.append(word[y].toString());
} else if (word[y].trim().equals("Apple1")) {
total++;
// str.append(word[y].toString());
}
}
System.out.println(word[0] + word[1] + word[2] + word[3] + word[4]
+ word.length);
System.out.println(str + "hihi" + total);
}
There is nothing wrong with your code but the problem lies in the String that you are giving to the variable.
String s = "Apple0, Apple1, Apple2, Apple3, Apple4";
Here the string contains spaces between them after the comma. So that when you split your string it splits like
word[0]= "Apple0"
word[1]= " Apple1"
word[2]= " Apple2"
word[3]= " Apple3"
and so on.
So that when you compare like
word[y].equals("Apple1") it returns false because " Apple1" and "Apple1" are two different strings. So that initialize your string like this
String s = "Apple0,Apple1,Apple2,Apple3,Apple4"; // without white spaces
It will work fine. Or you can use trim method in your existing code without changing String like
word[y].trim().equals("Apple1") //It will trim all the leading and trailing white spaces.
Hope this helps.

Categories