第一张是问题
第二张是我自己敲的 但是还是输出有问题
等待大神解答!
同学首先我说下你的问题哈,你的思路我懂的,你想利用字符串,前两个字符看是否等于第三个字符对吧。
但是字符相加这里是不行的因为'1'+'2'是不等于'3'的,它会转成Ascall码相加,你应该有学过。
那么如果按你的做法要怎么改呢
1、字符先转字符串 2、字符串再转为int 相加了,我给你修改了一下
import java.util.Scanner;
public class AddRemoveCells {
//个位+十位=百位
public static boolean num(String str){
boolean flag = false;
//字符转字符串
String num1 = String.valueOf(str.charAt(0)); //个位
String num2 = String.valueOf(str.charAt(1)); //十位
String num3 = String.valueOf(str.charAt(2)); //百位
//字符串转数字
int num11 = Integer.parseInt(num1);
int num22 = Integer.parseInt(num2);
int num33 = Integer.parseInt(num3);
if (num11 + num22 == num33){
flag = true;
}
return flag;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
if (num(str)==true){
System.out.println("yes");
}else {
System.out.println("no");
}
}
}
取模,分别取出百位,十位及个位再判断,代码如下:
import java.util.Scanner;
public class 个位加十位是否百位 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (calc(num))
System.out.println("yes");
else
System.out.println("NO");
}
public static boolean calc(int num) {
int a = num / 100; // 百位
int b = num / 10 % 10; // 十位
int c = num % 10; // 个位
if (b + c == a)
return true;
else
return false;
}
}
单个数字字符转成数值型最省力的方法是减掉ascii码的0
一般是用数字取模来算这种题,按你的思路,应该改成这样:
if( (str.charAt(1)-'0')+(str.charAt(2)-'0') == (str.charAt(0)-'0')){
flag = true;
}
楼主,楼上贴的思路都是很好的,我只补充吧。1.写代码,除了注释,类名,变量名,路径等不要出现中文! 2.另外输入的字符可以加两个判定,字符是否都是数字,字符是否满足是3位数
public static void main(String[] args) {
String num = "541";
Integer b = Integer.parseInt(num.substring(0,1));
Integer s = Integer.parseInt(num.substring(1,2));
Integer g = Integer.parseInt(num.substring(2,3));
if(b==(s+g)){
System.out.println("yes");
}else{
System.out.println("no");
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!