Why do I get wrong output? - java

I am very new to Java and am trying to write a simple code. Here is the description:
Write a program that prompts the user for a number X. Print the
numbers from 1 to X. However, in place of multiples of 4 print “qqqq”. In place of multiples of 7, print “seven”. If a number is divisible by both 4 and 7 print “qqqqseven”. It means if I input 4, my output should be 1, 2, 3, (qqqq), ...but I get 1(qqqq), 2(qqqq), 3(qqqq), 4(qqqq)..... Can anyone help me and let me know where I am doing wrong? Any help is appreciated. Than you.
public static void main(String args[])
{
//Print Method
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for(int i=1; i <= x; i++)
{
System.out.println(i);
//if x is multiples of 4
if (x % 4 == 0)
System.out.println("qqqq");
//if x is multiples of 7
if (x % 7 == 0)
System.out.println("seven");
//if x is divisible by 4 and 7
if (x % 4 == 0 && x % 7 == 0)
System.out.println("qqqqseven");
}
}
}

Replace
if (x % 4 == 0)
With
if (i % 4 == 0)
Do likewise for the other occurrences of %
To get the correct output for multiple of 28 you will need to modify you code to this:
if (i % 4 == 0 && i % 7 == 0) { // if i is a multiple of 28 (of both 4 & 7)
System.out.println("qqqqseven");
}
else {
if (i % 4 == 0) { // if i is multiples of 4
System.out.println("qqqq");
}
else if (i % 7 == 0) { // if i is multiples of 7
System.out.println("seven");
}
}

The idea here is to use the if condition from most specific to least specific. In you case the most specific condition is a divisor of 4 and 7, followed by divisor of 4, divisor fo 7 and finally the least specific one which means everything else. If you could arrage your if conditions in that order you'll get the result.
Note: It a good practice to close scanner or any resources that you open. :)
import java.util.Scanner;
public class TestProgram {
public static void main(String[] args) {
System.out.println("Enter number upto which you want to print: ");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
for (int i = 1; i <= x; i++) {
if(i%4 == 0 && i%7 == 0) {
System.out.println("qqqqseven");
} else if(i%4 == 0) {
System.out.println("qqqq");
} else if(i%7 == 0){
System.out.println("seven");
} else {
System.out.println(i);
}
}
input.close();
}
}

Related

Need help understanding this basic challenge?

Currently doing a challenge called number to words, I have created 2 methods, one which
deals with comparing values individually so that it can print out it's string value(method called numberToWord), another method called reverse which basically re-orders the values so that it is printed in a correct sequence, for example:s
Step One 567 --> Step 2, it will be converted into 765 --> Step 3, reverse method will then convert it back to 5,6,7 individually so that it can compare the values with the if statements. However, i have tried so many things to getting this to work, i managed to make it to step 3 but when i try to return the value it gives me 3 random values before it converts e.g = 7,6,7...5,6,7, i am unable to figure out how to remove the first 3 values and return just the last three values so that it can be compared in the numberToWords method.
package com.company;
public class Main {
public static void main(String[] args) {
numberToWords(567);
}
public static void numberToWords(int number) {
int lastDigit = 0;
int digit = number;
int reverseDigit = 0;
if (number < 0) {
System.out.println("Invalid Value");
}
for (int i = 0; i < digit; i++) {
//so we are taking the last digit from 567 per iteration
lastDigit = digit % 10;
//we are then dividing the digit by 10 each time so we can get another last digit
digit /= 10;
//i will now try to essentially get down to the final number which will be flipped
reverseDigit = (reverseDigit * 10) + lastDigit;
//checking values
System.out.println(reverse(reverseDigit));
// if (reverse(reverseDigit)== 0) {
// System.out.println("Zero");
// } else if (reverse(reverseDigit) == 1) {
// System.out.println("One");
// }else if (reverse(reverseDigit) == 2) {
// System.out.println("Two");
// }else if (reverse(reverseDigit) == 3) {
// System.out.println("Three");
// }else if (reverse(reverseDigit) == 4) {
// System.out.println("Four");
// }else if (reverse(reverseDigit) == 5) {
// System.out.println("Five");
// }else if (reverse(reverseDigit) == 6) {
// System.out.println("Six");
// }else if (reverse(reverseDigit) == 7) {
// System.out.println("Seven");
// }else if (reverse(reverseDigit) == 8) {
// System.out.println("Eight");
// }else if (reverse(reverseDigit) == 9) {
// System.out.println("Nine ");
// }
if (lastDigit == 0) {
System.out.println("Zero");
} else if (lastDigit == 1) {
System.out.println("One");
} else if (lastDigit == 2) {
System.out.println("Two");
} else if (lastDigit == 3) {
System.out.println("Three");
} else if (lastDigit == 4) {
System.out.println("Four");
} else if (lastDigit == 5) {
System.out.println("Five");
} else if (lastDigit == 6) {
System.out.println("Six");
} else if (lastDigit == 7) {
System.out.println("Seven");
} else if (lastDigit == 8) {
System.out.println("Eight");
} else if (lastDigit == 9) {
System.out.println("Nine");
}
}
}
public static int reverse (int a){
int lastDigit = 0;
for (int i =0; i < a; i++) {
lastDigit = a % 10;
a /= 10;
//testing values here
//System.out.println(lastDigit);
//sout in loop gives us 567
}
return lastDigit;
}
}
If I understand what you need correctly, you don't need that much code. Just print the reminder of division by 10 and then divide by ten for then next iteration until you get zero.
enum Numbers {
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine;
}
private static void process(int number) {
do {
final int digit = number % 10;
System.out.println(Numbers.values()[digit]);
number /= 10;
} while (number > 0);
}
First use an enum since you can use it like an array but easier to declare. Then with the number you get, first get the reminder over ten. For any integer expressed as decimal the reminder over ten is the last digit. Since you have to print the last digit in the first place, just print it. Then replace number with number divided by ten. That will discard the last digit (the one just printed out) because this is an integer division. I mean, 1234 over 10 is 123.4 but because these are integer it gets truncated to 123. So now loop and the last digit will be printed again (but now it will be the first to the left due to the division). At some point, after printing the first digit of the original number you will have a one digit integer (i.e. 7) divided by ten which results in zero (because it would be 0.7 but it's an integer division).
You need to add some preconditions like the negatives.
I think you have the right idea of doing remainder division for numberToWords() and reverse().
But I think you're condition for exiting the for loop is wrong
for (int i = 0; i < digit; i++)
It will exit before you get all the digits. You want to loop until digit is 0, since you want to remainder divide UNTIL there's no more to divide ( meaning digit is 0).
so
for(int i = 0; digit != 0; i++){
...
}
while loop might be better than a for a loop since you're not using i anyways.
while(digit != 0){
...
}
It also depends on which IDE you're using but IntelliJ and eclipse can do a line by line debug so you see which line is causing issues.

Printing numbers 1-100, except when divisible by 5 or 12

The question is
Write a Java program that prints numbers from 1 to 100. If the number is divisible by 5, instead of printing the number, your program should print how many fives are in this number, if the number is divisible by 12 it should print how many twelves are in this number.
Here's my current attempt:
import acm.program.*;
public class FiveTwelve extends ConsoleProgram {
public void run() {
int a = (1);
int b = (5);
int c = (12);
for (a = 1; a <= 100; a++) {
println(a);
if ((a % 5) == 0) {
println(a/b);
} else if ((a % 12) == 0) {
println(a / c);
}
}
}
}
The problem is that my code is also printing the divisible number instead of just the outcome. Example output:
1
2
3
4
5
1
6
7
8
9
10
2
11
12
1
This goes on. I want to remove numbers that are divisible by 5 and 12. Instead, I need to show the result or num/5 && num/12.
UPDATE!!!
import acm.program.*;
public class FiveTwelve Extends ConsoleProgram{
public void run() {
for (int a = 1; a <= 100; a++) {
if (a % 5 == 0 && a % 12 == 0) {
println(a / 5);
println(a / 12);
} else if (a % 5 == 0) {
println(a / 5);
} else if (a % 12 == 0) {
println(a / 12);
} else {
println(a);
}
}
}
}
guess we all missed something.
Instead of solving for the specific case, let's write an extensible solution. First, what variables are there in the question that could change? I'd say they are:
The starting number 1
The last number 100
The divisors 5 and 12
Additionally, as #Anoml pointed out, the problem wording suggests that if your number is divisible by multiple divisors, we should print out the number of times it is divisible for every applicable divisor. And, as you noted in your question, we only want to print the number itself when it is not divisible by any divisors.
So, our solution becomes:
import acm.program.*;
public class FiveTwelve extends ConsoleProgram {
private final int FIRST = 1;
private final int LAST = 100;
private final int[] DIVISORS = { 5, 12 };
public void run() {
boolean hasDivisor;
for (int i = FIRST; i <= LAST; i++) {
hasDivisor = false;
for (int divisor : DIVISORS) {
if (i % divisor == 0) {
println(i / divisor);
hasDivisor = true;
}
}
if (!hasDivisor) {
println(i);
}
}
}
}
This way, we can change our starting number, last number, or which divisors we support, and the program will still pass.
This is what you intended to do, println(a) in all other cases.
for (int a = 1; a <= 100; a++) {
if (a % 5 == 0) {
println(a / 5);
} else if (a % 12 == 0) {
println(a / 12);
} else {
println(a);
}
}

Java not reading "&&" statements properly?

I'm having a problem with my Java code. Specifically, one of my if statements containing an && is not returning True for certain inputs like I expect it to.
The snippet in question:
if (num%2==1 && num < 0) { //why is not reading this statement?
negodd ++;
}
Sample inputs and outputs vs expected outputs:
Enter any number to continue. Enter 0 to stop :
1
2
-2
-1
0 // not counted as a number since it is a stop function.
Output of my code. What it should be.
You Entered 4 numbers : You Entered 4 numbers :
1 negative even 1 negative even
1 positive even 1 positive even
0 negative odd 1 negative odd <--should read the 1
1 positive odd 1 positive odd
The full code in case that helps:
import java.util.Scanner;
public class stupid {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int num = 0;
int negodd = 0, count = 0, posseven = 0;
int possodd = 0; int negeven=0;
System.out.println("Enter any number to continue. Enter 0 to stop : ");
num = x.nextInt();
if(num==0){
System.out.print("You immediately stop");
System.exit(0);
}
while (num != 0) {
count ++;
if (num%2==1 && num > 0) {
possodd ++;
}
if (num%2==1 && num < 0) { //why is not reading this statement?
negodd ++;
}
if (num%2==0 && num > 0) {
posseven ++;
}
if (num%2==0 && num < 0) {
negeven++;
}
num = x.nextInt();
}
System.out.printf("You Entered %d numbers\n",count);
System.out.printf("%d negative even \n",negeven);
System.out.printf("%d positive even\n",posseven);
System.out.printf("%d negative odd\n",negodd);
System.out.printf("%d positive odd\n",possodd);
}
}
Thanks in advance!
Using the modulo operator with negative numbers gives you a different result than you might think.
1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1
To get the result you want, you can replace your modulo tests with num % 2 == 0 and num % 2 != 0.
1 % 2 == 1
2 % 2 == 0
-2 % 2 == 0
-1 % 2 == -1
Here, -1%2 does not results in 1. Hence, it will not increment value of negodd variable.
In JAVA, negative number modulo will give same result as positive number modulo but with a negative sign. 0 is neutral thus it will not have any sign.
-1 % 2 is going to return -1, not 1, where -2 % 2 will give a result of 0.

Detect if number is a multiple of 7 or contains the number 7

I read a book about challenges in Java, and it gives the next question:
create a function, which get a number as argument, and detect if number is a multiple of 7 or contains the number 7.
The signature is: public boolean find7(int num)
I create this function, when the number is between 0 to 99, by the next condition:
if (num mod 7 == 0 || num / 10 ==7 || num mod 10 == 7)
return true;
But what with number which is greater than 99? like 177, or 709? How can I detect it?
It's probably best to leave strings out of this:
public static boolean check(final int n) {
int m = Math.abs(n);
while (m > 0) {
if (m % 10 == 7)
return true;
m /= 10;
}
return n % 7 == 0;
}
The while-loop checks each digit and tests if it is 7; if it is, we return true and if it isn't, we continue. We reach the final return statement only if none of the digits were 7, at which point we return whether the number is a multiple of 7.
if (num % 7 ==0 || ("" + num).contains("7") ){
return true;
}
You can extend your approach to numbers above 100 like this:
public boolean find7(int num) {
// support for negative integers
num = Math.abs(num);
// check if num is a multiple of 7
if (num % 7 == 0) {
return true;
}
// check to see if num contains 7
while (num > 1) {
// if the last digit is 7, return true
if (num % 10 == 7) {
return true;
}
// truncate the last digit
num /= 10
}
// the number is not a multiple of 7 and it does not contain 7
return false;
}
You can do the following
if(Integer.toString(num).contains("7") || ...){
}
As far as checking if the number is divisible by 7, you're fine.
If you want to check if it contains the 7 digit, I think the easiest approach would be to treat the number as a String:
public boolean find7(int num) {
// check if it's a multiple of 7:
if (num % 7 == 0) {
return true;
}
// if it's not, check if it contains the character 7:
return String.valueOf(num).contains("7");
}
For detecting if number is multiple of 7:
boolean isMultiple = x % 7 == 0
For detecting digit:
Convert it to String and use String.contains()
or
Create digit List like this:
private List<Integer> getDigitList(int number){
List<Integer> list = new ArrayList<Integer>();
int leftover = number;
while (leftover != 0){
int result = leftover % 10;
leftover = (leftover - result)/10;
list.add(result)
}
assert leftover == 0;
return list;
}

Solving elimination using nested loops in java?

I was trying to solve a program challenge that solves this prompt
"When 2, 3, 4, 5, 6 eggs are removed at a time from a basket of eggs, the remaining amounts are 1, 2, 3, 4,5 eggs respectively. When 7 eggs are removed at a time, no eggs remain. What is the least number of eggs I could have had in the basket?"
I tried to make a program using nested loops and I feel like it should work, but when I run the program, it just prints blank space. I never get a number to satisfy the equation. Can someone help me, or show me what I did wrong please?
I'm only allowed to use nested loops and decision statements.
public class Program{
public static void main (String []args){
int c,d,e,f,g,h;
for (int j=1; j<1000; j++){
for (c=j; c>=1; c=c-2){
}
if (c==1){
for (d=j; d>=2; d=d-3){
}
if (d==2){
for (e=j; e>=3; e=e-4){
}
if (e==3){
for (f=j; f>=4; f=f-5){
}
if (f==4){
for (g=j; g>=5; g=g-6){
}
if (g==5){
for (h=j; g>=0; h=h-7){
}
if (h==0){
System.out.println(+j);
}
}
}
}
}
}
}
}
}
Try this:
public static void main(String[] args) {
int x = 7;
int result = -1;
while (true) {
if ((x % 2 == 1) && (x % 3 == 2) && (x % 4 == 3) && (x % 5 == 4)
&& (x % 6 == 5)) {
result = x;
break;
}
x += 7; // This because you know its multiple of 7
}
System.out.println("Result is: " + result);
}
int numberOfEggs = 0;
for (;;)
{
if (numberOfEggs % 2 == 1 &&
numberOfEggs % 3 == 2 &&
numberOfEggs % 4 == 3 &&
numberOfEggs % 5 == 4 &&
numberOfEggs % 6 == 5 )
return numberOfEggs;
else
numberOfEggs += 7;
}

Categories

Resources