英文:
Count letter in a word from scanner, java
问题
System.out.println("Enter the word you want to search in:");
String str1 = sc.nextLine();
System.out.println("Enter the letter you want to count:");
String str2 = sc.nextLine();
int count = 0;
for(int i = 0; i < str1.length(); i++) {
if(Character.toUpperCase(str1.charAt(i)) == Character.toUpperCase(str2.charAt(0)))
count++;
}
System.out.println("Number of occurrences of the letter in your word: " + count);
英文:
My code is looking like this right now, it's counting the letters in the word but I would like my code to count every letter in the word so if I write banana
or nine
, the code will ask which letter to count, and if I choose "N", it will print 2 "N". Please help me out.
System.out.println("Ange ordet du vill leta i: ");
String str1 = sc.nextLine();
System.out.println("Ange bokstaven du vill leta efter: ");
String str2 = sc.nextLine();
int count = 0;
for(int i = 0; i < str2.length(); i++) {
if(str2.charAt(i) != ' ')
count++;
}
System.out.println("Antal bokstäver i ditt ord: " + count);
答案1
得分: 0
你起初不需要对每个字母进行计数。在获取要计数的字母后,你应该开始计数。但这取决于情况。我假设你需要获取特定字符串中字母的计数。
你可以将计数逻辑放在一个 while() 循环内,以便一遍又一遍地执行这个操作。
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入单词");
String s = scanner.next();
System.out.println("输入字母");
char a = scanner.next().charAt(0);
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == a){
count++;
}
}
System.out.println(count);
}
}
英文:
You don't need to count every letter at first. You should count after getting the letter to count. But depending on the scenario. I assume that you need to get the count of the letter in a particular string.
You can wrap counting logic inside a while() to do this over and over again.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter word");
String s = scanner.next();
System.out.println("enter letter");
char a = scanner.next().charAt(0);
int count = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == a){
count++;
}
}
System.out.println(count);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论