This is simple code but I am not able to figure out why it is accepting two lines of input:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String inputString = scan.nextLine();
int n = Integer.parseInt (inputString);
for (int i = 1; i <= n; ++i) {
inputString = scan.nextLine();
int num = Integer.parseInt (inputString);
System.out.println ("Checking prime of: " + num);
for (int j = 2; j*j < num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
break;
}
}
System.out.println ("Prime");
}
}
}
Now when I run with the following input:
3
12
5
7
The program prints the following:
Checking prime of: 12
Not prime
Prime
Checking prime of: 5
Prime
Checking prime of: 7
Prime
Note the second Prime above when it has not consumed any input.
I must be making a simple mistake but not able to figure out what is wrong. If someone could point out what I am doing wrong that would be much appreciated.
This line is being printed always, every cycle.
System.out.println ("Prime");
Add a flag variable instead, inside your for 1st loop
boolean isPrime = true;
And inside your if:
if (num % j == 0) {
isPrime = false;
break;
}
Then have another condition
if (isPrime) {
System.out.println ("Prime");
} else {
System.out.println ("Not prime");
}
That's it
for (int j = 2; j*j < num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
break;
}
}
System.out.println ("Prime");
The last line is called either way. You need to either initialize a flag to help you figure out if the loop ended early, or simply return whenever you print "Not prime".
You do a scan on the 2nd line of the main method, then again at the top of your loop. The first one consumes the first line of input, but all you do with it is parse it into an int, you don't check it and don't output anything for it.
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String inputString = scan.nextLine();
int n = Integer.parseInt (inputString);
a: for (int i = 1; i <= n; ++i) {
inputString = scan.nextLine();
int num = Integer.parseInt (inputString);
System.out.println ("Checking prime of: " + num);
for (int j = 2; j*j <= num; ++j) {
if (num % j == 0) {
System.out.println ("Not prime");
continue a;
}
}
System.out.println ("Prime");
}
}
}
here you have pay attention over two points.
1. about break statement
that is it will break u from innermost loop only and that is the reason "prime" is printed whether the number is prime or not . so use labelled loop concept as i have used with "continue" .
your logic in "for loop" of checking the number whether it is prime or not is little bit wrong correct it as i have corrected that for(int j=2;j*j<=num;++j)
that is "<=" should be used in place of "<" otherwise on input 9,25etc.it will show prime which is wrong
Related
This Code works properly for numbers upto 4 but then prints wrong or sometimes both, "Number is Prime" and "not Prime".
package timepass;
import java.util.Scanner;
public class Timepass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the no :");
int n = sc.nextInt();
if (n==1 || n==0) {
System.out.println("It is not a prime no");
}
else if (n > 1) {
for(int i = 2; i<n; i++) {
if (n % i ==0) {
System.out.println("It is not a prime number");
break;
} else {
System.out.println("It is a prime number");
}
}
}
}
}
There is slight mistake in the logic.
You have to check all the integers from 2 to n-1, if they are factors of n and then make the final verdict.
Have a look at the following implementation:
import java.util.Scanner;
public class Timepass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the no :");
int n = sc.nextInt();
if (n==1 || n==0) {
System.out.println("It is not a prime no");
}
else if (n > 1) {
boolean isPrime = true;
for(int i = 2; i<n; i++) {
if (n % i ==0) {
isPrime = false;
break;
}
}
if(isPrime) {
System.out.println("It is a prime number");
}else{
System.out.println("It is not a prime number");
}
}
}
}
PS: Also search for more efficient logics to check if the number is prime. For example: In the above code, their is no need to iterate from 2 until n-1. You can stop at n/2.
I see the problem.
Hint: a number is prime if there are no factors. Your code is printing "prime" when >>a<< number is not a factor.
Look at the example 5 and your loop.
2: not a factor, print "It is a prime number"
3: not a factor, print "It is a prime number"
4: not a factor, print "It is a prime number"
When can you as a human tell that it is a prime number? Surely not already at 2.
(Actually you can at 3, but your loop condition is inefficient....)
So why do you print already? You should not.
Look at 9:
2: not a factor, print "It is a prime number"
3: is a factor, print "It is not a prime number"; break, stop looping
Again, at 2 you do not know yet but print anyway; at three you know and stop.
The solution is to print in all cases only when leaving the loop. You do so correctly before the break for "not prime". But you print several times for "prime", possibly wrongly and possibly later again for "not prime".
The point to print "prime" is after going through all of the loop without finding a factor.
Make sure that you do not do that printing after leaving the loop with break for "not prime". You can do so by introducing a function which does the prime check and returns a value indicating the result. That function can return where you currently break and after the loop. Then print the result text from the calling code, based on the return value.
You should be using a flag variable in order to check the number whether it is prime or not. The problem with your case is that everytime it check if the number is divisible by i and if this condition becomes false then it goes to the else condition and prints 'not prime' and this is wrong the program should wait for the loop to end and then it should print any result.
So use a flag variable, initialize it false and if the number is divisible by any value of i then make the value of flag true and break out of loop.
After the loop check for flag variable and if the variable is true print not prime else prime .
//you can use flag instead of printing the massage inside the for loop
// if flag is true means the number is not a prime number
boolean flag = false;
for(int i =2; i< n; i++){
if(n % i ==0){
flag = true;
break;
}
}
if (flag) {
System.out.println("It is not a prime number");
} else {
System.out.println("It is a prime number");
}
import java.util.Scanner;
class Timepass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the no :");
int n = sc.nextInt();
if (n==1 || n==0) {
System.out.println("It is not a prime no");
}
else if (n > 1) {
for(int i = 2; i<n; i++) {
if (n % i ==0) {
System.out.println("It is not a prime number");
break;
} else {
System.out.println("It is a prime number");
break;
}
}
}
}
}
I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}
The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:
some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)
Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}
This is what I am supposed to do:
Write a Java program that will compute the factorial of some numbers n (input from the user, accept only range 1 - 10). For each valid number in input, the output should be the value of n!. Your program should use a loop, to allow the user to input more than one number (count-controlled or sentinel-controlled, your choice)
This is what I have at the moment:
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int num, result = 1;
String str;
System.out.print("Do you want to start? (y/n) ");
str = console.next();
System.out.println();
while(str.charAt(0) == 'y')
{
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
if(num < 1 || num > 10)
{
System.out.print("NUMBER OUT OF RANGE!");
num = console.nextInt();
}
else
{
int i = 2;
while(i <= num)
{
result = result * i;
i++;
}
System.out.println(num + "! = " + result);
System.out.println();
System.out.print("Do you want to continue? ");
str = console.next();
}
System.out.println();
}
}
But this is my result:
Do you want to start? (y/n) y
Enter an integer (1 - 10): 1
1! = 1
Do you want to continue? y
Enter an integer (1 - 10): 2
2! = 2
Do you want to continue? y
Enter an integer (1 - 10): 3
3! = 12
Do you want to continue? y
Enter an integer (1 - 10): 4
4! = 288
I can't get the output to display the right results, that is the only problem I am having with my program. Also, it shows the correct result the first time you are asked to enter an integer, but after that, everything goes wrong
Try this code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String str;
System.out.print("Do you want to start? (y/n) ");
str = console.next();
System.out.println();
int num, result;
while (str.charAt(0) == 'y') {
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
while (num < 1 || num > 10) {
System.out.println("NUMBER OUT OF RANGE!");
System.out.print("Enter an integer (1 - 10): ");
num = console.nextInt();
}
int i = 2;
result = 1;
while (i <= num) {
result = result * i;
i++;
}
System.out.println(num + "! = " + result);
System.out.println();
System.out.print("Do you want to continue? ");
str = console.next();
System.out.println();
}
}
}
You need to set result = 1 inside your outer while loop, not before it. What's happening here is that the numbers you're multiplying are getting multiplied by the result from the previous iteration of the outer while loop.
You are not resetting the result when you iterate for a new value.
Just reset the result to 1 before you start calculating factorial
e.g. -
while(str.charAt(0) == 'y')
{
result =1;
I think you're having a logical error with your if statement. Having a range of 1-10, your if statement should look something like this:
if(userInput>0 && userInput<=10);
Also, as what David Wallace has stated, you need to re-initialize your variable i back to 1 after your inner "factorial while loop" finishes. In this way, your variable i would always have the starting value of 1 whenever it enters your inner factorial while loop.
I would begin by creating a lookup table for the valid range of factorials. That might be done iteratively, create a fact array and fill it. Something like,
int[] fact = new int[10];
int i;
fact[0] = i = 1;
while (i < fact.length) {
fact[i] = (i + 1) * fact[i - 1];
i++;
}
Then you can use an infinite loop with your Scanner (breaking on non-integer input) and the fact lookup table like,
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter a number 1-10 for the factorial (or a "
+ "non-number to quit): ");
if (!scan.hasNextInt()) {
break;
}
i = scan.nextInt();
if (i < 1 || i > 10) {
System.out.println("NUMBER OUT OF RANGE!");
continue;
}
System.out.printf("%d! = %d%n", i, fact[i - 1]);
}
I can run this code perfectly, but it's not running as intended. I tried to make a isPrime Method, but I keep getting an error where I get multiple responses instead of the intended single response.
For example, if I put in the number 3, I'll get the response:
[number] isn't prime.
[number] is prime.
If I put the number 100, I'll get the response:
[number] isn't prime.
[number] isn't prime.
[number] isn't prime.
...
[number] is prime.
I'll get the "isn't prime." response 99 times and the 100th response will be "is prime." Every once in a while the response "is prime" will show up.
Could anyone let me know what's messing it up?
import java.util.Scanner;
public class Chapter_8_13 {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("This program helps determine if a number is prime!");
System.out.println("Enter a number: ");
int num = keyboard.nextInt();
for (int i = 2; i <= num; i++)
{
if (num % i == 0)
{
System.out.println(num + " is prime.");
}
else
{
System.out.println(num + " isn't prime.");
}
}
}
}
You set a flag when num is divisible by any i. Then check the value of flag outside loop to find if its prime or not
flag=0;
for (int i = 2; i < num; i++)
{
if (num % i == 0)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println(num + " is prime.");
else
System.out.println(num + " isn't prime.");
NOTE: You need not loop num times. sqrt(num) is enough.
Actually, your algorithm is wrong. Condition if (num % i == 0) says only that num divides by i (and num is not prime).
It should be:
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++)
{
if (num % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("is prime");
} else {
System.out.println("isn't prime");
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out
.println("This program helps determine if a number is prime!");
System.out.println("Enter a number: ");
int num = keyboard.nextInt();
boolean isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
System.out.println(num + " isn't prime.");
break;
}
}
if (isPrime)
System.out.println(num + " is prime.");
}
}
I have to write a program which asks a user to input integers, but they have to be positive.
I'm pretty sure I have to use a loop, and don't think I'm allowed to use Math.abs().
What I've written right now looks quite messy though. Here is the code:
public class Q1{
public static void main(String[] args){
int num1, num2, num3;
while(true){
System.out.println("Input first integer.");
num1 = TextIO.getInt();
if(num1 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input second integer.");
num2 = TextIO.getInt();
if(num2 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input third integer.");
num3 = TextIO.getInt();
if(num3 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
....
}
}
I've basically just done separate while loops for each integer to test if the integer is positive because when I use one loop I can't get it to run properly. Is there a way of just using one loop that will still work but looks much neater?
You can move that loop inside another method:
public int readPositiveInt() {
int num = 0;
int attempt = 0;
int maxAttempt = 3;
// Allow only maxAttempt to enter correct input.
while(true && attempt < maxAttempt) {
num = TextIO.getInt();
if(num > 0)
break;
System.out.println("Integer isn't positive. Try again");
++attempt;
}
return num;
}
And then call this method where ever you are having a loop currently.
Make sure TextIO, whatever it is, is available to this method.
Also, you should better enforce a maximum number of attempt, as you might go into an infinite loop, if user keeps on entering negative numbers.
You can wrap your while loop inside a for loop and put your integers in an array:
int[] nums = new int[] {-1, -1, -1};
for (int i = 0; i < 3; i++) {
while(nums[i] <= 0)
nums[i] = TextIO.getInt();
}
When programming you try and achieve 3 objectives: making your code, readable, intuitive and maintainable.
I would suggest you create a method you can reuse. The method in your case would look something like this:
public int readPositiveInt(String message) {
int num = 0;
boolean exitLoop = false;
while(!exitLoop){
System.out.println(message);
num = TextIO.getInt();
if(num > 0) {
exitLoop = true;
// I don't like to break from a while(true), I personally find it messy
}
else {
System.out.println("Integer isn't positive. Try again");
}
}
return num;
}
Instead of creating variables like, num1, num2, num3 ... simply create an int array and store all values in there. If you are not sure how many numbers you would like to store, I suggest you use an implementation of a List, like the ArrayList.
I hope this helps.
Something like this perhaps?
public class Q1{
public static void main(String[] args){
int[] input_integers = new int[3]; //create an array of however many integers you need
int i = 0; // initiate your counter
while(i<input_integers.length){ // you will loop through until all integers are set
System.out.println("Input integer number "+ (1+i)); // computers count from 0, humans from 1
input_integers[i] = TextIO.getInt();
if(input_integers[i] < 0) // check if it is not positive
System.out.println("Integer isn't positive. Try again");
else { // if it is, increment your counter and get the next integer
i++;
}
}
}
}
Hope this helps
** This code was not tested
Here is a solution with a single while loop and using no array(it can be done). But, you can see that it's not upto the expectation. Such an implementation is always inefficient and is discouraged. So better use an array or separate method like others are suggesting.
int i=0;
while (i < 3) {
int tmp = 0;
switch (i) {
case 0:
num1 = tmp = TextIO.getInt();
System.out.println("Input first integer.");
break;
case 1:
num2 = tmp = TextIO.getInt();
System.out.println("Input second integer.");
break;
case 2:
num3 = tmp = TextIO.getInt();
System.out.println("Input Third integer.");
break;
}
if (tmp < 0) {
System.out.println("Integer isn't positive. Try again");
} else {
i++;
}
}