I have an assignment where I have to print each digit while using a for loop and I am very confused. I know that the code I have written is VERY wrong for many reasons, but I'm having a lot of trouble piecing together the various skills we have been learning. How can I fix my code so that 365 is printed as 3 6 5?
class Main {
method1(365);
public static void main(String[] args) {
}
String number = String.valueOf(num);
public int method1(int num) {
for (int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
System.out.print("digit: " + j);
}
}
}
You need to re-order your code in correct syntax and order to make it work correctly,
method1(365) inside the main methodmethod1(365) method static to be accessible as class method.charAtint j = Character.digit(number.charAt(i), 10); to convert the character to a digit by base of 10 or simpley use int j = Character.getNumericValue(number.charAt(i)); which will be default on base of 10.public static void main(String[] args) {
method1(365);
}
public static void method1(int num) {
String number = String.valueOf(num);
for (int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
// int j = Character.getNumericValue(number.charAt(i));
System.out.print("digit:" + j + " ");
}
}
Since Java 9 you can use codePoints method:
int number = 365;
String.valueOf(number)
// IntStream
.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// print in a column
.forEach(j -> System.out.println("digit: " + j));
Output:
digit: 3
digit: 6
digit: 5