עזרה בשאלת JAVA
היי חברים,
אני מנסה לפתור את השאלה הבאה, אשמח אם מישהו יעזור לי. מצ"ב הקוד שכתבתי... (אפשר להתעלם משם המחלקה)
(Occurrences of each digit in a string) Write a method that counts the occurrences
of each digit in a string using the following header:
public static int[] count(String s)
The method counts how many times a digit appears in the string. The return value
is an array of ten elements, each of which holds the count for a digit. For example,
after executing int[] counts = count("12203AB3"), counts[0] is 1,
counts[1] is 1, counts[2] is 2, counts[3] is 2.
Write a test program that prompts the user to enter a string and displays the number
of occurrences of each digit in the string.
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string");
String str = input.next();
isLetterOrDigit(str); //check if digit or letter
}
//check if digit or letter
public static void isLetterOrDigit(String str)
{
String newStr = "";
for (int i = 0; i < str.length(); i++)
{
if (Character.isDigit(str.charAt(i)))
{
newStr += str.charAt(i);
}
}
count(newStr);
}
//check occurrences of digits
public static int[] count(String newStr)
{
int[] count = new int[10];
for (int i = 0; i < 10; i++)
{
for (int x = 0; x < newStr.length(); x++)
{
if (i == newStr.charAt(x))
{
count++;
}
}
System.out.println("The number " + i + " appears " + count + " times");
}
return count;
}
}
היי חברים,
אני מנסה לפתור את השאלה הבאה, אשמח אם מישהו יעזור לי. מצ"ב הקוד שכתבתי... (אפשר להתעלם משם המחלקה)
(Occurrences of each digit in a string) Write a method that counts the occurrences
of each digit in a string using the following header:
public static int[] count(String s)
The method counts how many times a digit appears in the string. The return value
is an array of ten elements, each of which holds the count for a digit. For example,
after executing int[] counts = count("12203AB3"), counts[0] is 1,
counts[1] is 1, counts[2] is 2, counts[3] is 2.
Write a test program that prompts the user to enter a string and displays the number
of occurrences of each digit in the string.
import java.util.Scanner;
public class Arrays
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string");
String str = input.next();
isLetterOrDigit(str); //check if digit or letter
}
//check if digit or letter
public static void isLetterOrDigit(String str)
{
String newStr = "";
for (int i = 0; i < str.length(); i++)
{
if (Character.isDigit(str.charAt(i)))
{
newStr += str.charAt(i);
}
}
count(newStr);
}
//check occurrences of digits
public static int[] count(String newStr)
{
int[] count = new int[10];
for (int i = 0; i < 10; i++)
{
for (int x = 0; x < newStr.length(); x++)
{
if (i == newStr.charAt(x))
{
count++;
}
}
System.out.println("The number " + i + " appears " + count + " times");
}
return count;
}
}