Just curious is there a way to set an if statement condition that checks if value is equal to a data type. Like if (x=int) kind of thing.
I am suppose to create a program that checks for prime numbers but i do not know how to do it other than divide the number(entered by user) by the building block number (2-9(excluding 1 because all numbers are divisible ...)) and if all of them return a float then the number is prime.
I also think this way is inefficient but again i do not have any other clue how i would do it. So if possible some ideas would work too.
This is the structure of the code:
package innocence;
import java.util.*;
class GS1
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
double num;
System.out.println("Enter a number to check if it is prime or not");
num=input.nextDouble();
if((num % 2 == float) || (num % 3== float) || (num % 4 == float)|| (num % 5 == float)|| (num % 6 == float)|| (num % 7 == float)|| (num % 8 == float)|| (num % 9 == float) ) // float returns an error but i want to do it so it checks if it is a float or not
{
System.out.println("The number you haver entered," + num + "is a prime number");
}
else
{
System.out.println("The number entered is not prime");
}
}
}
You can check if the number is equal to the number rounded to the nearest integer:
public static boolean isInteger(double n) {
return n == Math.round(n);
}
if(!isInteger(num % 2) && !isInteger(num % 3) && !isInteger(num % 4) &&
!isInteger(num % 5) && !isInteger(num % 6) && !isInteger(num % 7) &&
!isInteger(num % 8) && !isInteger(num % 9) )
{
System.out.println("The number you haver entered," + num + "is a prime number");
}
else
{
System.out.println("The number entered is not prime");
}
If course this doesn't really check if the number is prime or not; it only checks whether the number is divisible by the integers 2 to 9.
Related
i set an if to check if the numbers being sent we're divisible by 3 or 7 or so on..
but it doesn't seem to do that.
i tried changing how it worked which is why it looks like this now but it still doesn't work.
public void primeNumbers() {
System.out.println("Enter the amount of prime numbers you'd like: ");
int numberOfPrimes = reader.nextInt();
int numbersFound = 0;
int foundCount = 0;
while(foundCount < numberOfPrimes) {
if (numbersFound < 2) {
numbersFound++;
}
else if(numbersFound % 3 == 0 || numbersFound % 5 == 0 || numbersFound % 7 == 0 || numbersFound % 11 == 0 || numbersFound == 2) {
System.out.print(numbersFound +" ");
foundCount++;
numbersFound++;
}
else {
numbersFound++;
}
}
}
no errors, it's just the numbers coming out aren't prime.
I figured out why it wasn't working.
I just forgot to set a condition that said that if the number is divisible by 2, then skip.
And instead of making all the numbers that are divisible by 3 7 5 and 11 be printed
i make them not be printed
im pretty sure
Sorry lol
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();
}
Hi everyone on this community.
I'm a Java newbie. This is no homework, I'm really passionate about programming and I really want to learn more. I am stuck with one exercise.
Basically I have to create a simple lottery game.
The user has to input one number from 0 to 999, a three digit number.
If the guess is exactly the same, the prize is 10.000 $,
If the guess is about the same (digits guessed but not in order) the
prize is 3,000 $
If the guess is not really the same (digits guessed == 1) the prize
is 1,000 $.
Here's my code so far: I don't know how to deal with condition 2 and 3. Could I have some hint or comment?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a three digit number");
int guess = input.nextInt();
//generate number:
int lottery = (int)(Math.random() * 1000);
if ((guess > 999) || (guess < 100)) {
System.out.println("The number is not a three digit number. The system will exit NOW.");
System.exit(1);
}
else {
// extract digits from lottery number
int lotteryDigit1 = lottery / 100;
int lotteryDigits = lottery % 100;
int lotteryDigit2 = lottery / 10;
int lotteryDigit3 = lottery % 10;
// extract digits from guessed number
int guessDigit1 = guess / 100;
int remainingDigits = guess % 100;
int guessDigit2 = guess / 10;
int guessDigit3 = guess % 10;
System.out.println("The lottery number is: " + lottery);
// check the guess:
if (guess == lottery) {
System.out.println("Exactly what the number was.");
}
else if {
// digits guessed, but not in exact order (eg. 332 = 233)
}
else if {
// only one digit is guessed (eg. 332 = 442)
}
}
}
}
Could I have some comment on the code? Is it readable or horribly written? I really don't have a clue since I am really just new to programming. Thanks.
With an array, you can count how many digits the real number and the guessed number contains, and perform comparisons with that. First make two arrays of length 10 (one slot for each digit), then increase each relevant "slot" by 1 for every digit in the real number. Do the same for the guess, and compare.
I'm recommending this approach because it will scale for guesses with 4, 5, or even 15 digits, whereas coding these checks by hand will quickly turn into a problem with lots of duplicate code.
If, for some reason, you're not allowed to use arrays, you could manually do the counting - it sounds tempting to check if each digit exists in the other set of digits, but you'll run into trouble with duplicate digits (consider 112, which, when compared to 122, would contain "all" the digits; just not in the right amounts!). This will lead to a lot of duplicate code.
It'd be something like this...
int matchingDigits = 0;
if ( guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit1 == lotteryDigit3) {
matchingDigits++;
}
if ( guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2 || guessDigit2 == lotteryDigit3) {
matchingDigits++;
}
if ( guessDigit3 == lotteryDigit1 || guessDigit3 == lotteryDigit2 || guessDigit3 == lotteryDigit3) {
matchingDigits++;
}
As you can see, it's a lot of duplicate code, and it doesn't properly handle the 112 vs 122 case. To properly handle that, you'd have to split each check apart and cross out numbers you've already "used"... which is possible, but leads to really lengthy code.
Here's how you'd do it...
boolean digit1Used = false;
boolean digit2Used = false;
boolean digit3Used = false;
int matchingDigits = 0;
if ( guessDigit1 == lotteryDigit1) {
matchingDigits++;
digit1Used = true;
} else if ( guessDigit1 == lotteryDigit2) {
matchingDigits++;
digit2Used = true;
} else if ( guessDigit1 == lotteryDigit3) {
matchingDigits++;
digit3Used = true;
}
if ( guessDigit2 == lotteryDigit1 && !digit1Used) {
matchingDigits++;
digit1Used = true;
} else if ( guessDigit2 == lotteryDigit2 && !digit2Used) {
matchingDigits++;
digit2Used = true;
} else if ( guessDigit2 == lotteryDigit3 && !digit3Used) {
matchingDigits++;
digit3Used = true;
}
if ( guessDigit3 == lotteryDigit1 && !digit1Used) {
matchingDigits++;
} else if ( guessDigit3 == lotteryDigit2 && !digit2Used) {
matchingDigits++;
} else if ( guessDigit3 == lotteryDigit3 && !digit3Used) {
matchingDigits++;
}
Note that I left out the checks for digitUsed in the first checks and the sets for digitUsed for the third set of checks - because we're not going to use them anymore. As you can see, it's really long AND it's basically faking arrays. Hence why it's not recommended to do so.
Imagine that solution for a 15 digit array! It'd be (N + 1 + (N*3*N) + N + N) lines long - 15 for digitUsed declarations, 1 for the matching digits, 15 digit comparisons of 3 lines for 15 digits, plus 15 closing braces and 15 blank lines in between - a total of 721 lines! That's why you should use arrays for this, and not checking it by hand.
If you've learned about methods already, I suggest you put the digit matcher in a separate function; that way you can keep your digit matching logic and the result-to-prize matching logic somewhat separated.
It’s not going to be nice code. For the second bullet, guessing all the digits but not in the right order, you may write a class like:
public class ThreeDigitNumber {
int digit1;
int digit2;
int digit3;
public ThreeDigitNumber(int number) {
digit1 = number / 100;
int remainingDigits = number % 100;
digit2 = remainingDigits / 10;
digit3 = remainingDigits % 10;
}
public int getDigit1() {
return digit1;
}
public int getDigit2() {
return digit2;
}
public int getDigit3() {
return digit3;
}
boolean isDigitGuessed(int digit) {
if (digit == digit1) {
// allow digit to be guessed only once, so set to a non-digit value when returning true
digit1 = -1;
return true;
}
if (digit == digit2) {
digit2 = -1;
return true;
}
if (digit == digit3) {
digit3 = -1;
return true;
}
return false;
}
}
Now you can test whether all digits have been guessed:
ThreeDigitNumber lotteryTdn = new ThreeDigitNumber(lottery);
ThreeDigitNumber guessTdn = new ThreeDigitNumber(guess);
boolean allDigitsGuessed = false;
if (lotteryTdn.isDigitGuessed(guessTdn.getDigit1())) {
if (lotteryTdn.isDigitGuessed(guessTdn.getDigit2())) {
if (lotteryTdn.isDigitGuessed(guessTdn.getDigit3())) {
allDigitsGuessed = true; // 3000 $ won
}
}
}
I recently started to get into Java (about a week ago) and I have a question for the code bellow:
The program written checks if the input number from a user (whole number) can be divided on both 5 and 7, only by 5, only by 7 and if it cannot be divided at all.
My question is, is there some other way to reduce the code written?
First post here, sorry if I ask dumb question, I am just curious.
Thank you in advance.
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
int number = sc.nextInt();
int five = 5;
int seven = 7;
boolean a = (number % five == 0) && (number % seven == 0);
if (a == true)
{
System.out.println(number + " divides on both 5 and 7.");
}
else
{
System.out.println(number + " doesn't divide on both 5 and 7.");
}
if (number % five == 0)
{
System.out.println(number + " divides successfuly by 5.");
}
else
{
System.out.println(number + " can't be divided successfuly by 5.");
}
if (number % seven == 0)
{
System.out.println(number +" divides successfuly by 7.");
}
else
{
System.out.println(number + " can't be divided successfuly by 7.");
}
Yes of course. What you need to do is nest if statements.
int number = sc.nextInt();
if (number % five == 0)
{
if (number % seven == 0)
System.out.println(number + " is divisible by both 5 and 7.");
else
System.out.println(number + " is divisible by 5.");
}
else {
if (number % seven == 0)
System.out.println(number + " is divisible by 7.");
else
System.out.println(number + " is not divisible by either 5 or 7.");
}
This means that any code inside the curly braces of the first if statement can only be reached if number%five == 0. Therefore, after that point, there are two possibilities: either it is divisible by 7 as well or it is not.
Likewise, code in the first else can only be reached if number%five != 0. Therefore, after that point, there are two possibilities: either it is divisible by 7 or it is divisible by neither of them.
I heard you can determine if a number is prime by checking if it is divisible by 2 or 3 and then either 6k + 1 or 6k - 1 (17 --> 6(3) - 1)
When I try this though, it says 1125 is a prime number. It evaluates the num - 1%6 to be true in the if statement but not in the print function. The syntax is the same as the num + 1 %6 if statement so I'm not sure what is going on.
boolean prime = false;
if(num%2 != 0){
if(num%3 != 0){
if(((num+1)%6) == 0)
prime = true;
if(((num-1)%6) == 0)
prime = true;
System.out.print((1124%6 == 0));
}
}
Your code never gets past (num % 3 != 0) on 1125 because 1125 is evenly divisible by 3. So, on that number, your System.out is never executed.
Here, I adjusted your code a bit:
public static void main(String[] args) {
for (int num = 2; num < 2000; num++) {
boolean prime = false;
if (num % 2 != 0) {
if (num % 3 != 0) {
if (((num + 1) % 6) == 0) prime = true;
if (((num - 1) % 6) == 0) prime = true;
}
}
System.out.println(num + " prime? " + prime);
}
}
Sample output:
1124 prime? false
1125 prime? false
1126 prime? false
1127 prime? true
1127 is not prime (7 * 161) so the algorithm doesn't work. Although I suspect it's pretty good at finding prime candidates.