Hello I have a working code for testing the amounts of hashtags, attributions, and links in the program but I need to test for if there is a tab key or space used after either the hashtags or attributions so as to not count them and have been having trouble.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a tweet: ");
String input = scan.nextLine();
int length = input.length();
int count = 0;
int hashtags = 0, attributions = 0, links = 0;
char letter;
char letter2;
if (length > 140) {
System.out.println("Excess Characters: " + (length - 140));
} else {
while (count < length) {
letter = input.charAt(count);
if (letter == '#') {
if (input.startsWith("#\t", count)) {
} else {
hashtags++;
count++;
}
if (letter == '#') {
if (input.startsWith("#\t", count)) {
count++;
} else {
attributions++;
count++;
}
}
if (letter == 'h') {
input = input.toLowerCase();
if (input.startsWith("http://", count)) {
links++;
count++;
} else {
count++;
}
} else {
count++;
}
}
System.out.println("Length Correct");
System.out.println("Number of Hashtags: " + hashtags);
System.out.println("Number of Attributions: " + attributions);
System.out.println("Number of Links: " + links);
}
}
}
}
One easy way:
Call Character.isWhitespace(char). (Example: Character.isWhitespace(input.charAt(count+1))). Obviously you'd need to check to make sure that the hashtag isn't the last character.
Some unsolicited advice:
Try not to use .startsWith(), because that is limited to specific characters, and you'd have to add a different if statement for each character you wanted to check for (space, tab, etc.). I recognize that this might not work in all cases, such as your .startsWith("http:") case. In this case, .startsWith() can still work, but use the count to get the index: input.substring(count).startsWith("http:") (Documentation here)
One issue your code currently faces is that the checking of spaces always goes from the beginning of a string. For the input string #\tabc #def #ghi, it will show 0 hashtags, because it fails the space on the first case, which is the one it's checking every time.
If you are constantly doing if (letter=='<char>'), you might want to try using a switch statement (e.g. switch(letter)). In Java, this works on characters (or Strings, if you are using Java 8). This can help avoid difficult-to-trace errors regarding bracket placement, etc.
Related
I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;
public class GimmeAW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Line\nEntering -1 exits the program")
String aLine;
aLine = input.nextLine();
char one = aLine.charAt(0);
char two = aLine.charAt(1);
if (one == '-' && two == '1') {
System.out.println("System Exit");
System.exit(1);
}
for (int i = 0; i < aLine.length(); i++) {
if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
int location = i;
System.out.print(" " + i);
}
}
}
To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();
for(int i = 0; i < ch.length; i++) {
System.out.print("The character " + ch[i] + " is at locations ");
// searching
for(int j = 0; j < l; j++) {
if(aLine.charAt(j) == ch[i]) {
System.out.print(j + " ");
}
}
System.out.println();
}
And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
// code
// want to repeat ??
choice = in.nextLine();
} while(choice.equals("yes"));
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;
}
I am desperately trying to figure out a way of stopping "String index out of range: 0" errors... It happens whenever I don't enter anything and then continue execution:
static String getRef(Scanner Keyboard)
{
Scanner keyboard = new Scanner(System.in);
String ref= "";
boolean valid = false;
int errors = 0;
boolean problem = false;
while(valid==false)
{
System.out.println("Please enter a reference number which is two letters followed by three digits and a letter(B for business accounts and N for non business accounts)");
ref = keyboard.nextLine();
for (int i=0; i<6; i++)
{
if (ref.charAt(i)=='\0')
{
problem = true;
}
}
if(problem == true)
{
System.out.println("The reference must consist of 6 Characters");
}
else
{
if ((Character.isDigit(ref.charAt(0))== true) || (Character.isDigit(ref.charAt(1))== true))
{
System.out.println("The first 2 characters must be letters");
errors = errors + 1;
}
if ((Character.isDigit(ref.charAt(2))== false) || (Character.isDigit(ref.charAt(3))== false)||(Character.isDigit(ref.charAt(4))== false))
{
System.out.println("The 3rd,4th and 5th characters must be numbers");
errors = errors + 1;
}
if ((!ref.toUpperCase().endsWith("B"))&&(!ref.toUpperCase().endsWith("N")))
{
System.out.println("The 6th character must be either B(for business accounts) or N(for non business accounts) ");
errors = errors + 1;
}
if (errors==0)
{
valid=true;
}
}
}
return ref;
}
What I want is to be able to output an error message if the string does not contain a character at a certain index e.g. ref.charAt(0).
This will help (example):
if(ref.charAt(aNumber)==null) {
// display error message
}
Your problem is here:
ref.charAt(i)=='\0'
What happens if ref is a zero length string? In that case, trying to access the character at index 0 (where the first character would normally be) will give you your index out of range: 0 error. Make sure you test the string length first:
if (ref != null && !ref.isEmpty() &&ref.charAt(i)=='\0') { .. }
Adding a length() check
ref is empty (that is "") when you don't enter anything. So you can't get the character at 0 (or 1, 2, 3 ...). You can add an if check on the length, something like
if (ref.length() > 5) {
for (int i = 0; i < 6; i++) {
if (ref.charAt(i) == '\0') {
problem = true;
}
}
} else {
System.out.println("Please enter at least 6 characters");
}
Regular Expression
It might be simpler to compile a (reusable) Pattern with a regular expression to validate your reference criteria (2 letters, followed by 3 digits, followed b or n). Something like,
String ref; // <-- get input
Pattern p = Pattern.compile("([a-zA-Z]{2})(\\d{3})([B|N|b|n])");
Matcher m = p.matcher(ref);
if (m.matches()) { // <-- valid = m.matches();
System.out.println("ref is valid");
} else {
System.out.println("ref is not valid");
}
I was having problem with the output: it always puts an extra star at the end when there isn't suppose to be. Sample:
m*i*c*h*a*e*l*
When it is suppose to not have an asterisk after l or the last character. Can anyone help me figure this out? Here is my code so far:
import java.util.Scanner;
public class CoolSet2Problem3
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your first name in all lowercase: ");
String name = keyboard.next();
int n = 0;
String star = "*";
while (n < name.length())
{
System.out.print(name.charAt(n) + star);
n++;
}
}
}
My teacher told me that we might have to do something with ASCII character sets, which I have no idea about.
Well when you print the last character you are adding a star at the end of it... Thats why there is one being added at the end.
Try this:
while (n < name.length() - 1)
{
System.out.print(name.charAt(n) + star);
n++;
}
System.out.print(name.charAt(n));
There are a number of approaches. One simple one is to check a boundary condition to see if the star should be printed, e.g.
while (n < name.length())
{
if (n != 0) System.out.print(star);
System.out.print(name.charAt(n));
n++;
}
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();