I have written a small program that takes user input, n (int), and calculates every prime number up to n, using a loop in a loop. If the user inputs forexample 85023, it will be a very long series of numbers. How do i make the output break every 10th number? this would make the output alot more proffesional and neat to look at.
Relevant code:
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
// Append prime numbers to string
primeNumbers = primeNumbers + i + " ";
}
}
// Print Number
System.out.println("Primtallene fra 1 til " + n + " er: ");
System.out.println(primeNumbers);
}
You could have a separate counter which counts the number of prime numbers you have currently found, like this:
int primeCount = 0;
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
// Append prime numbers to string
primeNumbers = primeNumbers + i + " ";
// Increment prime counter
primeCount++;
// If 10 primes have been printed then add new line and reset counter
if ((primeCount % 10) == 0) {
primeNumbers += "\n";
}
}
}
// Print Number
System.out.println("Primtallene fra 1 til " + n + " er: ");
System.out.println(primeNumbers);
}
\n is the newline character, hope this helps.
Related
Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and
7 are twin primes, and 11 and 13 are twin primes. Write a Java program TwinPrimes.java that prompts
the user to input the search range of twin primes, display all the twin primes (2 pairs per line) within
the range, and print the number of twin primes found. The search range is assumed to be positive and
your program should repeatedly perform the same task until a sentinel value of -1 is entered.
The expected output of your program should be as follows:
Round 1:
Enter the search range: 100
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
Number of twin primes less than or equal to 100 is 8
Round 2:
Enter the search range: 150
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
......(Omitted)
Number of twin primes less than or equal to 200 is 15
Round 4:
Enter the search range: -1
End
I know that I am not complected the code, but I am struggling on how to print the Prime numbers in ( , ) ( , )way and how to calculate the number of twin primes show it at the end.
The below coding is what I had to do:
import java.util.Scanner;
import java.util.Random;
public class TwinPrimes {
public static void main(String[] args) {
int i = 0;
int A, B = 0, D = 0;
int num = 0;
System.out.println("Round" + " " + ++i + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
A = scn.nextInt();
{
if (A < 0)
System.out.println("End");
}
for (i = 3; i <= A; i++) {
int counter = 0;
for (num = B; num >= 1; num--) {
{
if (B % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
}
}
System.out.println("(" + i + "," + i + ")" + " " + "(" + i + "," + i + ")");
// sum Number of twin primes to
System.out.println("Number of twin primes less than or equal to " + A + " " + "is" + " ");
return;
}
}
}
package array1;
import java.io.IOException;
import java.util.Scanner;
public class Mainclass {
public static void main(String args[]) throws NumberFormatException, IOException
{
int a,k=0,line=0,count=0;
while(true)
{
System.out.println("Round" + " " + ++k + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
a= scn.nextInt();
{
if (a< 0)
{
System.out.println("End");
System.exit(0);
}
}
System.out.println("The Twin Prime Numbers within the given range are : ");
for(int i=2; i<=(a-2); i++)
{
if(isPrime(i) == true && isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
line++;
if(line==2)
{
System.out.println();
line=0;
}
count++;
}
}
System.out.println();
System.out.println("the number of twin prime numbers less than or equal to"+a+"is"+count);
}
}
static boolean isPrime(int n) //funton for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
}
I am struggling on how to print the Prime numbers in ( , ) ( , ) way
You may use String.format. See How to use String.format in Java?
For example, String.format("Found pair (%d,%d)", prime1, prime2);
How to calculate the number of twin primes show it at the end.
Simply keep a counter, say int counter when you're looking for the prime pairs.
import java.util.Scanner;
public class Main {
// Consider writing a helper function to check primality
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int max_number = 100;
int counter = 0; // keep a count
for (int i = 2; i+2 < max_number; i++) {
if (isPrime(i) && isPrime(i+2)) {
counter++; // increment counter
String msg = String.format("Found pair (%d,%d)", i, i+2);
System.out.println(msg);
}
}
System.out.println("Total number of pairs is " + counter);
// Total number of pairs is 8
}
}
I have an issue. My lecturer wants me to make a loop, with an input of JOptionPane and an output of console. How can I use loop for JOptionPane and send an output through console.
Here's my code:
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
String a1 = JOptionPane.showInputDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++){
int a = Integer.parseInt(a1);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
I would try using a DO-WHILE loop with and an int[], example:
int size = 10;
int count = 0;
int[] yourNumbers = new int[size];
do {
yourNumbers[count] = Integer.parseInt(JOptionPane.showInputDialog(null,
"Your message here."));
count++;
} while (count < 10);
This way you can loop through and grab all the numbers. Then you can use a FOR-LOOP to cycle through and print what you need
System.out.println("Even Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 == 0) {
System.out.println(yourNumbers[i]);
}
}
System.out.println("Odd Numbers are: ");
for(int i = 0; i < yourNumbers.length; i++) {
if (yourNumbers[i] % 2 != 0) {
System.out.println(yourNumbers[i]);
}
}
The problem with your current code is that you only ask the user one time to input a number but you actually seem to want 10 values. So you parse ten times the same value.
The solution is simple, put the dialog inside the loop (only changed the lines with comments):
int even = 0;
int odd = 0;
int e_e = 0;
int o_o = 0;
// No return type, just a message
JOptionPane.showMessageDialog(null, "Type in 10 integer");
for (int counter = 0; counter < 10; counter++) {
// Dialog inside the loop, asking to
// input a number in every iteration
String value = JOptionPane.showInputDialog(null, "Type in "
+ (counter + 1) + ". value");
int a = Integer.parseInt(value);
if (a % 2 == 0) {
even++;
e_e += a;
} else {
odd++;
o_o += a;
}
}
System.out.println("\n\nNumber of even numbers : " + even);
System.out.println("Number of odd numbers : " + odd);
System.out.println("Total of even numbers : " + e_e);
System.out.println("Total of odd numbers : " + o_o);
This code is designed to list off the prime numbers between a minimum and maximum input by the user. When the numbers are output at the end of the code, they are all on the same line. I would like there to be ten numbers per line, so I assume that it takes a loop of some kind to indent every ten numbers, however I don't know how to do this. While I have the code posted here, other, unrelated feedback would be helpful.
String primenumbers = "";
System.out.println("Prime Number Generator.");
System.out.print("Minimum: ");
int oldmin = s.nextInt();
s.nextLine();
int min = oldmin;
System.out.print("Maximum: ");
int max = s.nextInt();
s.nextLine();
System.out.println();
for (min = min; min <= max; min++)
{
int counter=0;
int num = min;
for(num = min; num >= 1; num--)
{
if(min % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
primenumbers = primenumbers +min+ " ";
}
}
System.out.println("Primes Between "+oldmin+" & "+max+":");
System.out.print(primenumbers);
Instead of concatinating prime numbers into a string, you can add them into a list and iterate the list in the end, e.g.:
primenumbers = primenumbers +min+ " "; will be replaced with
List<Integer> primenumbers = new ArrayList<>();
primenumbers.add(min);
After System.out.println("Primes Between "+oldmin+" & "+max+":"); statement, you can do the following:
for(int i=0 ; i < primenumbers.size() ; i++){
System.out.print(primenumbers.get(i) + " ");
if(i+1 % 10 == 0){
System.out.println();
}
}
I'm trying to create a game that rolls 2 set of dice, three times in a row. It has the user guess a number between 2-12 just once. If that one guess matches any of the three rolls he/she wins, otherwise he/she loses. I have another class to display results and I have a counter for how many loops it's been through. It comes out 0 if the user correctly guessed it, otherwise it comes out as 1. I'm guessing the loop just loops once so if anyone can point out what I'm doing wrong to make it so it loops three times(and stopping if the user gets the answer right).
import javax.swing.JOptionPane;
/**
* #author Marcus
*
*/
public class Dice {
int randomDieNum1;//random number generator for dice
int randomDieNum2;//random number generator for dice
private final int MINVALUE1 = 1, //minimum die value
MAXVALUE1 = 6;//maximum die value
private final int MINVALUE2 = 1, //minimum die value
MAXVALUE2 = 6;//maximum die value
int userNum = Integer.parseInt(JOptionPane.showInputDialog(null, "Guess a number between 1-12", "Guess a Number",
JOptionPane.INFORMATION_MESSAGE));//gets user input
String result ; //results
int start = 0 ; //counter to see how many turns were taken
public Dice()
{
for (int i = 1 ; i <= 3; i++)
randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly";
++ start;
}
else if (randomDieNum1 + randomDieNum2 == userNum)
{
result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
}
else
{
result = "You Did not guess the number correctly";
}
}
public String get() //used in another class to display count
{
String temp;
temp = "" + start;
return temp;
}
}
EDIT
Thanks guys. I added both suggestions and added a break to stop the loop after the user gets the answer right.
This is what it looks like:
public Dice()
{
for (int i = 1 ; i <= 3; i++)
{randomDieNum1 = ((int)(Math.random()* 100) % MAXVALUE1 + MINVALUE1);
randomDieNum2 = ((int)(Math.random()* 100) % MAXVALUE2 + MINVALUE2);
int total = randomDieNum1 + randomDieNum2;
if (randomDieNum1 + randomDieNum2 == userNum)
{result = randomDieNum1 + "+" + randomDieNum2 + "=" + total + "\n" +
"You guessed the number correctly";
++ turns; //
break; //stops the loop if condition is meet
}
else if(randomDieNum1 + randomDieNum2 != userNum)
{
result = "You did not guess the \n number correctly\n\n";
++ turns;
}
}
}
Apart from the missing { in for (int i = 1 ; i <= 3; i++) {
You might have to reconsider the logic used in the if condition
if(x+y != c)
{// do operation A}
else if (x+y == c)
{// do operation B}
the else condition after the else-if will never get executed.
This isn't encapsulating everything in the loop
for (int i = 1 ; i <= 3; i++)
You're missing the brackets for encapsulating
for (int i = 1 ; i <= 3; i++) {
}
I am printing the factorial of the first 10 numbers, so it is 0 - 9. The below code works for me. But I am unable to make the loop such that the factorial of 0 is within the loop too. Any advice is appreciated. Thank you.
public class fact {
public static void main(String[] args) {
System.out.println("\n\n(f) Loop to print first 10 factorial numbers");
System.out.println("\nFactorial of 0 is 1");
int fact = 1;
int index = 1;
while (index < 10)
{
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
}
}
How about adding an if condition in your while loop for index 0
int fact = 1;
int index = 0;
while (index < 10)
{
if(index == 0)
System.out.println("\nFactorial of 0 is 1");
else {
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
}
index++;
}
The factorial of 0 is a special case, so you are better off printing it outside the loop, just as you are doing now.
For big n numbers find factorial and its digit count .
import java.util.Scanner;
public class N_Faktorial {
public static void main(String [] args)
{
int u=1,A[]=new int[9999999];
Scanner scan =new Scanner(System.in);
System.out.print("n=");
int n=scan.nextInt();
A[1]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++) {
A[j]*=i;
}
for(int j=1;j<=n;j++)
{
if(A[j]>9)
{
A[j+1]+=A[j]/10;
A[j]%=10;
}
if(A[u+1]!=0) {
u++;
}
}
}
System.out.print(n+"! digit count:"+u+"\\n Result: \\n");
for(int i=u;i>=1;i--)
{
System.out.print(A[i]);
}
}
}
factorialList(10);
public static int factorialList(int indexMax) {
int fact = 1;
if (indexMax > 0) fact = indexMax * factorialList(indexMax - 1);
System.out.println("Factorial of " + indexMax + " is " + fact);
return fact;
}
Fn calls are less effective than loops but I bet it would be optimized to ~ the same on task of this size.
You can do like this
int fact = 1;
int index = 0;
while (index < 10)
{
fact=(index==0)?1:fact*(index);
System.out.println("Factorial of " + index + " is " + fact);
index++;
}