public class Main {
public static void main(String[] args) {
char c = '1';
//Implicitly cast to int type, double type
int i = c;
double d = c;
System.out.println(c + "To int type →" + i);
System.out.println(c + "To double type →" + d);
//Pass char type as an argument to a method whose argument is double type
doubleMethod(c);
}
static void doubleMethod(double d) {
System.out.println("double type →" + d);
}
}
Cast 1 to int type → 49
Cast 1 to double type → 49.0
double type → 49.0
Create a program that calculates the sum of each digit of a given number. Input Multiple datasets are given as input. Each dataset is given in one line containing one integer x. x is an integer of 1000 digits or less. When x is 0, the input ends. Do not output to this dataset. Output For each data set, output the sum of each digit of x on one line.
ans + = line.charAt (i)-‘0’;
in this exampleline.charAt (i)
returns charans
is an integer, so convert it to an integerimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int ans;
while(true){
String line = br.readLine();
if(line.length() == 1 && line.equals("0")){
break;
}else{
ans= 0;
for(int i = 0; i < line.length(); i++){
ans += line.charAt(i)-'0';
/*Confirmation of type cast
System.out.println("line.charAt(i) "+line.charAt(i));
System.out.println("line[i] "+(int)line.charAt(i));
System.out.println("(int)'0' "+(int)'0');
*/
}
System.out.println(ans);
}
}
}
}
Recommended Posts