程序我运行了,基本正确(只是要对2特殊处理,因为2是质数)
另外,程序书写应该规范一些:
public class Zhi {
public static void main(String[] args) {
int i = 2, j = 2, b = 1;
System.out.println("输入一个数字,我帮你判断是不是质数");
try {
i=System.in.read();
} catch (Exception e) {
System.out.println("Cannot read:"+i);
}
for (j = 2; j < (i / 2); j++) {
if ((i % j) == 0) {
b = 2;
break;
}
}
if (b == 1) {
System.out.println("恭喜了,你输入的是质数");
} else {
System.out.println("不是质数,能被"+j+"整除");
}
}
}java和c++的循环控制应该一样,都和c一样
另外,程序书写应该规范一些:
public class Zhi {
public static void main(String[] args) {
int i = 2, j = 2, b = 1;
System.out.println("输入一个数字,我帮你判断是不是质数");
try {
i=System.in.read();
} catch (Exception e) {
System.out.println("Cannot read:"+i);
}
for (j = 2; j < (i / 2); j++) {
if ((i % j) == 0) {
b = 2;
break;
}
}
if (b == 1) {
System.out.println("恭喜了,你输入的是质数");
} else {
System.out.println("不是质数,能被"+j+"整除");
}
}
}java和c++的循环控制应该一样,都和c一样
解决方案 »
- 【Debug调试】为什么在创建对象的语句上调试就出错
- java异常处理机制和抽象方法的重写或者接口方法的实现问题
- 求最新的TestKing或者TestKiller (SCJP 5.0)
- [Fatal Error] :-1:-1: Premature end of file.!!!XML文件的读写
- 求课程设计题目
- Copy的一段代码,运行不出结果
- 请问如何在窗口关闭时如何向数据库插入数据?
- 诚恳询问关于Runtime().exec方面的问题,请高手一定进来详细指点,加急!!!
- Java 好书
- 98下如何用JDK进行编译,谢谢
- rmi问题 着急!!!!!!!
- java中如何实现拷屏粘贴功能!高分!!
public class Test {
public static void main(String[] args) {
int i = 2, j = 2, b = 1;
System.out.println("输入一个数字,我帮你判断是不是质数");
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
i = Integer.parseInt(in.readLine().trim());
} catch (Exception e) {
System.out.println("Cannot read:"+i);
}
for (j = 2; j < (i / 2); j++) {
if ((i % j) == 0) {
b = 2;
break;
}
}
if (b == 1) {
System.out.println("恭喜了,你输入的是质数");
} else {
System.out.println( i + "不是质数,能被"+j+"整除");
}
}
}
public class Zhi {
public static void main(String[] args) {
int i = 2, j = 2, b = 1;
System.out.println("输入一个数字,我帮你判断是不是质数");
try {
i=System.in.read();
} catch (Exception e) {
System.out.println("Cannot read:"+i);
}
for (j = 2; j < (i / 2); j++) {
if ((i % j) == 0) {
System.out.println("不是质数,能被"+j+"整除");
b = 2;//为什么这里不写break就不行了呢?
}
}
if (b == 1) {
System.out.println("恭喜了,你输入的是质数");
}
}
}
最可气的是我同样的思路在C++下就完成的很好,为什么到了JAVA下连个循环都不行了?天啊!~~~~~~~~~
for (j = 2; j < (i / 2); j++) {
if ((i % j) == 0) {
System.out.println("不是质数,能被"+j+"整除");
b = 2;
break;//加了break什么都跳出了!呵呵!
}
}
class zhi
{
public static void main(String arg[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i=0,j=2,b=1;
System.out.println("输入一个数字,我帮你判断是不是质数");
System.out.flush();
try
{
i=Integer.parseInt(br.readLine());
System.out.println(i);
}
catch(Exception e)
{
System.out.println("Cannot read");
}
for(j=2;j<(i/2);j++)
{
if((i%j)==0)
{ b=2;
System.out.println("不是质数,能被"+j+"整除");}
} if (b==1)
System.out.println("恭喜了,你输入的是质数");
} }