Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

java - Conditional Statement on Java7

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("(
|[

u2028u2029u0085])?");


        scanner.close();
    }
}

Please what am i doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Online Demo

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...