I need the program to run in a loop until 0 is entered. My code will end with 0 entered but when attempting to run the program with numbers entered it still ends the program. instead of running the numbers entered. The while loop is to keep the program running unless a 0 is entered.
import java.util.Scanner;
public class CountCompare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100 (0 to end, 0 < to exit): ");
int[] counts = new int[100];
// Count occurrence of numbers
count(counts);
while(counts[0] > 0){
// Display results
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0)
System.out.println((i + 1) + " occurs " + counts[i] +
" time" + (counts[i] > 1 ? "s" : ""));
}
System.out.print("Enter the integers between 1 and 100 : ");
// Count occurrence of numbers
count(counts);
}
System.out.print("\nEnd of run");
}
/** Method count reads integers between 1 and 100
* and counts the occurrences of each */
public static void count(int[] counts){
Scanner input = new Scanner(System.in);
int num; // holds user input
do {
num = input.nextInt();
if (num >= 1 && num <= 100)
counts[num - 1]++;
} while (num != 0);
}
}
I have posted the entire program.
output looks like this
Enter the integers between 1 and 100 (0 to end, <0 to exit):
23 23 4 5 6 7 8
0
4 occurs 1 time
5 occurs 1 time
6 occurs 1 time
7 occurs 1 time
8 occurs 1 time
23 occurs 2 times
Enter the integers between 1 and 100:
Your program still ends because:
int[] counts = new int[100];
You have defined the limit of the counts here. This means your loop will run
for (int i = 0; i < counts.length; i++)// counts.length=100;
So as far as you code suggest you want to end the user input when user input 0. So you might do this:
int x=1;
int y;
Scanner sc= new Scanner(System.in);
while(x!=0){
System.out.println("Enter your values");
y=sc.nextInt();
if(y==0){
x=0;
}
else{
System.out.println("You entered "+y);
}
int count=new Scanner(System.in).nextInt();
int myarray[]=new int[count];
for(int tmp=0; tmp<count;)
myarray[tmp]=++tmp;
while(count != 0){
for(int inc=1; inc<=count; inc++){
System.out.println(inc + "times occur");
}
System.out.println("Enter 0 to exit");
count=new Scanner(System.in).nextInt();
}
You should take a look at the line
while(counts[0] > 0) {
and try to figure out what is the purpose of this while loop in the main method.
Related
for the task i need to Write a Java application that accepts 30 integer numbers from the user. The input should be in the range of 1-200. Error message needs to be displayed if user entered input which is not in this range. Based on this input, the program will display the number of integers entered in the following categories:
Less than 50
Between 50-100 (inclusive of 50 and 100)
Sample output :
Enter number 4: 211
Input error..Pls enter number between 1 to 200 only
Enter number 4: 20
..
..
Enter number 30: 90
Less than 50: 12
Between 50-100 (inclusive of 50 and 100): 8
Between 101-150 (inclusive of 101 and 150): 5
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
// a.Declare an array to hold 5 Integer values
int list[] = new int[5];
int i = 0;
System.out.print("\n\tInput numbers from 1 to 200: \n");
while (i < 5) {
// b.Fill the array with intgers from the keyboard(range: 1 to 200).
System.out.print("Enter Integer" + (i + 1) + ":");
int value = kbin.nextInt();
if (value >= 1 && value <= 200) {
list[i] = value;
i++;
} else {
System.out.println("!! Error! Please Enter Value between 1 and 200 !!");
}
}
}
}
Here is an example using Java Streams. Here we simply read all the values first, then filter out each category later. Performance wise, it's better to just use a counter for each category if you don't care about the actual numbers being counted though.
public class Test {
public static void main(String[] args) {
int counter = 0;
Scanner scanner = new Scanner(System.in);
List<Integer> values = new ArrayList<>();
while (counter < 5) {
System.out.print("Enter integer (" + (counter + 1) + "): ");
int value = scanner.nextInt();
if (value >= 1 && value <= 200) {
counter++;
values.add(value);
} else {
System.out.println("Please enter a value between 1 and 200");
}
}
System.out.println("Between 1-50 : " + values.stream().filter(val -> val < 50).count());
System.out.println("Between 50-100 : " + values.stream().filter(val -> val >= 50 && val <= 100).count());
System.out.println("Between 101-150: " + values.stream().filter(val -> val > 100 && val <= 150).count());
System.out.println("Between 151-200: " + values.stream().filter(val -> val > 150 && val <= 200).count());
}
Output example:
Enter integer (1): 5
Enter integer (2): 55
Enter integer (3): 125
Enter integer (4): 175
Enter integer (5): -2
Please enter a value between 1 and 200
Enter integer (5): 201
Please enter a value between 1 and 200
Enter integer (5): 199
Between 1-50 : 1
Between 50-100 : 1
Between 101-150: 1
Between 151-200: 2
It is a very simple problem here #Dilip. Just introduce a flag variable which would mark if an input is wrong. If it is, then just accept the value again. Else proceed.
Following is the code snippet for the input part also considering the wrong and right input boundaries.
System.out.print("\n\tInput numbers from 1 to 200: \n");
for(i = 0; i < 5; i++) {
flag = 0;
while(flag == 0) {
list[i] = kbin.nextInt();
if(!(list[i] < 1 || list[i] > 200)){
flag = 1;
}
else {
System.out.println("INVALID INPUT!!! Enter a valid number.");
}
}
}
I have gone through the problem statement which you have told about in the comments section and have coded the program which would serve the purpose. I have also attached the output for confirmation and reference. Hope this helps.
CODE:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Keyboard Initialization
Scanner kbin = new Scanner(System.in);
// a.Declare an array to hold 5 Integer values
int list[] = new int[5];
int category1[] = new int[5], k1 = 0;
int category2[] = new int[5], k2 = 0;
int category3[] = new int[5], k3 = 0;
int i, flag;
System.out.print("\n\tInput numbers from 1 to 200: \n");
for(i = 0; i < 5; i++) {
flag = 0;
while(flag == 0) {
System.out.print("Enter the input number " + (i+1) + ": ");
list[i] = kbin.nextInt();
if(!(list[i] < 1 || list[i] > 200)){
flag = 1;
}
else {
System.out.println("INVALID INPUT!!! Enter a valid number.");
}
}
}
for(i = 0; i < 5; i++) {
if(list[i] < 50)
category1[k1++] = list[i];
else if(list[i] < 101)
category2[k2++] = list[i];
else
category3[k3++] = list[i];
}
System.out.print("Category 1(1 TO 49): ");System.out.println(k1);
System.out.print("Category 2(50 TO 100): ");
System.out.println(k2);
System.out.print("Category 3(greater than 100): ");
System.out.println(k3);
System.out.print("Category 4(151 to 200): ");
System.out.println(k4);
}
}
OUTPUT:
Input numbers from 1 to 200:
Enter the input number 1: 2
Enter the input number 2: 3
Enter the input number 3: 50
Enter the input number 4: 56
Enter the input number 5: 159
Category 1(1 TO 49): 2
Category 2(50 TO 100): 2
Category 3(101 to 150): 0
Category 4(151 to 200): 1
I have a program that reads a list of integers, and then display the number of even numbers and odd numbers. We assume that the input ends with 0. Here is the sample run of the program.
Input numbers: 1 2 3 4 5 6 7 8 9 0
Odd: 5 Even: 4
However, my result is
Odd: 5 and Even: 5.
The problem is that 0 is counted as an even number. This is my code
public class Q75 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner (System.in);
double [] numbers = new double[10];
System.out.print("Enter numbers: ");
for(int i = 0;i<numbers.length;i++){
numbers[i] = input.nextDouble();
}
int Evens = 0;
int Odd = 0;
for(int i = 0;i<numbers.length;i++){
if(numbers[i]%2 == 0){
Evens++;
}else{
Odd++;
}
}
System.out.println("The number of odd numbers: " + Odd);
System.out.println("The number of even numbers: " + Evens);
}
}
There are two options
A) Adding another branch in your if statements i.e.
if(number[i] > 0) {
if(number[i] % 2 >0)
Odd++;
else
Evens++;
}
NB: changing the else branch to else if(number[i] >0), you can do without the outer if condition.
B) Since the list of number ends with 0 you can put this as a condition in your for loop i.e.
for(int i =0; i < numbers.length && numbers[i] > 0 ; i++)
Also as a rule of thumb variable names in java start with a small letter
Just don't check the last element: Use i < numbers.length - 1
for(int i = 0;i < numbers.length - 1; i++) {
//
}
Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should: output the individual digits of 3456 as 3 4 5 6 and the sum as 18, output the individual digits of 8030 as 8 0 3 0 and the sum as 11, output the individual digits of 2345526 as 2 3 4 5 5 2 6 and the sum as 27, and output the individual digits of 4000 as 4 0 0 0 and the sum as 4.
Moreover, the computer always adds the digits in the positive direction even if the user enters a negative number. For example, output the individual digits of -2345 as 2 3 4 5 and the sum as 14.
This is the question I'm having minor difficulties with, the only part I can't figure out is how can I print the single integers in the order that he wants, from what I learned so far I can only print them in reverse. Here's my code:
import java.util.*;
public class assignment2Q1ForLoop {
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
int usernum, remainder;
int counter, sum=0, N;
//Asaking the user to enter a limit so we can use a counter controlled loop
System.out.println("Please enter the number of digits of the integer");
N = console.nextInt();
System.out.println("Please enter your "+N+" digit number");
usernum = console.nextInt();
System.out.println("The individual numbers are:");
for(counter=0; counter < N; counter++) {
if(usernum<0)
usernum=-usernum;
remainder = usernum%10 ;
System.out.print(remainder+" ");
sum = sum+remainder ;
usernum = usernum/10;
}
System.out.println();
System.out.println("the sum of the individual digits is:"+sum);
}
}
You have to storeremainder variables in an array and then print them in the loop from last index to first as shown in this tutorial.
You can either store digits in array and then print them, or you can try something like that:
final Scanner console = new Scanner(System.in);
System.out.println("Please enter your number");
final int un = console.nextInt();
long n = un > 0 ? un : -un;
long d = 1;
while (n > d) d *= 10;
long s = 0;
System.out.println("The individual numbers are:");
while (d > 1) {
d /= 10;
final long t = n / d;
s += t;
System.out.print(t + " ");
n %= d;
}
System.out.println();
System.out.println("the sum of the individual digits is:" + s);
An idea would be : convert int to string and write a method
getChar(int index) : String
which gives you for example 4 from 3456 with
getChar(2);
See Java - Convert integer to string
Here, I wrote a code for your problem with using a stack. If you want a simple code, you can comment my solution and I will wrote another one.
Scanner c1 = new Scanner(System.in);
System.out.print("Enter the number: ");
int numb = c1.nextInt();
numb = Math.abs(numb);
Stack<Integer> digits = new Stack<Integer>();
while(numb>0){
int n = numb%10;
digits.push(n);
numb = numb/10;
}
int sum = 0;
while(!digits.isEmpty()){
int n = digits.pop();
sum+=n;
System.out.print(n+" ");
}
System.out.print(sum);
My program is meant to add up all the even integers between 2 and an input number which is between 20 and 60. The logic for that is correct and will work, but it's supposed to be able to run again if the user wishes, and when it runs again, the input only changes if you input a new integer higher than the previous iteration. If you enter one lower, it just uses the same integer input as before. Here is the code:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number
for no): ");
restart = scan.nextInt();
} while (restart == 1);
}
}
So for example, if I enter 20 as the input, the program outputs:
Sum of even numbers between 2 and 20 is: 110
Enter a new value? (1 for yes, any other number for no):
and then I enter 30 (same run of the program):
Sum of even numbers between 2 and 30 is: 240
Enter a new value? (1 for yes, any other number for no):
and then I try to enter 20 again:
Sum of even numbers between 2 and 20 is: 240
Enter a new value? (1 for yes, any other number for no):
(Should clearly be 110, not 240)
My initial thought was that it wasn't actually scanning for a new input on the second iteration, but because it will work if I keep giving it inputs of greater value I know that is not true.
Use this code inside main()
Scanner scan = new Scanner (System.in);
int input;
int i = 2;
int sum = 0;
int restart;
do
{
System.out.print ("\nEnter a value between 20 and 60: ");
input = scan.nextInt();
if (input >= 20 && input <= 60) // checks validity of input
{
i = 2;
sum = 0;
while (i <= input)
{
sum = sum + i;
i = i + 2;
}
System.out.println ("\nSum of even numbers between 2 and " +
input + " is: " + sum);
}
else
{
System.out.println ("\nInput is not between 20 and 60. ");
}
System.out.print ("\nEnter a new value? (1 for yes, any other number for no): ");
restart = scan.nextInt();
} while (restart == 1);
Beginner here. So I want to write a program that prints out all the prime numbers up to the number the user entered. E.g., user enters 5, program prints out 2 and 3. That part I understand, however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no) IF the entered number is bigger than, let's say, 50. Here is code for first part:
public class Primes {
public static void main(String args[]) {
System.out.println("All primes up to: ");
int num = new Scanner(System.in).nextInt();
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
I honestly can't wrap my around as to what I should be doing next. My first program ever ("Hello world" does not count ;P).
Edit :
Your current code seems to work fine.
As per your doubt as mentioned in one of the comments : Yes, but where do I add if statement that does the following: if the number entered is below 50, then the program prints out all the prime numbers up to the entered number. If the number the user entered is bigger than 50, it tells only whether the entered number is prime or not ( simply "It's a prime" or "No, it's not a prime"). Hope that made things clearer
The check you need to put is after you take the input :
int num = new Scanner(System.in).nextInt();
if( number > 50 )
{
if(isPrime(number))
{
// print out is prime
}
// print out it is not prime
}
else
{
System.out.println("Prime numbers from 1 to " + num + " are: ");
for(int number = 2; number<=num; number++){
if(isPrime(number)){
System.out.println(number);
}
}
}
SUGESTIONS :
However, just to touch upon the algorithmic part, I would recommend using Sieve of Eratosthenes for picking out all the prime numbers within a given range, as you need in your case.
Example :
To find all the prime numbers less than or equal to 30, proceed as follows:
First generate a list of integers from 2 to 30:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Strike (sift out) the multiples of 2 resulting in:
2 3 5 7 9 11 13 15 17 19 21 23 25 27 29
The first number in the list after 2 is 3; strike the multiples of 3 from the list to get:
2 3 5 7 11 13 17 19 23 25 29
The first number in the list after 3 is 5; strike the remaining multiples of 5 from the list:
2 3 5 7 11 13 17 19 23 29
The first number in the list after 5 is 7, but 7 squared is 49 which is greater than 30 so the process is finished. The final list consists of all the prime numbers less than or equal to 30.
Here's the code attached for reference ( Disclaimer : I'm picking up this code here from this site. Just pasted it here for more immediate visibility).
Code :
public class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]) primes++;
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
Try this..
int j = 2; //variable
int result = 0; //variable
int number = 0; //variable
Scanner reader = new Scanner(System.in); //Scanner object
System.out.println("Please enter a number: "); //Instruction
number = reader.nextInt(); //Get the number entered
while (j <= number / 2) //start loop, during loop j will become each number between 2 and
{ //the entered number divided by 2
if (number % j == 0) //If their is no remainder from your number divided by j...
{
result = 1; //Then result is set to 1 as the number divides equally by another number, hergo
} //it is not a prime number
j++; //Increment j to the next number to test against the number you entered
}
if (result == 1) //check the result from the loop
{
System.out.println("Number: " + number + " is Not Prime."); //If result 1 then a prime
}
else
{
System.out.println("Number: " + number + " is Prime. "); //If result is not 1 it's not a prime
}
this is more efficient way tough:-
public boolean isPrime(int n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
however what I am struggling with, is what if I want the program to print out whether the number the user entered is a prime or not (simple yes or no).
Your current isPrime function seems to work, so just ask for a number and test it.
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.printf("%d yes%n", num);
} else {
System.out.printf("%d no%n", num);
}
}
Or with a ternary,
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
}
Edit Based on your comment, move your print up sequence to a method
public static void primesUpTo(int num) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
}
Then
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
System.out.println("Enter a number (is it prime): ");
int num = scanner.nextInt();
if (num > 50) {
System.out.printf("%d %s%n", num, isPrime(num) ? "yes" : "no");
} else {
primesUpTo(num); // <-- call the method above.
}
}
If i understand the question right:
If user enteres number lesser than or equal to 50, then print all primes that are lesser than that number.
Otherwise, just write if inputted number is a prime.
With already existing isPrime() method:
int num = new Scanner(System.in).nextInt();
if (num <= 50) {
System.out.println("Prime numbers from 1 to " + num + " are: ");
for (int number = 2; number <= num; number++) {
if (isPrime(number)) {
System.out.println(number);
}
}
} else { //num > 50
if(isPrime(num)) {
System.out.println(num + " is prime.");
} else {
System.out.println(num + " isn't prime.");
}
}