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 have a question about a problem. I'm a beginner at this so I appreciate your help!
The code should ask for two user input numbers, and will print out in the console all the prime numbers between these two.
Here is the code I got until now: (It's not checking the numbers between these two, only printing out the one number if it's a prime. )
package questionsAndAnswers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Number {
static boolean primes;
public static boolean number( ) {
try {
for (int i = 0; i < 2; i++) {
BufferedReader br = new BufferedReader(new InputStreamReader System.in));
String num1 = br.readLine();
String num2 = br.readLine();
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt(num2);
for (int j = number1; j < number2; j++) {
if ( (j % 2) == 0 ) return true;
for (int k = 3; (k*k) <= j; k+=2) {
if(j % k == 0) {
return false;
}
System.out.println("All the primes b/n number " + number1 + " and number" + number2 + " are :" + j );
return true;
}
System.out.println(primes);
// br.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return primes;
}
}
...and in the main class :
public class TwoWholeNumbers {
public static void main(String[] args) {
System.out.println("Enter two integer numbers to see what is the multitude b/w them: ");
Number.number();
}
}
You have copy pasted code from some place. Issue is you are breaking after first value.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Number {
static boolean primes;
public static boolean number() {
try {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 2; i++) {
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String num1 = br.readLine();
String num2 = br.readLine();
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt(num2);
for (int j = number1; j < number2; j++) {
if ( (j % 2) == 0 ) {
continue;
}
int x=0;
for (int k = 3; (k*k) <= j; k+=2) {
if(j % k == 0) {
x=1;
break;
}
}
if(x==1) continue;
buffer.append(j + " ");
}
System.out.println("All the primes b/n number "
+ number1 + " and number" + number2 + " are :"
+ buffer.toString() );
}
} catch (IOException e) {
e.printStackTrace();
}
return primes;
}
public static void main(String[] args) {
System.out.println("Enter two integer numbers to see what "
+ "is the multitude b/w them: ");
Number.number();
}
}
My fastest way to check if number is prime:
boolean isPrime(int p) {
int m = (int) Math.sqrt(p);
if(m<2) {
return true;
}else {
for(int i = 2;i++;i<=m) {
if((p % i)==0) {
return false;
}
}
}
return true;
}
You have given return in the number() method instead of break and continue. number() method is not called in a loop in the main() that you need to return for each iteration. Also the boolean return simply doesn't make sense.
I'll show you a few changes you need to do, which will make the program print out a few numbers. But that doesn't mean its the correct output. The logic for prime numbers is highly faulty. You'll have to fix that. I'm just helping you solve the basic problem of why you don't get any output.
for (int j = number1; j < number2; j++) {
if ((j % 2) == 0)
continue; // return true replaced by continue
for (int k = 3; (k * k) <= j; k += 2) {
if (j % k == 0) {
break; // return false replaced by break
}
System.out.println("All the primes b/n number "
+ number1 + " and number" + number2 + " are :"
+ j);
}
}
I've given the break and continue to avoid return statements, but in reality, the logic really needs a makeover.
Related
I'm doing and exercise for college and for some reason, the second for index is not increasing and when I the console recive a new input with a different number it doens't count.
Sorry for any grammar mistakes
import javax.swing.JOptionPane;
import java.util.*;
public class Atividade999 {
public static void main(String[] args) {
ArrayList<Integer> valor = new ArrayList<>();
int num2 = 0;
int cont = 0;
int rcont = 0;
int num = Integer.parseInt(JOptionPane.showInputDialog("Informe a frequencia: "));
for (int i = 0;i < num; i++)
{
num2 = Integer.parseInt(JOptionPane.showInputDialog("Informe o valor: "));
valor.add(num2);
for (int j = 0; j < num; j++){
boolean igual = false;
if(Objects.equals(valor.get(i), valor.get(j))){
igual = true;
}
if(igual != false){
cont++;
System.out.println("Numero "+num2+" "+cont+" X");
}
if(igual == false){
cont=1;
System.out.println("Numero "+num2+" "+cont+" X");
}
break;
}
}
System.out.println("A lista completa: " + valor);
}
}
Here is some pseudocode (NOT FULL) that may be helpful to "count a frequency of a number in arraylist"
int runningCount = 0;
for(the list of numbers)
{
if(it is the number)
{
runningCount++;
}
System.out.println("Numero " + num2 + " " + runningCount + " X");
}
frequency = runningCount / total numbers;
EDIT for clarification: this would be in place of the giant chunk that has
if(it is equal) set to true;
if(it is not false) doThis;
if(it is false) doThat;
In fact, when you trigger the false condition, it currently resets the count with cont=1, regardless of how many there already were.
I was making an Armstrong number checker not for only 3 digits numbers for which I used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code:
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new
Scanner(System.in);
int num = sc.nextInt();
int numc = num ;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = 0;
while(num != 0){
rem = num%10;
while(numc != 0){
numc /=10;
int i = 0;
i++;
val2 += i;
}
cu = Math.pow(rem,val2 );
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a "+val2+" Armstrong number because its returning " + val+"after Calculations ");
}
else{
System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
}
}
}
///////////////////////////////////////////
And this is the Compilation of my code:
if(val == numc){ - This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.
So I would suggest to assign the input from the user to another variable which you can use for checking the final if - else part.
Like int input = num and at the end if(val==input){ . This would resolve your issue.
The num and numc become zero due to "/= 10" operation. Hence the if condition fails.
Also you need not compute the length of integer every time.
Don't have the reputation to comment hence giving a full fledged solution.
Following is my solution to your problem.
All the best!
import java.util.Scanner;
import java.lang.Math;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("Hello world!\n");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
double rem = 0;
double cu = 0;
int val = 0;
int val2 = countNumOfDigits(num);
while (num != 0) {
rem = num % 10;
cu = Math.pow(rem, val2);
val += cu;
num /= 10;
}
if (val == numc) {
System.out.println("Yes its a " + val2 + " digit Armstrong number because its returning " + val
+ "after Calculations ");
} else {
System.out.println("No its not a " + val2 + " digit Armstrong number because its returning " + val
+ " after Calculations ");
}
}
private static int countNumOfDigits(int number) {
if (number < 100000) {
if (number < 100) {
if (number < 10) {
return 1;
} else {
return 2;
}
} else {
if (number < 1000) {
return 3;
} else {
if (number < 10000) {
return 4;
} else {
return 5;
}
}
}
} else {
if (number < 10000000) {
if (number < 1000000) {
return 6;
} else {
return 7;
}
} else {
if (number < 100000000) {
return 8;
} else {
if (number < 1000000000) {
return 9;
} else {
return 10;
}
}
}
}
}
}
This program checks if a user's input number is prime.
My problem is in the if statement. For some reason the Boolean is never switched. If the number is prime, it will just give both results.
What am I missing?
import java.util.Scanner;
public class Prime
{
public static void main(String[] args)
{
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean more = true;
do
{
for (int i = 2; i <= n; i++)
{
if (n <=1 || n%i==0)
{
System.out.println(n + " is not prime");
more = false;
}
}
}
while (more);
System.out.println(n + " is prime");
}
}
Remove the print which is inside if() and use the below code after the do while loop
if(more)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
and also you dont need a do while loop remove it.Complete Code
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System. in );
int n = kb.nextInt();
boolean more = true;
for (int i = 2; i <= n / 2; i++) {
if (n <= 1 || n % i == 0) {
more = false;
break;
}
}
if (more) System.out.println(n + " is prime");
else System.out.println(n + " is not prime");
Demo
It's possible to check prime numbers with few lines using a for loop. It's better for performance.
Code to check prime numbers:
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
Full class according to your example:
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
for (int i = 2; i < n && isPrime; i++) {
isPrime = !(n % i == 0);
}
System.out.println(n + " is prime - " + isPrime);
}
}
Try this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean prime = true;
for (int i = 2; i <n; i++)
{
if (n <=1 || n%i==0)
{
prime = false;
break;
}
}
if(prime)
{
System.out.println(n + " is prime");
}
else
{
System.out.println("Not prime");
}
}
The following logic is working. Please try this.
int count=0;
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
count=1;
break;
}
}
if (count==0)
System.out.println(i+" is a prime number.");
else
System.out.println(i+" is not a prime number.");
If the count got increased, the given number is divisible by some other numbers. Or else It should be a prime number.
Thank you...
You don't need to check all the way up to n, just up to the square root. which if you calculate before should make your loop take less iterations and be faster.
Try this code with simple for loop.
boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
Try this:
System.out.println("Enter a number to check if it is prime:");
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
boolean isPrime = true;
if (n < 1)
isPrime = false;
else
for(int i = 2; 2 * i < n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println( n + " is " + (isPrime? "" : "not ") + "prime");
How can I add a statement that allows me to check if the credit card number inputted by the user is a palindrome? I am checking for the appropriate length already so how can i Input the new palindrome checker into this code:
import java.util.Scanner;
public class DT18 {
public static void main(String[] args) {
String number;
Boolean debug = false;
if (args.length == 0) { // no command line
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a Credit Card number to validate.");
number = keyboard.next();
} else { // command line input
number = args[0];
}
if (debug) System.out.println("String Length " + number.length());
if (number.length() < 10) {
System.out.println("Not Valid");
}
int sum = 0;
int oddDigit = 0;
for (int i = number.length() - 1; i >= 0; i--) {
if (debug) System.out.println("i = " + i);
if ((Character.getNumericValue(number.charAt(i)) < 0) || (Character.getNumericValue(number.charAt(i)) > 9)) {
System.out.println("Not Valid");
break;
}
if (i % 2 == 0) { //Even Digit
sum += Character.getNumericValue(number.charAt(i));
} else { //Odd Digit
oddDigit = (2 * Character.getNumericValue(number.charAt(i)));
if (oddDigit > 9) oddDigit = (oddDigit % 10) + 1;
sum += oddDigit;
}
if (debug) System.out.println(sum);
}
if (sum % 10 == 0) {
System.out.println("Valid");
} else {
System.out.println("Not Valid");
}
}
}
From an answer I once gave here:
public boolean isPalindrom(int n) {
return new StringBuilder("" + n).reverse().toString().equals("" + n);
}
This post should give you for loop logic:
http://www.programmingsimplified.com/java/source-code/java-program-check-palindrome
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
You can write a simple function to check if a string is a palindrome or not.
private static boolean checkPalindrome(String input) {
int i = 0, j = input.length() - 1;
for (; i < j; i++) {
if (i == j) {
return true;
}
if (input.charAt(i) == input.charAt(j)) {
j--;
}
else
return false;
}
return true;
}
This is a crude method; you may want to modify it according to your requirement, but it will get the job done in most of the cases.
I've looked over the other answers and all of them have bad performance and working with String instead of just using the given number. So I'll add the version without conversion to String:
public static boolean isPalindrome(int n) {
int[] digits = new int[length(n)];
for (int i = 0; n != 0; ++i) {
digits[i] = n % 10;
n /= 10;
}
for (int i = 0; i < digits.length / 2; ++i) {
if (digits[i] != digits[digits.length - i - 1]) {
return false;
}
}
return true;
}
public static int length(int n) {
int len = 0;
while (n != 0) {
++len;
n /= 10;
}
return len;
}
Not sure, if that's the best implementation, but I got rid of Strings :-)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
It is an algoritm class and i would like to get the output of this program when n = 8
import java.io.*;
public class Algorithm
{
public static void main(String args[])
{
int i,j,n;
String s = in.readLine();
n = Integer.parseInt(s);
i = 2;
while( i<= n)
{
for(j=1; j<= n/2; j++)
System.out.println(i + " "+j)
System.out.println(i + " " +j);
i = i+2;
}
for (j =0; j<= i ; j+=4)
System.out.println(" "+j);
}
}
Try like this:
import java.util.Scanner;
public class Algorithm {
public static void main(final String args[]) {
int i, j, n;
final Scanner scanner = new Scanner(System.in);
try {
String s = scanner.nextLine();
n = Integer.parseInt(s);
i = 2;
while (i <= n) {
for (j = 1; j <= n / 2; j++) {
System.out.println(i + " " + j);
}
System.out.println(i + " " + j);
i = i + 2;
}
for (j = 0; j <= i; j += 4) {
System.out.println(" " + j);
}
} finally {
scanner.close();
}
}
}
This should work:
import java.io.*;
public class Algorithm
{
public static void main(String args[])
{
int i,j,n;
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
n = Integer.parseInt(s);
i = 2;
while( i<= n)
{
for(j=1; j<= n/2; j++)
System.out.println(i + " "+j)
System.out.println(i + " " +j);
i = i+2;
}
for (j =0; j<= i ; j+=4)
System.out.println(" "+j);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(in != null)
{
try
{
in.close();
}
catch(IOException e) {}
}
}
}
}