import java.util.Scanner; public class Cal{ public static void main(String[] args){ Scanner sc = new Scanner(System.in);//键盘输入 int x = sc.nextInt();//输入整数 int y; if(x<1) y = x; else if(x<10) y = 3*x - 2; else y = 4*x; System.out.println(x); } }
给你一个更完善点的,楼上有三个问题(也不算是问题吧,只是我更严谨一些) 1、要求输出的是y的值,他输出的是x的值,这里是错误的 2、没有对输入进行提示,也没有错误处理(如果输入不是整数,程序直接炸了,我这里做了提示,同时不是整数会处理异常) 3、最后是if else,无论是否后面只有一句话,都要打上{}符号,这样符合编码规范,同时方便阅读 public static void main(String[] args) { Scanner sc = new Scanner(System.in);//键盘输入 System.out.print("请输入整数:"); int x = 0; try { x = sc.nextInt();//输入整数 } catch (Exception e) { System.out.println("您输入的不是整数"); return;//结束程序 } int y; if(x<1){ y = x; } else if(x<10) { y = 3*x - 2; }else { y = 4*x; } System.out.println("y的值:"+y); }
if else
62,614
社区成员
307,327
社区内容
加载中
试试用AI创作助手写篇文章吧