Prime numbers with input from keyboard - java

I'm supposed to write a program in java, that allows the user to determine number (quantity) of prime numbers, that he wants to be displayed.
I have managed to write a program, in which user can specify the maximum prime number.
Can I please have some tips?
import java.util.Scanner;
public class PrimeNumbers{
public static void main(String[] agrs){
int max;
Scanner sk = new Scanner(System.in);
System.out.print("How many prime numbers you want to display? ");
max = sk.nextInt();
System.out.print("Prime numbers: ");
for(int x =2; x <= max; x++){
boolean isPrime = true;
for(int y = 2; y < x; y++){
if(x % y == 0){
isPrime = false;
break;
}
}if (isPrime){
System.out.print(x + " ");
}
} System.out.print("...");
}
}
If i.e I put as a user 5, I get only 2,3, 5
But I want the result to be: 2, 3, 5, 7, 11

Track the number of primes you have printed, which is not x. Check whether you have printed enough.
import java.util.Scanner;
public class PrimeNumbers{ public static void main(String[] agrs){
int max;
int numPrinted=0;
Scanner sk = new Scanner(System.in);
System.out.print("How many prime numbers you want to display? ");
max = sk.nextInt();
System.out.print("Prime numbers: ");
for(int x =2; numPrinted < max; x++){
boolean isPrime = true;
for(int y = 2; y < x; y++){
if(x % y == 0){
isPrime = false;
break;
}
}if (isPrime){
System.out.print(x + " ");
numPrinted++;
}
} System.out.print("...");
} }

Related

I need to display prime numbers within a range using min. of 1 while & for loop. And getting the wrong output

import java.util.Scanner;
public class PrimeN {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
while (a < b) {
for (int i = a; i <= b; i++) {
int count = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
} //count if equals 2 the prime numbers displayed
if (count == 2) {
System.out.println(i);
a++;
}
}
}
}
}
This is what my output looks like. I dont understand why last prime numbers are being repeatedly printed.
What you should probably do is breaking task into steps.
Get the input
satrt finding the prime numbers from 1 to the max
create a list of already found prime numbers
start a loop from 1 to max
each iteration loop trough already found primes and perform number % prime == 0
if none of numbers in prime numbers can fulfils the condition add number to the list
if found number is greater or equal to min, save the index of it (startIndex).
print the input by iterating trough list from startIndex and printing the numbers
this workflow guarantees you will not consider multiplicant of two big prime numbers as prime number with better performance
You missplaced your first statement, your while-loop is a little bit scary, but here your fix:
import java.util.Scanner;
public class PrimeN{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int a,b;
a = sc.nextInt();
b = sc.nextInt();
for(int i = a; i <= b; i++){
int count = 0;
for(int j = 1; j <= i; j++){
if(i%j == 0){
count++;
}
}//count if equals 2 the prime numbers displayed
if(count == 2){
System.out.println(i);a++;
}}}}
Found a way to solve the ques.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
for(int n = a; n <= b; n++){
boolean prime = true;
int i = 2; //1 will be a factor always
while(i <= n/2){
if(n%i == 0){
//is not prime
prime = false;
break;
}i++;
}
if(prime){
System.out.print(n+ " ");
}
}}}
Just remove your while(a<b) around the two for loops and then your code works fine
like this
import java.util.Scanner;
public class PrimeN {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int a, b;
a = sc.nextInt();
b = sc.nextInt();
// System.out.println("a<b");
int i = a;
while(i<=b)
{
int count = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
count++;
}
} // count if equals 2 the prime numbers displayed
if (count == 2) {
System.out.println("a" + a + " i:" + i);
a++;
}
i++;
}
}
}
To find out what the actual error is, print out the values of a,b,i and j in each iteration.

How to initialize variable back to 0 in a while loop in java?

I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}

How to quit scanner when input is negative?

This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.
You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}

Building a lotto machine using java. Program Doesn't function if same number is chosen more then once

I am trying to build a lotto machine using java. This is the code:
import java.util.Scanner;
import java.util.Random;
import java.util.Random;
public class wissam {
public static void main(String[] args) {
int counter = 0;
int[] lottoNumbers = new int[6];
for (int x = 0; x < lottoNumbers.length; x++) {
Random rand = new Random();
lottoNumbers[x] = rand.nextInt(42) + 1;
}
int[] userChoice = new int[6];
System.out.println("Enter a number");
Scanner scan = new Scanner(System.in);
userChoice[0] = scan.nextInt();
for (int y = 1; y < userChoice.length; y++) {
System.out.println("Enter another number");
userChoice[y] = scan.nextInt();
}
for (int x = 0; x < lottoNumbers.length; x++) {
System.out.print(lottoNumbers[x] + " ");
}
System.out.println("");
for (int z = 0; z < userChoice.length; z++) {
for (int a = 0; a < lottoNumbers.length; a++) {
if (lottoNumbers[z] == userChoice[a]) {
counter++;
int b = lottoNumbers[z];
System.out.print("The common numbers were" + b + "");
}
}
}
if (counter == 0) {
System.out.println("You are such a loser");
}
}
}
It asks the user to input 6 numbers and works fine, as long as the user chooses 6 distinct numbers between 1 and 42.
I want to check if the user inputs distinct numbers that are between 1 and 42, and if they aren't I want to ask the user to change the number. How do I do that?
I would not use an array. I would use a Set. It has the function 'contains'. So whenever the users gives another number, you can check if the Set so far already contains the number.
I would do it this way
public static void main(String[] args) {
final ArrayList<Integer> userChoice = new ArrayList<>(6);
// Scan numbers
Scanner scan = new Scanner(System.in);
while (userChoice.size() < 6) {
System.out.println("Enter a number");
int choice = scan.nextInt();
if (choice < 1 || choice > 42) {
System.out.println("Number not between 1 and 42");
continue;
}
if (userChoice.contains(choice)) {
System.out.println("Number already chosen");
continue;
}
userChoice.add(choice);
}
System.out.println("You have chosen: " + userChoice);
}
Considering that you're almost there, the simplest case would be to create nested loops and before you store the number, check that it's not already within the array.
for (int y = 1; y < userChoice.length; y++) {
System.out.println("Enter another number");
boolean flag = false;
int result = scan.nextInt();
if(result < 1 || result > 42){
System.out.println("please enter a number between 1 - 42 inclusive");
y--;
continue;
}
for(int i = 1; i < userChoice.length; i++){
if(result == userChoice[i]){
flag = true;
break;
}
}
if(flag){
System.out.println("Enter a different number");
y--;
}else{
userChoice[y] = result;
}
}

Three consecutive numbers in a while loop

Write a program that reads integers from the user until he enters -1, and print “Consecutive ” if there are three consecutive numbers otherwise print “None Consecutive”; that is in the number list you read are in an order such that there is some integer k that the numbers values are k, k+1, and k+2.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
x = scan.nextInt();
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
Can anyone please tell me what's wrong with this code?
Get the next integer before checking with y, then check for z. if one of these fails update y and z and check again.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
x = scan.nextInt();
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
y = x + 1;
z = x + 2;
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
You need to increment y and z by 1 before scaning new x.
This is what you are looking for:
Scanner scan = new Scanner(System.in);
System.out.println("enter");
int x = scan.nextInt();
boolean areConsecutive = false;
while (x != -1) {
int y = x + 1;
System.out.println("enter");
x = scan.nextInt();
if (x == y) {
System.out.println("enter");
int z = x + 1;
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
}
if (areConsecutive)
System.out.println("Consecutive");
else
System.out.println("None Consecutive");
You're close but you're not maintaining the history of the numbers correctly.
First, to clarify, the specification calls for you to enter an arbitrary quantity of arbitrary numbers from the user and simply check if any three of them are consecutive. Hence the first line below would have a consecutive sequence (the 1 2 3 bit starting at the third number) but the second would not:
9 9 1 2 3 9
3 1 4 1 5 9
One way to do this is simply maintain the minimal information to detect a consecutive sequence. To do that, you need to keep a copy of only the last three numbers entered. The pseudo-code (easily transformable into any procedural language) for such a beast would be:
# Get first number, ensure no chance of consecutive
# sequence until at least three are entered.
num3 = getint()
num2 = num3
num1 = num3
consecutive = false
# Loop until -1 entered.
while num3 != -1:
# Check for consecutive sequence.
if (num1 + 1 == num2) and (num2 + 1 == num3):
consecutive = true
# Shift numbers "left".
num1 = num2
num2 = num3
num3 = getint()
if consecutive:
print "Consecutive"
else
print "None Consecutive"
This is what you are looking for:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
boolean areConsecutive = false;
while ((x != -1)&&(y != -1)&&(z != -1)){
if ((z == y + 1)&&(y == x + 1)
areConsecutive = true;
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
I would do it this way, we have to check if three numbers are consecutive no matter the order they were entered by user:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] numbers = new int[3];
for( int i = 0; i < numbers.length; ++i)
numbers[i] = scan.nextInt();
Arrays.sort(numbers);
boolean areConsecutive = true;
for( int i = 0; i < numbers.length - 1; ++i)
if(numbers[i+1] - numbers[i] != 1)
areConsecutive = false;
if(areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}

Categories

Resources