鱼C论坛

 找回密码
 立即注册
查看: 4225|回复: 5

关于JAVA的一道题

[复制链接]
发表于 2015-3-11 19:22:48 | 显示全部楼层 |阅读模式
20鱼币
编写求素数的函数,要求用封装的思想,将输入,合法性检测,判断素数分别封装成1个函数(getInput(),isValid(),isPrime())

最佳答案

查看完整内容

import java.util.Scanner; public class Test { public static void main(String[] args) { String n = getInput(); if (!isValid(n)) { System.out.println("输入不合法"); return; } if (isPrime(Integer.parseInt(n))) { System.out.println("yes"); }else { System.out.println("no"); } } public static String getInput(){ System.out.println("请输入一个自然 ...
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-3-11 19:22:49 | 显示全部楼层
本帖最后由 百日维新 于 2015-3-16 17:32 编辑

import java.util.Scanner;

public class Test {

        public static void main(String[] args) {
                String n = getInput();
                if (!isValid(n)) {
                        System.out.println("输入不合法");
                        return;
                }
               
                if (isPrime(Integer.parseInt(n))) {
                        System.out.println("yes");
                }else {
                        System.out.println("no");
                }
               
        }
        public  static String getInput(){
                System.out.println("请输入一个自然数:");
                Scanner in = new Scanner(System.in);
                String str = in.nextLine();

                return str;
               
        }
       
        public static boolean   isValid(String str){
                try {
                        if(Integer.parseInt(str) >= 0){
                                return true;
                        }else {
                                return false;
                        }
                } catch (Exception e) {
                        return false;
                }

               
        }
       
        public static boolean isPrime(int n){
                  for (int i = 2; i < Math.sqrt(n); i++) {
                           if (n % i == 0)
                            return false;
                          }
                          return true;
                         }

}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-3-15 14:31:17 From FishC Mobile | 显示全部楼层
晚上帮你看
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-3-15 14:31:18 From FishC Mobile | 显示全部楼层
晚上帮你看
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2015-3-15 22:54:49 | 显示全部楼层

大神看完了没。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-3-15 23:00:34 | 显示全部楼层
liwenhao96 发表于 2015-3-15 22:54
大神看完了没。。。

ok 了!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 21:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表