I'm new to Java. I've been writing code to find the binary equivalent of an integer in Java using a while loop. I've written the following code and it's not throwing any error, but it was not printing INVALID INPUT. It is printing the valid binary number of a given integer value. Can anyone suggest where and what I'm doing wrong? And how should I get the proper input?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if ((n >= 0) && n > 999) {
System.out.println("Invalid Input");
} else {
while (n > 1) {
if (n <= 999) {
System.out.println(Integer.toBinaryString(n));
break;
}
}
}
}
}
Change && to ||:
if (!(n >= 0) || n > 999) {
Or even better, express conditions without negation:
if (n < 0 || n > 999) {
Positive conditions, ie "a is b", are easier to read.
Why are you using a loop at all? You're just adding needless complexity. Your code can be re-written to this:
if (n >= 0 && n < 1000) {
System.out.println(Integer.toBinaryString(n));
return;
}
System.out.println("Invalid Input");
You haven't said if this is an assignment but typically it is done like this for such questions.
loop until value is 0
get remainder from division by 2.
prepend to string
divide n by 2 to expose next binary digit.
// get some input,
int n = 1249;
String s = "";
while(n != 0) {
s = (n%2) + s;
n/=2;
}
System.out.println(s);
prints
10011100001
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
The code I say has to complete these assignments:
Given an integer,N, 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.
My code looked like this:
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
scanner.close();
int Numberparorimpa = N % 2;
if(N < 2 || Numberparorimpa ==1 || N <=20 && N >=6 ){
System.out.println("Weird");
}else{
if(N >=2 && Numberparorimpa == 0){
System.out.println("Not Weird");
}else{
if(Numberparorimpa == 0 && N >=6 || N<=20){
System.out.println("Weird");
}else{
if(Numberparorimpa== 0 && N> 20){
System.out.println("Not Weird");
}else{
return;
}
}
}
}
}
}
How can I reduce the IFs of this code?
I think an optimize version could be this :
if (N % 2 == 1 || (N >= 6 && N <= 20)) {
System.out.println("Weird");
}
else {
System.out.println("Not Weird");
}
If N is odd or N in range of 6 to 20 it's weird.
Else N is either even or not in the range so it's not weird.
You can reduce the complexity and improve the readability of your code by extracting your logic to method/class etc. Also, nested conditions are hard to read, you should avoid it.
Example:
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
scanner.close();
String print = isGivenNumberWeird(n) ? "Weird" : "Not Weird"
System.out.println(print);
}
private static boolean isGivenNumberWeird(int n) {
boolean isOdd = n % 2 == 1;
if (isOdd) {
return true;
}
if (n >= 2 && n <=5) {
return false;
}
if (n >= 6 && n <=20) {
return true;
}
if (n > 20) {
return false;
}
}
Sometimes, the normal if-else isn't enough. In such cases, we have what we call ladder if and else conditions. So here we'll learn to use them.
Given a positive integer N. Your task is to check if it divisible as given below:
If it is divisible by 2, print "Two".
If it is divisible by 3, print "Three".
If it is divisible by 11, print "Eleven".
If not follow above three rules, print "-1".
Note: If N is divisible by more than one of the above given numbers, print the one which is largest.
Input Format:
First line of input contains number of testcases T. For each testcases, there will be a single line containing N.
Output Format:
For each testcase, check divisibility and print statements accordingly as given in above steps (without quotes).
Your Task:
Your task is to complete the function to check divisibility as required.
Constraints:
1 <= T <= 10
1 <= N <= 106
Example:
Input:
2
3
11
Output:
Three
Eleven
** For More Input/Output Examples Use 'Expected Output' option **
class Geeks {
static void isDivisibleByPrime (int n)
{
//Your code here
Scanner sc=new Scanner(System.in);
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
if(a[i]%2==0)
System.out.println("Two");
else if(a[i]%3==0)
System.out.println("Three");
else if(a[i]%11==0)
System.out.println("Eleven");
else
System.out.println("-1");
}
}
}
First use braces around every block of code. it is easier to reading for everyone.
Second the point in your spec was to print the largest value if divisible, so you
should start with checking if it divides by 11 first, then 3 and then 2.
Right code is here:
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
System.out.println();
}
First things first - always use braces around every block of code - especially a beginner to the language. It will make your life easier, and anyone reading your code.
Second, the point in your spec was to print the largest value if divisible, so you should start with checking if it divides by 11 first, then 3 and then 2.
And lastly, I would get all the input first, and not in the isDivisibleByPrime method, and just call that method for each input.
So just leave your isDivisibleByPrime as
static void isDivisibleByPrime(int n) {
if (n % 11 == 0) {
System.out.println("Eleven");
} else if (n % 3 == 0) {
System.out.println("Three");
} else if (n % 2 == 0) {
System.out.println("Two");
} else {
System.out.println("-1");
}
}
And call it elsewhere with the values
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of test cases:");
int numOfTestCases = sc.nextInt();
for (int i = 0; i < numOfTestCases; i++) {
System.out.println("Enter value to check:");
int valueToCheck = sc.nextInt();
isDivisibleByPrime(valueToCheck);
}
Obviously there's no error handling or whatnot, but as you're likely new to this, I'm sure it's not a requirement.
Here's an online example.
I'm doing a hackernet challenge where n is an int input. The conditions are:
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.
Im sure the code makes logic and dont think theres syntax. It gives the correct responses and hackernet still says its incorrect so ive come here to see if anyone can see what the problem is
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
System.out.print("not weird");
}
}
The problem is the logic in your else condition, which would also catch values of N which are less than 2. Try this version:
if (N % 2 != 0)
{
System.out.print("weird");
}
else if (N >= 2 && N <= 5 || N > 20)
{
System.out.print("not weird");
}
else if (N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
// NOTE: if the code still fails, remove this else condition
System.out.print("unexpected value of N");
}
Note: To get your code to pass the Hackernet task, you might have to completely remove the else condition. I added it for completeness, but Hackernet might test N=1 to see if nothing gets printed.
Read this condition :
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
as
if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20))
Then see how operator precedence changes the behaviour and yield desired results.
Check the following one
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N%2!=0) {
System.out.print("weird");
}else if(N>=2 && N<=5) {
System.out.print("not weird");
}else if(N>=6 && N<=20) {
System.out.print("weird");
}else if(N>20) {
System.out.print("not weird");
}
}
For the technical part: start by reading about
precedence of java operators and then make your code easier to read.
Pushing that many conditions into a single if is not helpful. You see it yourself: you think the code is correct, but probably it isn't. And now you look to other people to explain your overly complex code back to you. And of course, all the other answers do all that for you ... but beyond that:
The "real" answer here is: learn how to test your code.
Instead of having a main that somehow asks for a number, and then makes decisions, write a method boolean isWeird() that takes a number and returns true/false according to your requirements.
And then simply test that method with all reasonable cases. And then check if that result is as expected.
Using JUnit, you could write something like
assertThat(isWeird(1), true);
assertThat(isWeird(21), true);
assertThat(isWeird(22), true);
...
Ideally, you write such tests before you implement that method. And then you implement all the conditions, and any check that fails tells you that you got something wrong.
I feel, In the if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20) condition, you are verifiying the odd and even values at same time using && and || operator. Can you modify the condition into like this if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20)) and check? If N is odd weird will be printed or if N is even and it falls under the 6 and 20 inclusive, weird will be printed.
You already have a good few answers here but if you think logically about what you actually need, you can break it down easier.
It looks like the only "Not Weird" print out is 2, 4 and even numbers > 20
So an example could be something like:
if (n % 2 == 0) {
if ((n >= 2 && n <= 5) || (n > 20)) {
return "Not Weird";
}
}
return "Weird";
You can try this
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (n % 2 == 1 || (n >= 6 && n <= 20)) {
System.out.println("Weird");
} else {
System.out.println("Not Weird");
}
scanner.close();
}
I am relatively new to Java and this would be my first post on this site.I have used it many times before, but this time I haven't found an answer to my problem so here I am..
This code works great in my IDE (JDeveloper) but for some reason, when I run it in CMD it hangs for certain parameters (ex. 7844578642 2;7844578642 16 - the two sets work in IDE but not CMD).
Any ideas what am I doing wrong?
class PR13_19 {
public static void main(String args[]) {
long N = 0;
int base = 0,pow = 1;
String result = "";
if(args.length != 2){
System.out.println("Please enter Number and base...");
return;
}
try{
N = Long.parseLong(args[0]);
base = Integer.parseInt(args[1]);
if(!(base >= 2 && base <= 16)) throw new NumberFormatException();
}catch(NumberFormatException | StringIndexOutOfBoundsException exc){
System.out.println("Invalid Input");
return;
}
//converts number N in base 10 to any base "base"
// if base >10 11=A,12=B,13=C....(ex.hexadecimal)
while(pow <= N/base)
pow *= base; //greatest power of "base" >= N
while(pow > 0){
if(N >= pow) {
if(N/pow > 9) result += (char)((N/pow) + 55);
else result += (N/pow);
N -= (N - (N % pow));
}
else result += "0";
pow /=base;
}
System.out.println(result);
}
}
You must enter a number defined in javas LONG scope or change the code.
You can also add try/catch clause to see which error occurs.
This is my code snippet:
import java.util.Scanner;
public class Numrs {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int pos, i = 1;
char d;
while (num <= 10) {
String line = in.nextLine();
pos = line.length();
if (line.length() <= 1000000) {
if (line.charAt(i) == 'R') {
line.replace('R', 'K');
i++;
}
if (line.charAt(i) == 'K') {
line.replace('K', 'R');
i++;
}
num++;
}
}
}
It's showing a StringIndexOutOfBoundsException when I enter a single digit number like 3, and even if a 2 digit number is entered, it's getting terminated without reading the string. Please help.
Well, if you enter only one character /digit, then size will be 1 but it will be placed in index 0. and you are trying to do line.charAt(i) where i=1
There are many problems in this approach.
1. The input you need to pass is more than a digit, like 3 this works because after the 3 your in expects some string.
you are not updating num. So it will end up in an infinite loop
This won't work if you give any value more than 10. I m not sure what you wanted to achieve.
Start i from 0, Developers start with 0 :)