Java7的条件语句 [英] Conditional Statement on Java7

查看:210
本文介绍了Java7的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我刚刚开始对hackerrank进行编码练习,并且使用带有skip功能的扫描器类遇到了一些挑战.这是我尝试过的. 客观的 在这个挑战中,我们从条件语句开始.查看教程"选项卡以获取学习材料和教学视频!

Hello i just started a coding exercise on hackerrank and i am having a little challenge using scanner class with the skip function. here is what i have tried. Objective In this challenge, we're getting started with conditional statements. Check out the Tutorial tab for learning materials and an instructional video!

任务

给出一个整数,执行以下条件操作:

  • 如果n为奇数,则打印怪异
  • 如果n为偶数且在2到5的范围内,则打印Not Weird
  • 如果n为偶数且在6到20的范围内,则打印怪异
  • 如果n为偶数且大于20,则打印Not Weird
  • 完成编辑器中提供的存根代码以打印是否或 不是n很奇怪.
  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird
  • Complete the stub code provided in your editor to print whether or not n is weird.

输入格式

包含正整数n的单行.

A single line containing a positive integer,n.

约束

输出格式

如果数字很奇怪,请打印Weird;否则,请打印Not Weird.

Print Weird if the number is weird; otherwise, print Not Weird.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {


    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int N = scanner.nextInt();

        if (N % 2 == 0 && N >= 2 && N <= 5 && N > 20) {
            System.out.println("not weird");

        } else if (N % 2 == 0 && N >= 6 && N <= 20) {
            System.out.println("weird");
        } else {
            System.out.println("weird");
        }

        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");


        scanner.close();
    }
}

请问我在做错什么.

推荐答案

您正在混合&&||,因此您的第一个if将永远不会像注释中所述运行.

You're mixing up && and ||, so your first if will never run as mentioned in the comments.

因此,看起来唯一的"Not Weird"打印输出是24和偶数> 20.

So it looks like the only "Not Weird" print out is 2, 4 and even numbers > 20.

因此,您可以利用它来检查"Weird"输出,否则打印"Not Weird".

So use this to your advantage to just check for the "Weird" outputs, otherwise print "Not Weird".

if (n % 2 == 0) {
    if ((n >= 2 && n <= 5) || (n > 20)) {
        return "Not Weird";
    }
}
return "Weird";

在线演示

Online Demo

话虽如此,我不确定

Having said this, I'm not sure what you want with Scanner::skip

这篇关于Java7的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆