java7 it,Java7的条件语句

在 HackerRank 的编程练习中,遇到使用 Java Scanner 类的 skip 方法时遇到了问题。原始代码在处理条件判断时混淆了逻辑运算符,导致结果不正确。修正后的代码应检查数字是否为奇数,并根据给定范围判断是否为 'Weird' 或 'NotWeird'。主要关注条件是数字的奇偶性和其所在范围。
摘要由CSDN通过智能技术生成

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!

Task

Given an integer, perform the following conditional actions:

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.

Input Format

A single line containing a positive integer,n.

Constraints

Output Format

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();

}

}

Please what am i doing wrong.

解决方案

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

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

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";

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值