I'm facing an issue with control structures - java

My problem is with output of my code. When I enter 20, the output must be weird, but I am getting not weird. Same with the value 18.
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}

the output must be weird,but i am getting not weird
Because, if(n%2 == 1) return false and fall to else block where
if(n <= 2 && n >= 5) is `false`
and
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else block. You probably change
if(n <= 2 && n >= 5)
to
if(n >= 2 && n <= 5)
and
else if(n <= 6 && n >= 20)
to
else if(n >= 6 && n <= 20)
Otherwise, they will never be true and always falls to else.

In your program last else is being executed. Change && (logical AND) to || (logical OR) which will check if number is less than something OR higher than something, instead of checking if something is less or equal 5 AND higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case.

I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}

Related

Issue with my if else statement in a do while loop

My do-while loop is supposed to print out numbers from 1 - 106 (including 1 and 106)
whats supposed to happen:
multiples of 3 are supposed to print out Big,
multiples of 5 are supposed to print out Mean,
multiples of 7 are supposed to print out Bugs,
multiples of 3 and 5 are supposed to print out BigMean,
multiples of 3 and 7 are supposed to print out BigBugs,
multiples of 5 and 7 are supposed to print out MeanBugs,
multiples of 3, 5 and 7 are supposed to print out BigMeanBugs.
What actually happens:
my do-while loop only runs the first "if" statement. Any help?
My code:
public static void main(String [] args){
int i = 0;
do{
++i;
if(i %3 == 0){
System.out.print("Big, ");
if(i %5 ==0){
System.out.print("Mean, ");
}
if(i %7 ==0){
System.out.print("Bugs, ");
}
if((i %3 == 0) && (i %5 == 0)){
System.out.print("BigMean, ");
}
if((i %3 == 0) && (i %7 == 0)){
System.out.print("BigBugs, ");
}
}else if((i %5 == 0) && (i %7 == 0)){
System.out.print("MeanBugs, ");
}else if((i %3 == 0) && (i %5 == 0) && (i %7 ==0)){
System.out.print("BigMeanBugs, ");
}else{
System.out.print(i + " ");
}
}while(i<=106);
}//closing main
As I could see your problem is probably that your if-statements are inside of first if-statement, so maybe you want this:
public class BigMeanBugsDoWhileLoop
{
public static void main(String [] args)
{
int i = 0;
do
{
++i;
boolean bug = false;
String result = "";
if(i %3 == 0)
{
result += "Big";
bug = true;
}
if(i %5 ==0)
{
result += "Mean";
bug = true;
}
if(i %7 ==0)
{
result += "Bugs";
bug = true;
}
if(!bug)
{
System.out.println(i + "");
}
else
{
System.out.println(result);
}
}while(i<106);
}//closing main
} // closing class
You don't need other if-statements because you don't use break so other expressions will be evaluated before next iteration.
First, if something is divisible by 3 and 7 it is divisible by 21.
Second, if you reverse the order, you will catch divisible by 3 and 5 before divisible by 3 or 5 separately (assuming that is what you want). If you do it the other way you may print the values prematurely or miss them altogether before checking the other possible factors. This behavior is also dependent on if vs if/else if statements.
I have limited the printout to 25 to avoid a long list. Modify as you see fit.
public class BigMeanBugsDoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
String bugType = "";
if (i % 105 == 0) {
bugType = "BigMeanBugs"; // 3 5 7
} else if (i % 35 == 0) {
bugType = "MeanBugs"; // 5 7
} else if (i % 21 == 0) {
bugType = "BigBugs"; // 3 7
} else if (i % 15 == 0) {
bugType = "BigMean"; // 3 5
} else if (i % 7 == 0) {
bugType = "Bugs"; // 7
} else if (i % 5 == 0) {
bugType = "Mean"; // 5
} else if (i % 3 == 0) {
bugType = "Big"; // 3
}
System.out.println(bugType.isEmpty() ? i : bugType);
i++;
} while (i <= 25);
}// closing main
} // closing class
Prints this.
1
2
Big
4
Mean
Big
Bugs
8
Big
Mean
11
Big
13
Bugs
BigMean
16
17
Big
19
Mean
BigBugs
22
23
Big
Mean
You have to increment the value of i in the end of loop
public static void main(String [] args){
int i = 1;
do{
if(i %3 == 0){
System.out.print("Big, ");
if(i %5 ==0){
System.out.print("Mean, ");
}
if(i %7 ==0){
System.out.print("Bugs, ");
}
if((i %3 == 0) && (i %5 == 0)){
System.out.print("BigMean, ");
}
if((i %3 == 0) && (i %7 == 0)){
System.out.print("BigBugs, ");
}
}else if((i %5 == 0) && (i %7 == 0)){
System.out.print("MeanBugs, ");
}else if((i %3 == 0) && (i %5 == 0) && (i %7 ==0)){
System.out.print("BigMeanBugs, ");
}else{
System.out.print(i + " ");
}
i++;
}while(i<=106);
}//closing main
} // closing class

why there is no output in java even after using system.out.println function?

class PrimeTernary {
public static void main(String[] args) {
int i, m;
int n = 8;
m = n / 2;
String result;
if (n == 0 || n == 1)
System.out.println("Not prime number");
else
for (i = 3; i <= m; i++) {
result = (n % i == 0) ? "not prime" : "prime";
System.out.println(result);
}
}
}
what is wrong in my code? Can anyone pleased to explain it in brief?
Even if n is 0 or 1 (only then your print statement could ever be reached), then m is necessarily 0. This means, the for loop does not run.
Your if condition is never true since n is always 8.
if (n == 0 || n == 1) is the same as if (8 == 0 || 8 == 1)
So your loop will never execute.

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("(\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";
Online Demo
Having said this, I'm not sure what you want with Scanner::skip
if (N % 2 == 0 && N >= 2 && N <= 5) {
System.out.println("Not Weird");
} else if (N % 2 == 0 && N > 20) {
System.out.println("Not Weird");
} else {
System.out.println("Weird");
}
This is how I simplified it.
if(N % 2 == 0 )
{
if((N >= 2 && N <= 5) || N > 20)
{
System.out.println("Not Weird");
}
else
{
System.out.println("Weird");
}
}
else
{
System.out.println("Weird");
}
See code below
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
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");
}
public class Solution {
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==0 && n>2 && n<5 || n>20) {
System.out.println("Not Weird");
} else if( n>6 || n<20) {
System.out.println("Weird");
} else {
System.out.println("Weird");
}
scanner.close();
}
}
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();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 == 0 && N >= 2 && N <= 5 ) {
System.out.println("Not Weird");
} else if (N % 2 == 0 && N >= 6 && N<=20) {
System.out.println("Weird");
} else if(N%2==0 && N>20) {
System.out.println("Not Weird");
}else {
System.out.println("Weird");
}
scanner.close();
}
}
package hudai;
import java.util.Scanner;
public class Hudai {
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();
if(N%2 == 1){
System.out.println("Weird");
}
if(N%2==0 && 2<N && N<5){
System.out.println("Not Weird");
}
if(N%2==0 && 6<N && N<=20){
System.out.println("Weird");
}
if(N%2==0 && 20<N && N<=100){
System.out.println("Not Weird");
}
}
}
if(N % 2 == 0){
if((N >=2 && N <= 5) || (N > 20)){
System.out.println("Not Weird");
}
else if(N >= 6 && N <= 20){
System.out.println("Weird");
}
}
else{
System.out.println("Weird");
}
import java.util.Scanner;
public class Main {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
if (n % 2 == 1) {
System.out.println("Weird");
}
if (n % 2 == 0 && 2 < n && n < 5) {
System.out.println("Not Weird");
}
if (n % 2 == 0 && 6 < n && n <= 20) {
System.out.println("Weird");
}
if (n % 2 == 0 && 20 < n && n <= 100) {
System.out.println("Not Weird");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
}
}
}
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) )
{
System.out.println("Not Weird");
}
else if(N % 2==0 && 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();
}
}
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 ) {
System.out.println("Not Weird");
}
else if(N % 2 == 0 && 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();
}
}
Using ternary operation,
String w="Weird";
String nw= "Not Weird";
String s= (N%2!=0)?w:(N%2==0 && (N>=2 && N<=5))?nw:(N%2==0 && (N>=6 && N<=20))?w:nw;
if(n % 2 == 0){
if (n >= 2 && n <= 5 || n > 20) {
System.out.println("Not Weird");
}
if (n >= 6 && n <= 20) {
System.out.println("Weird");
}
} else if(n % 2 != 0){
System.out.println("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();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N %2 == 0){
if((N>=2 && N<=5) || (N>20)){
System.out.println("Not Weird");
}
else if (N>=6 && N<=20){
System.out.println("Weird");
}
}
else {
System.out.println("Weird");
}
scanner.close();
}
}
Java 8 functional interface applied on Integer.
int n = 24;
Function<Integer, String> f = x -> x % 2 == 1 || (x >= 6 && x <= 20) ? "Weird" : "Not Weird";
System.out.println(f.apply(n));
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();
}

JOptionPane error-- Tortoise and Hair race

I am new to my Intro to Java course and am struggling with a program. I have posted about this program before but this is a different question. My program is supposed to model a race between a hare and a tortoise. I think I have everything I need but I am having trouble with my JOptionPane phrase. I think my phrase is Ok, but I am experiencing problems with the while portion of my statement. Here is the error message: cannot find symbol - Variable OK.
I use Blue J to write and compile my program. Is there any reason why its not working? I thought the variable OK was the thing that the program user chooses to start the program. Am I mistaken? Can anyone help with this problem? Is there anything else you see in my program that needs fixing? Thanks
import java.util.Random;
import javax.swing.JOptionPane;
class Race
{
int [] race = new int[70];
int tortoise;
int hare;
Random randomGenerator = new Random();
public boolean again = true;
public void StartRace()
{
tortoise = 1;
hare = 1;
System.out.println("AND THEY'RE OFF!!!!");
while (tortoise < race.length && hare < race.length)
{
moveHare();
moveTortoise();
DisplayCurrentLocation();
String request;
}
if
(tortoise > hare)
{
System.out.println("\n TORTOISE WINS!!");
}
else if
(hare > tortoise)
{
System.out.println("\n HARE WINS!!!");
}
else if
(hare == tortoise)
{
System.out.println("TIE!!!");
}
}
public void moveTortoise()
{
int n = randomGenerator.nextInt(10) + 1;
//fast plod
if ( n > 0 && n< 6)
tortoise += 3;
//slip
else if (n > 10 && n< 11)
tortoise -= 6;
//slow plod
else if (n > 6 && n< 9)
++tortoise;
// protect from going past start
if (tortoise < 1)
tortoise = 1;
// to make sure game ends
else if (tortoise > 70)
tortoise = 70;
}// end tortoise
public void moveHare()
{
int m = randomGenerator.nextInt(10) + 1;
//big hop
if (m > 0 && m<3)
hare += 9;
//big slip
else if (m < 6)
hare -= 12;
// small hop
else if (m > 3 && m< 5)
++hare;
// )small slip
else if (m < 9)
hare -= 2;
else if (m < 11)
hare += 0;
//ensure hare doesn't go past start
if (hare < 1)
hare = 1;
// ensure hare doesnt go past end
else if (hare > 70)
hare = 70;
} // end movehare
public void DisplayCurrentLocation()
{
//this is the location of each on the array
for (int count = 1; count <= 70; count++)
// when at same location
if (count ==tortoise && count ==hare)
{
System.out.println("OUCH");
}
else if (count == hare)
{
System.out.println("H");
}
else if (count == tortoise)
{
System.out.println("T");
}
else
System.out.println();
}
public static void main ( String[] args)
{
Race Application = new Race();
int startRaceRequest;
while(startRaceRequest != JOptionPane.OK_OPTION)
{
JOptionPane.showConfirmDialog(null, "Select OK To Begin the Race!:");
}
do
{
Application.StartRace();
} while(startRaceRequest != JOptionPane.OK_OPTION);
}
}
To your question with the JOptionPane: I suggest you to use
JOptionPane.showConfirmDialog(null, "Message");
instead of
JOptionPane.showMessageDialog(null, "Message");
because it allows you to do this:
int startRaceRequest;
while(startRaceRequest != JOptionPane.OK_OPTION)
JOptionPane.showConfirmDialog(null, "Hit OK to start the race!");
I don't really understand what you mean by "Ok" later on in your code, but if you refer to the confirmed dialog, try using JOptionPane.OK_OPTION wich represents an int.
Also some help with your code: At the beginning you initialize the int[] race with the length of 70. Whenever you check if one of the racers is at or above 70, you do it like this
if(tortoise < 70 && hare < 70){}
wich is called hard-coding and you should try to avoid that as much as possible, to keep your code as dynamic as possible.
If you do this
if(tortoise < race.length && hare < race.length)
you don't have to rewrite half your code just because you changed the length of the race.
Another thing to the methods MoveTortoise and MoveHare. Conventionally the should be named moveTortoise and moveHare because method ins Java begin with lower case (that goes for all your methods!). Within those two methods inside your if conditions you write way too much code. for example this:
if (m == 1 || m == 2)
hare += 9;
else if (m == 6)
hare -= 12;
else if (m == 3 && m == 5) //there is something wrong here, m cant be 5 and 3 ;)
++hare;
else if (m == 7 || m == 8)
hare -= 2;
else if (m == 9 || m == 10)
hare += 0;
could be cut to this:
if(m > 0 && m < 3){ // if a number is > 0 and < 3 -> number is 1 or 2
} else if(m < 6){ // if a number is > 0 and > 3 -> if number is < 6 -> number could be 3, 4 or 5
} else if(m == 6){
} else if(m < 9){ // -> 7 or 8
} else if(m < 11){ // 9 or 10
}
In Addition, you use a random number generator and I think you are aiming for a number between 1 to 10, however this
int m = randomGenerator.nextInt(11);
will return a number from 0 to 10. Instead, try this:
int m = randomGenerator.nextInt(10) + 1;
wich will return a number from 0 to 9, adding one will result in a number between 1 and 10.
Hope this helps. Please remember to give feedback and mark a solution if your question was answered.

Add binary values with points without shortcut [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have got a school project to add 2 binary numbers in java. The binary numbers can also have decimal values.
Example - 10.01 + 10.01 = 100.1
I cannot use short cuts like Integer.parseInt(str,radix); (These projects really suck)... :'(
I just have to use strings and stuff. I tried the following code but I am getting lost in the mid and especially to overcome the decimal factor is becoming next to impossible for me:-
String a = "101";
String b = "101";
for(int i=0;i<a.length() || i<b.length();i++){
int digit1 = Integer.parseInt(a.substring(a.length()-1));
int digit2 = Integer.parseInt(b.substring(b.length()-1));
if(digit1 == 0 && digit2 ==0 && carry == 0) {sum = 0;carry = 0;}
if(digit1 == 0 && digit2 ==1 && carry == 0) {sum = 1;carry = 0;}
if(digit1 == 1 && digit2 ==0 && carry == 0) {sum = 1;carry = 0;}
if(digit1 == 1 && digit2 ==1 && carry == 0) {sum = 0;carry = 1;}
if(digit1 == 0 && digit2 ==0 && carry == 1) {sum = 1;carry = 0;}
if(digit1 == 0 && digit2 ==1 && carry == 1) {sum = 0;carry = 1;}
if(digit1 == 1 && digit2 ==0 && carry == 1) {sum = 0;carry = 1;}
if(digit1 == 1 && digit2 ==1 && carry == 1) {sum = 1;carry = 1;}
...//could not continue further
Please help me...I am stuck very badly. Any help will be gladly appreciated! :)
This is the working code:
Note: I have just shown you how to add thses numbers. IF your 1st binary number has (say) 4 digits and 2nd binary number has (say) 10 digits then obviously this code won't work!you have to check that condition and add respective code.I have assumed that both numbers have same digits.
Also note the change in for loop conditions!
public class ADDBinary {
public static void main(String[] args) {
// TODO Auto-generated method stub
String num1 = "1101";
String num2 = "1010";
String sum = "";
int carry = 0;
for (int i = 0; i < num1.length() && i < num2.length(); i++) {
System.out.println("In for loop");
char digit1, digit2;
digit1 = num1.charAt(num1.length() - i - 1);
digit2 = num2.charAt(num2.length() - i - 1);
System.out.println("Digits="+digit1+digit2);
if (digit1 == '0' && digit2 == '0' && carry == 0) {
sum = sum + "0";
carry = 0;
} else if (digit1 == '0' && digit2 == '1' && carry == 0) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '1' && digit2 == '0' && carry == 0) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '1' && digit2 == '1' && carry == 0) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '0' && digit2 == '0' && carry == 1) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '0' && digit2 == '1' && carry == 1) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '1' && digit2 == '0' && carry == 1) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '1' && digit2 == '1' && carry == 1) {
sum = sum + "1";
carry = 1;
}
}
if(carry == 1)
sum = sum + "1";
System.out.println(new StringBuilder(sum).reverse().toString());
}
}
I have used same conditions!
First of all, some tips.
Looking at your code, I can see eight if's with the same format. This is called code duplication and it is to be avoided. You are basically typing the same lines over and over again, which is more work for you and makes your code less readable, adaptable and maintanable. If you encounter something that needs to be done multiple times, in slightly different ways, make a new method that does that thing.
You say they can have decimal values. That's not really good terminology, decimal implies base10. Radix point is what we call the decimal point in base10, but since we're working with base2, decimal doesn't apply, so we call it radix point instead.
As for your question:
(Deleted this because NullPointer beat me to it.)

Categories