Java Question .What is the problem in my code? - java

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.

Related

Print a number from 0 to inputted number that divisible by 3 or end with 3

There's one hidden test case that this code doesn't work and I don't know why. [EDITED] Sorry for the lack of information. I'm using an app to learn Java and this is a coding test, there are 4 total test with 4 different inputs, the first 3 one is fine but the last one (hidden so I don't know the input and output) told me that it's wrong but I don't know what's wrong in my code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int number = read.nextInt();
int x = 3;
while(number > 3 && x <= number)
{
if(x%3==0 || x%10==3)
{
System.out.println(x);
}
++x;
}
}
}
If number = 3, your while loop does not run, and since 3 is divisible by 3 it should be printed.
You can just remove that part from your while loop, and leave this.
while(x <= number)
In your code you just ignoring when the number is 3. Your condition number > 3 is ignoring when the number == 3.
DO like this while(number >= 3 && x <= number) instead of while(number > 3 && x <= number)
while(number >= 3 && x <= number)
{
if(x%3==0 || x%10==3)
{
System.out.println(x);
}
++x;
}
One thing is x>3 condition is wrong as x==3 is also true.
Other thing is, why would you use an extra condition and increase complexity when you can just do a simple for loop/ while loop from 0-number and check if number %3 or number%10 is true?

Branching statements - ascending or descending integers

Been studying Java for a few months now with no prior development experience, but I am determined to learn this. This is my first post. Here's the question:
Write a program that reads a sequence of integer numbers and outputs true if the sequence is ordered (in ascending or descending order), otherwise, false. Keep in mind, if a number has the same value as the following number, it does not break the order.
The sequence ends with 0. Do not consider this number as a part of the sequence. The sequence always has at least one number (excluding 0).
Sample Input 1:
9 8 7 6 5 4 3 2 1 0
Sample Output 1:
true
Sample Input 2:
1 2 3 3 9 0
Sample Output 2:
true
Sample Input 3:
1 2 5 5 2 3 0
Sample Output 3:
false
I've read other posts that addresses this issue, but my code is a representation of the concepts I've learned and quasi-understand thus far.
My intuition is that in order to iterate through all the values that are input BEFORE producing a 'true' or 'false', a list is probably needed. But, I'm unsure of how to utilize Scanner within a list and how to use a list within a 'for loop' &/or 'if' statements. Here is my code thus far, which is producing a error of time limit exceeded. Thank you in advance for your help.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
for (int i = 1; i > 0; i++) {
if (input >= i || input == i + 1) {
System.out.println(true);
}
else if (input <= i || input == i - 1) {
System.out.println(true);
}
else {
System.out.println(false);
}
}
}
}
Let's first read in all the numbers:
Scanner scanner = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>(); //use a list to store
int number = -1;
while(number != 0) { //go until 0
System.out.println("Enter a positive int or 0 to stop!");
number = scanner.nextInt(); //read integer
if(number != 0) {
numbers.add(number); //save it, but only if it's not 0
}
}
Now we have all numbers in the list. Some methods can be writter to check if they are ascending:
public static boolean isAscending(List<Integer> numbers) {
int number, next;
if(numbers.size()==1) return true; // edge cases
if(numbers.size()==2) {
return numbers.get(0) <= numbers.get(1);
}
for(int i=0; i<numbers.size() - 2; i++) { //from first to one before last
number = numbers.get(i);
next = numbers.get(i+1);
if(next < number) { //next is NOT bigger then the current (equal accepted)
return false;
}
}
return true; //if we got here then it's ascending
}
The descending method is similar, but you use '>' when comparing the numbers. Then, it's just a matter of calling them on the input list:
boolean ascending = isAscending(numbers);
boolean descending = isDescending(numbers);
if(ascending || descending) {
//result is TRUE here
System.out.println("TRUE");
} else {
//result is FALSE here
System.out.println("FALSE");
}

How to remove unwanted items from a printed list?

Write a Java function that accepts an integer, n, as input and outputs a string of integers from 1 to n where every number that is a multiple of 4 is replaced with "Hello", every number that is a multiple of 5 is replaced with "Wonderful" and every number that is a multiple of 7 is replaced with "World".
package Multiple;
import java.util.Scanner;
public class MultipleList {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer number: ");
int n = reader.nextInt();
for (int i = 1; i <= n; i++) {
// Checking if the integer is a multiple of 4
if ((i % 4) == 0) {
// print
System.out.println("Hello");
}
// Checking if the integer is a multiple of 5.
if ((i % 5) == 0) {
// print
System.out.println("Wonderful");
}
// Checking if the integer is a multiple of 7.
if ((i % 7) == 0) {
// print
System.out.println("World");
}
System.out.println(i);
}
}
}
When I put n = 7 (for example) I expect the output "1, 2, 3, Hello, Wonderful, 6, World", but the actual output is "1, 2, 3, Hello, 4, Wonderful, 6, World, 7".
You have to do this:
if ((i % 4) == 0) {
System.out.println("Hello");
} else if ((i % 5) == 0) {
System.out.println("Wonderful");
} else if ((i % 7) == 0) {
System.out.println("World");
} else {
System.out.println(i);
}
Your last print statement, the unconditional
System.out.println(i);
should only be executed if nothing has previously been printed for this particular value of i.
There are two ways to go about this; (1) the brute force way, preceding that statement which says "if this is not a multiple of 4 and not a multiple of 5 and not a multiple of 7", and (2) tracking whether you've printed anything. I prefer the second approach.
I think it would be useful for you to supply the exact code, though, so I have not done so here.
You can change
if( n!=i)
Syso(i)
instead of end of the line of system.out.println(i);

java while loop won't print the text after a the stopping condition [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 8 years ago.
Improve this question
I just started studying Java and I'm required to use while to decided how many players can be goalkeepers based on their number. The loop is supposed to stop after the user entered 0 and print the counted number of players that can be goalkeepers.
public class Q3_201303719 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int num; int count=0;
System.out.println("Enter the players' numbers");
num = input.nextInt();
while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))
count++;
System.out.println(count+ " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it won't
// print and keeps asking the user to enter a number.
}
}
From the question it is difficult to understand what it is you are trying to achieve. However, we can try to help you understand the code as it is written.
The while loop is currently written as:
while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))
This could be rewritten as the following and it would not make any difference:
while (num != 0 && num < 31 && num%2==0 || num%3==0)
The additional parenthesis that you included are not required.
In Java the operator precedence is && before ||. This means that the && operators will be evaluated first, followed by the ||. Therefore, the above statement could therefore be rewritten as the following and it would not make any difference:
while ((num != 0 && num < 31 && num%2==0) || num%3==0)
However, it may make the code a little easier to understand.
So when the code executes the following occurs:
The count variable is initialised to 0.
A value is retrieved and stored in the variable num. Lets say that this value is 10.
The while statement is evaluated for the first time:
num != 0 is true as 10 != 0.
num < 31 is true as 10 is less than 31.
num%2==0 is true as 10 divided by 2 is 5 and leaves a remainder of 0.
As these all evaluate to true, the OR part (num%3==0) is not evaluated as it is not neccessary. See short circuit evaluation (http://users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf).
The count is incremented to 1.
The loop executes again for the second time. num is still 10.
num != 0 is true as 10 != 0.
num < 31 is true as 10 is less than 31.
num%2==0 is true as 10 divided by 2 is 5 and leaves a remainder of 0.
The count is incremented to 2.
And so on... in an infinite loop.
If the variable num was instead set to 9. The loop would evaluate as follows:
num != 0 is true as 9 != 0.
num < 31 is true as 9 is less than 31.
num%2==0 is false as 9 divided by 2 is 4 and leaves a remainder of 1.
Therefore, now the || part is evaluted:
num%3==0 is true as 9 divided by 3 is 3 and leaves a remainder of 0.
Again, this would result in an infinite loop.
If the variable num was instead 0:
num != 0 is false
As the first num!=0 is false, the num<31 and num%2==0 parts are not evaluated as their results would not make any difference.
The num%3==0 is then evaluated:
num%3==0 is true as 0 divided by 3 leaves a remainder of 0.
Again, this would result in an infinite loop.
I hope that this may help to clarify your understanding and allow you to correct the code appropriately.
how many players' numbers do you have to input?
you have a while loop that depends on num value, but you never change the num value. that will end up in endless loop...
if you have more players, create a for loop to enter the numbers, store the numbers in an array or an arraylist and if you use the while loop, use it so that it depends on a value that you change inside the loop. otherwise it will loop forever.
do{
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
}while(num!=0);
your code with this should look like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
int count = 0;
do {
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
} while (num != 0);
System.out.println(count + " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it
// won't
// print and keeps asking the user to enter a number.
}
If you can't use a do-while-loop as Ubica suggested, then you need to work your way around it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num=2; // you need to initialize num with a value, that allows you to go inside the while loop at least once
int count = 0;
while((num != 0) && (num < 31) && (num % 2 == 0) || (num % 3 == 0)) {
System.out.println("Enter the players' numbers");
num = input.nextInt(); // user input is here inside the loop
count++; // your count will count every valid input + the user input that ends the loop
}
count--; // if your user entered 0 to exit the loop, count would have still incremented, so you need do subtract one again
System.out.println(count + " players can be goalkeepers.\n");
}
As I commented in the code, first you initialize num with a dummy value, that allows you to enter the loop at least once. Then you listen to the users input and count the loop iterations. But since the loop will execute at least once (even though your user might enter 0 right away to exit the loop) your count would be one higher than the actual number of valid inputs. So you have to subtract that 1 from your count again.
EDIT
I forgot to mention: your loop will not stop when the user enters 0 because
(num % 3 == 0) // is true with num=0
so when the user enters 0 the while condition will evaluate like this:
while( false && true && true || true )
while( false || true )
while( true )
The bracketing for the loop should fix this problem.
You need braces surrounding your while loop block. As a general rule, it is best to overuse braces rather than under-use them.
Your code should look like:
package q3_201303719;
import java.util.Scanner;
public class Q3_201303719 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int num; int count=0;
System.out.println("Enter the players' numbers");
num = input.nextInt();
while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
count++;
}
// The braces added above are required for the while loop and will keep your program
// from not outputting your results.
System.out.println(count+ " players can be goalkeepers.\n");
}
}
Best of luck and happy coding. :)
Your code isn't making sense.
1st : The While loop is not modifying the "num" value, resulting in
infinite loop if entered.
2nd : What is the code supposed to do? It is really hard to tell from what you show.
I think placing while loop upper could help you, but still code makes no much sense
public class Q3_201303719 {
public static void main(String[] args) {
int num = 0; int count=0;
while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
Scanner input = new Scanner (System.in);
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
}
System.out.println(count+ " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it won't
// print and keeps asking the user to enter a number.
}
}
Edit :
This problem occurred because you didn't follow a really simple rule : think before coding.
For this exercise you need to think about what your code should be doing, and then write the code for it. Coding is just a language, if you know what you want to write then it is easier. Here you obviously don't really know what you wanna do, and as you are new with development it was likely that you get stucked

java program outputting even/odd numbers

My task is to write a java program that first asks the user how many numbers will be inputted, then outputs how many odd and even numbers that were entered. It is restricted to ints 0-100. My question is: What am I missing in my code?
import java.util.Scanner;
public class Clancy_Lab_06_03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;
System.out.println("How many numbers will be entered?");
n = input.nextInt();
while (n < 0 || n > 100) {
System.out.println("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
n++;
}
int odd = 0;
int even = 0;
while (n >= 0 || n <= 100) {
n = input.nextInt();
if (n % 2 == 0) {
even++;
} else {
odd++;
}
}
System.out.println(even + "even" + odd + "odd");
}
}
Second while loop is infinite. Relplace it with something like this:
for (int i = 0; i < n; i++) {
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also I don't understand why are you incrementing n in first loop. For example when you will first give -5, you will be asked to re-enter the number. Then you type -1, but it gets incremented and in fact program processes 0, altough user typed -1. In my opinion it is not how it suppose to work and you should just remove this n++.
As you asked in comment - the same using while loop:
while(n > 0) {
n--;
int b = input.nextInt();
if (b % 2 == 0) {
even++;
} else {
odd++;
}
}
Also it is good idea to close input when you no longer need it (for example at the end of main method)
input.close();
You had two issues - first you were incrementing n in the first loop, rather than waiting for the user to enter a valid number.
In the second loop, you weren't comparing the number of entries the user WANTED to make with the number they HAD made - you were over-writing the former with the new number.
This version should work, although I've not tested it as I don't have java on this machine.
Note that we now sit and wait for both inputs, and use different variable names for the "how many numbers will you enter" (n) and "what is the next number you wish to enter" (num) variables? Along with a new variable i to keep track of how many numbers the user has entered.
import java.util.Scanner;
public class Clancy_Lab_06_03
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int n;
System.out.println ("How many numbers will be entered?");
n = input.nextInt();
//Wait for a valid input
while (n < 0 || n > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
n = input.nextInt();
}
//Setup variables for the loop
int odd = 0;
int even = 0;
int num;
//Keep counting up until we hit n (where n is the number of entries the user just said they want to make)
for(int i = 0; i < n; i++)
{
//Changed this, because you were over-writing n (remember, n is the number of entries the user wants to make)
//Get a new input
while (num < 0 || num > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
num = input.nextInt();
}
//Check whether the user's input is even or odd
if (num % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println(even + " even. " + odd + " odd.");
}
}
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Enter an Integer number:");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
My suggestion to you is to have a clear separation of your requirements. From your post, you indicate you need to prompt the user for two distinct data items:
How many numbers will be entered (count)
The values to be analyzed
It is a good practice, especially when you are learning, to use meaningful names for your variables. You are using 'n' for a variable name, then reusing it for different purposes during execution. For you, it is obvious it was difficult to figure out what was 'n' at a particular part of the program.
Scanner input = new Scanner (System.in);
int count;
System.out.println ("How many numbers will be entered?");
count = input.nextInt();
//Wait for a valid input
while (count < 1 || count > 100)
{
System.out.println ("ERROR! Valid range 1-100. RE-Enter:");
count = input.nextInt();
}
Additionally, a count of zero should not be valid. It does not make sense to run a program to evaluate zero values (don't bother a program that does nothing). I believe the lowest count should be one instead.
int odd = 0;
int even = 0;
int value;
do
{
System.out.print("Enter a number between 0 and 100: ");
value = input.nextInt();
while (value < 0 || value > 100)
{
System.out.println ("ERROR! Valid range 0-100. RE-Enter:");
value = input.nextInt();
}
if (value % 2 == 0)
{
even++;
}
else
{
odd++;
}
count--; // decrement count to escape loop
} while (count > 0);
System.out.println(even + " even. " + odd + " odd.");
This example uses a do/while loop because in this case, it is OK to enter the loop at least once. This is because you do not allow the user to enter an invalid number of iterations in the first part of the program. I use that count variable directly for loop control (by decrementing its value down to 0), rather than creating another variable for loop control (for instance , 'i').
Another thing, slightly off topic, is that your requirements were not clear. You only indicated that the value was bounded to (inclusive) values between 0 and 100. However, how many times you needed to repeat the evaluation was not really clear. Most people assume 100 was also the upper bound for your counter variable. Because the requirement is not clear, checking a value greater or equal to 1 for the count might be valid, although highly improbable (you don't really want to repeat a million times).
Lastly, you have to pay attention to AND and OR logic in your code. As it was indicated, your second while loop:
while (n >= 0 || n <= 100) {}
Is infinite. Because an OR evaluation only needs one part to evaluate to TRUE, any number entered will allow the loop to continue. Obviously, the intent was not allow values greater than 100. However, entering 150 allows the loop to continue because 150 >= 0. Likewise, -90 also allows the loop to continue because -90 <= 100. This is when pseudocode helps when you are learning. You wanted to express "a VALUE between lower_limit AND upper_limit." If you reverse the logic to evaluate values outside the limit, then you can say " value below lower_limit OR above upper_limit." These pseudocode expressions are very helpful determining which logical operator you need.
I also took the liberty to add a message to prompt the user for a value. Your program expects the user to enter two numbers (count and value) but only one prompt message is provided; unless they enter an out of range value.
extract even numbers from arrayList
ArrayList numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
numberList.stream().filter(i -> i % 2 == 0).forEach(System.out::println);

Categories