Displaying number of times a character is in a string - java

I need to print the amount of times an input character appears in the string. It runs and works for all tests, however when a character appears only 1 time it prints "1 times" instead of "1 time" like expected, and i am unsure of how to add this into my code. It has to be when count is equal to 1 the outprint changes from times to time. I am lost.
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
Expected to

You should add a condition for the same instead of printing the static string "times" as below:
for( i = 0; i < input.length(); i ++){
if (input.charAt(i) == letter)
{
count = count + 1;
}
}
String str = (count==1)?"time":"times";
System.out.println("The letter '" + letter + "' appears " + count + str + " in the string " + "\"" + input + ".\"");

Maybe try something like this
String plural = (count == 1) ? "" : "s";
System.out.println("The letter '" + letter + "' appears " + count + " time" + plural + "in the string " + "\"" + input + ".\"");

I would use an if statement to determine how many times this specific letter appears in your string. Also, since first character is charAt(0), the last character should be charAt(s.length()-1);.
for( i = 0; i < (input.length()-1); i ++){
if (input.charAt(i) == letter)
count = count + 1;
} //end of your for loop
if (count == 1){
System.out.println("The letter '" + letter +
"' appears " + count + " time in the string " + "\"" + input + ".\"");
}
else{
System.out.println("The letter '" + letter + "' appears " + count + " times in the string " + "\"" + input + ".\"");
}

Related

There is an error of exception in thread "main" and i need to have a message entered

I don't see the issue or how to input the message. The full error that I keep getting is below. I can't see any problems with the code and I can't find a way to a message into the code.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of ran
ge: 30
at java.base/java.lang.StringLatin1.charAt (String.java:47)
at java.base/java.lang.String.charAt (String.java:693
at Main.main (Main.java:15)
import java.util.Scanner;
public class Main
{
public static void main( String[] args )
{
Scanner kb = new Scanner(System.in);
System.out.println("What is your message? ");
String message ="" + "\n";
System.out.println("\nYour message is " + " characters long.");
System.out.println("The first character is at position 0 and is '" + "'.");
int lastpos = 30;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for ( int i=0; i<message.length(); i++ )
{
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for ( int i=0; i<message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' );
{
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}
You never actually capture a message from the scanner - something like this:
message = kb.nextLine();
In addition, if you're trying to get the last index/position of the message, you'd want to do something like this:
int lastpos = message.length();
OR
int lastpos = message.length()-1;
The difference between the two being that the first gives you the size of the string, and the second gives you the last index of the string (for example, "abcdefg", lastpos 1 would be 7, and lastpos 2 would be 6).
Finally, keep in mind, you can do something like
message.charAt(0);
to get the first index character of the string.
I have made 3 changes from the code that you have written. They are the following:
Read the message using kb.nextLine(); instead of "" + "\n";
The first character of the message is message.charAt(0) instead of "'."
To count the number of characters, you have given semicolon after the if condition. Remove that. The semicolon after if is not needed.
Check the snippet below for better understanding.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("What is your message? ");
String message = kb.nextLine();
System.out.println("\nYour message is " + " characters long.");
System.out.println("The first character is at position 0 and is '" + message.charAt(0));
int lastpos = 30;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for (int i = 0; i < message.length(); i++) {
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for (int i = 0; i < message.length(); i++) {
char letter = message.charAt(i);
if (letter == 'a' || letter == 'A') {
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}

swap both user input and database to lowercase before comparing

I am trying to find a way to "collect all the classes from a selected date to another, managed by a specific teacher", and so far, its going okay. I have used to uppercase to match with a capital letter as the first one in the name... but since some teachers (McGonnagal) for example is having capital letters in her lastname, is there a way to, say , get the input to lowercase, and also transfer the data in the database (McGonnagal) all to lowercase?
So it would always be a match even if the user inserted McGoNNaGal in the program.... anyone got any ideas?`
try {
String lararesNamn = txtLoCLarare.getText();
String LFN = lararesNamn.toUpperCase().charAt(0)+lararesNamn.substring(1);
String datumFrom = txtLoCfom.getText();
String datumTom = txtLoCtom.getText();
String lararesEN = txtLarareEN.getText();
String LEN = lararesEN.toUpperCase().charAt(0)+lararesEN.substring(1);
ArrayList<HashMap<String,String>> listOfClasses = databas.fetchRows("SELECT KURSNAMN FROM KURS JOIN LARARE ON KURSLARARE = LARAR_ID WHERE KURSSTART >= " + "'" + datumFrom + "'" + " AND KURSSLUT <= " + "'" + datumTom + "'" + " AND(LARARE.FORNAMN = " + "'" + LFN + "'" + " AND LARARE.EFTERNAMN = " + "'" + LEN + "'" + ")");
System.out.println(listOfClasses);
JOptionPane.showMessageDialog(null, listOfClasses);
} catch(InfException ex){
System.out.println(ex.getMessage());
}
Best regards!
You can convert the fetched name from SQL DB to lower or upper case. For LOWER case modify your query to.
SELECT KURSNAMN FROM KURS JOIN LARARE ON KURSLARARE = LARAR_ID WHERE KURSSTART >= " + "'" + datumFrom + "'" + " AND KURSSLUT <= " + "'" + datumTom + "'" + " AND(LOWER(LARARE.FORNAMN) = " + "'" + LFN + "'" + " AND LOWER(LARARE.EFTERNAMN) = " + "'" + LEN + "'" + ")"
You can use UPPER function for upper case

java StringIndexOutOfBoundsException: String index out of range: 0

Its a very simple function. I don't know why it is giving an StringIndexOutOfBoundsException for the function source.charAt(i). I have checked the values of 'i' are not exceeding the length of the string which will be always 9.
public static String getClockResetString(String source, String target, Hashtable order)
{
String temp = "",name;
for(int i = 0; i < source.length(); i++){
name = (String)order.get(""+i);
if(source.charAt(i) != target.charAt(i))
{
if((int)source.charAt(i) < (int)target.charAt(i)){
temp = "h" + name + "=" + "dp" + name + "0" + " do " + "{h" + name + "'=0, k'=k+1} ";
}
else{
temp = "h" + name + "=" + "dn" + name + "1" + " do " + "{h" + name + "'=0, k'=k+1} ";
}
}
}
return temp;
}
I bet that you are exceeding the bounds on target, not source
if(source.charAt(i) != target.charAt(i))
You need to check that
i < target.length()

how to find a letter in a string and how to return two strings in alphabetical order? java [duplicate]

This question already has answers here:
Comparing strings by their alphabetical order
(10 answers)
Closed 8 years ago.
How can I print which word comes first (alphabetically) when I prompts the user to write two words? and how to check if a certain character exist in that scanned words?
For ex: if the user wrote "Word" and "Apple" how can I print these two words in alphabetical order. Also, I wrote a program to check if char 'z' appears on either words or not, but I don't know what's wrong about it? Here is my program:
import java.util.*;
public class Pr7{
public static void main(String[] args){
//print two words and read them..
Scanner scan = new Scanner (System.in);
String Word1;
String Word2;
System.out.println();
System.out.print("* Please write one word: ");
Word1 = scan.nextLine();
System.out.print("* Please write one word: ");
Word2 = scan.nextLine();
//Prints which word has more characters in it..
if (Word1.length() > Word2.length())
System.out.println("- " + "(" + Word1 + ")" + " has more characters.");
else if (Word2.length() > Word1.length())
System.out.println("- " + "(" + Word2 + ")" + " has more characters.");
else
System.out.println("- " + "(" + Word1 + ")" + " has equal characters with " + "(" + Word2 + ")");
//Prints which word comes first (alphabetically)..
/*
char ch;
int compare = Word1.compareTO(Word2);
*/
//Prints whether the letter 'z' appears in either word..
if (Word1.indexOf('z') == true)
System.out.print("- Letter 'z' appears in the first word.");
else if (Word2.indexOf('z') == )
System.out.print("- Letter 'z' appears in the second word.");
else
System.out.print("- Letter 'z' doesn't appears in either word.");
System.out.println();
//Prompts the user for a sentence and reads it..
String Str1;
String Str2;
System.out.println();
System.out.print("* Please write a string: ");
Str1 = scan.nextLine();
System.out.print("* Please write a string: ");
Str2 = scan.nextLine();
//Prints how many characters are in the first sentence and the second sentence..
if (Str1.length() > Str2.length()){
System.out.println("- " + "(" + Str1 + ")" + " has more characters.");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
else if (Str2.length() > Str1.length()){
System.out.println("- " + "(" + Str2 + ")" + " has more characters.");
System.out.print("- " + "(" + Str2 + ")" + " = " + Str2.length() + " Character(s)" + " && " + "(" + Word1 + ")" + " = " + Word1.length() + " Character(s)");
}
else{
System.out.println("- " + "(" + Str1 + ")" + " has equal characters with " + "(" + Str2 + ")");
System.out.print("- " + "(" + Str1 + ")" + " = " + Str1.length() + " Character(s)" + " && " + "(" + Word2 + ")" + " = " + Word2.length() + " Character(s)");
}
System.out.println();
}//main
}//Pr7
I know the methods I need to call, but I don't know how to use it.
To sort a list of strings in alphabetical order, you can do the following:
List<String> lst = new ArrayList<>();
lst.add("asd");
lst.add("ffsd");
Collections.sort(lst, new Comparator<String>() {
#Override
public int compare(String foo, String bar) {
return String.CASE_INSENSITIVE_ORDER.compare(foo, bar);
}
});
// will print the first of the sorted strings
System.out.println(lst.get(0));

Infinitely Looping if statement

First: I keep running into an infinite loop in the following code. The code is built so that you enter 8 numbers between 1 and 10. It proofs that these numbers are between 1 and 10. Then the second proof is that these 8 numbers added together equal 60. I'm having trouble with the end if else statement. If the total of the numbers is 60 it works fine and gives the print out but if it gets stopped at the if statement it infinitely prints the "You've entered the wrong total number" printout as well as an ever increasing total number of points. Am I missing something easy like a parenthesis or something?
Secondly: How can I loop back to the original entering of values if the total is not 60 and start the whole process over?
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
while (jamesTotalQuarter != 60){
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
}
}
}
Let me know if the following code solves your problem. Have not tested it, but it should just work fine now. Get the logic and fix it yourself incase of errors.
public static void lebronJames() {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
While(true){ // keeps it in a loop forever and only a "break" statement can stop it
//Declare an array to hold 8 intgers values
int lebronJamesAttributes[] = new int[8];
int attribute = 0;
System.out.println("Please allocate your attribute points for Lebron James in the following order. Your point allocations per attribute should be between 1 and 10. You have a total of 60 points to allocate");
System.out.println("-----------------");
System.out.println("Close Range" + "\n" + "Mid Range" + "\n" + "Three Point" + "\n" + "Free Throw" + "\n" + "Offensive Rebound" + "\n" + "Defensive Rebound" + "\n" + "Assist" + "\n" + "Steal" + "\n");
while (attribute <= 7) {
int attributeValue = input.nextInt();
if (attributeValue >= 1 && attributeValue <= 10 ) {
lebronJamesAttributes[attribute] = attributeValue;
attribute++;
}
else {
System.out.println("The attribute value you have selected is out of range. Select again.");
}
}
int jamesTotalQuarter = 0;
for (int jamesTotalQ1 : lebronJamesAttributes){
jamesTotalQuarter += jamesTotalQ1;
}
if (jamesTotalQuarter != 60) {
System.out.println("You have entered the wrong total number of attribute points. Please enter a total of 60 attribute points between the 8 characteristics.");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");
continue; // loop execution starts from the beginning and your program gets fresh inputs.
}
else {
System.out.println("Close Range" + lebronJamesAttributes[0] + "\n" + "Mid Range" + lebronJamesAttributes[1] + "\n" + "Three Point" + lebronJamesAttributes[2] + "\n" + "Free Throw" + lebronJamesAttributes[3] + "\n" + "Offensive Rebound" + lebronJamesAttributes[4] + "\n" + "Defensive Rebound" + lebronJamesAttributes[5] + "\n" + "Assist" + lebronJamesAttributes[6] + "\n" + "Steal" + lebronJamesAttributes[7] + "\n");
System.out.println("You have allocated a total of " + jamesTotalQuarter + " points.");}
break; // breaks from the loop on correct input
}
}
}

Categories