I can loop simply but it is hard for me to do even and odd numbers only. I want it like these for example:
Enter your number: 20
2 4 6 8 10 12 14 16 18 20
Do you want to do it again? Yes/No?
My code:
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
String c = null;
do {
int i;
System.out.println("Enter a Number:");
int n = input.nextInt();
for(i=1; i<n; i++) {
System.out.println(i);
if(n%2==0) {
System.out.println(i + " " );
}
System.out.println("Try Again? Y/N");
c = input.next();
}
}while(c.equalsIgnoreCase("y"));
}
You need to check i % 2 == 0 instead of n % 2 == 0.
Demo:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String c = null;
do {
System.out.print("Enter a Number: ");
int n = input.nextInt();
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
System.out.print("\nTry Again? Y/N: ");
c = input.next();
} while (c.equalsIgnoreCase("y"));
}
}
A sample run:
Enter a Number: 20
2 4 6 8 10 12 14 16 18 20
Try Again? Y/N: y
Enter a Number: 25
2 4 6 8 10 12 14 16 18 20 22 24
Try Again? Y/N: n
Your code is saying if (n%2 == 0) but the loop iterates over i. This n will never change in each loop.
It's probably not the only problem in your code, but certainly you should be looking at what i does in the loop instead of n on that line.
Related
You have to print a pattern using recursion. Given a input
N
the pattern looks like this
N
,
a
i
,
a
i
+
1
,
a
i
+
2
,.....,
N
. Where if
a
i
>
0
then
a
i
+
1
=
a
i
−
5
else
a
i
+
1
=
a
i
+
5
. It will be a decreasing sequence from
N
till
a
i
<=
0
and then an increasing sequence till
N
. (See sample test cases for better explanation)
Input format
First line contains an integer
T
denoting number of test cases.
For each of the next
T
lines, each line contains an integer
N
.
Output format
For each test case on a new line, print the required pattern.
Constraints
1
<=
T
<=
6
0
<=
N
<=
2000
Example
Input
2
16
10
Output
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
Sample test case explanation
For the first test case
N=16, it will be a decreasing sequence till the printing number becomes <=0.
16 11 6 1 −4
After this point it will be a increasing sequence till the printing number becomes N
1 6 11 16
So the pattern is 16 11 6 1 −4 1 6 11 16.
My code is below but i got the output as 16,11,6,1,-4 only. Help me to correct this code
import java.util.Scanner;
public class Day3
{
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=n)
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
series(n,true);
t-=1;
}
}
}
Because 'n' changes in every cases. You must create another variable and keep first 'n' in that, for control if temp smaller than 'n'.
For example
import java.util.Scanner;
public class Day3
{
int firstN = 0; //added that line
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=firstN) //changed that line
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
firstN = n; //added that line
series(n,true);
t-=1;
}
}
}
Also a little tip;
you can use (flag) for (flag==true)
and (!flag) for (flag==false)
Just FYI : Although this can be solved using recursion, it can be solved more efficiently without using recursion. It is as simple as this:
private static void printSeries(int N) {
int T = N;
while ( T >= 0 ) {
System.out.print(T + " ");
T = T - 5;
}
while ( T <= N ) {
System.out.print(T + " ");
T = T + 5;
}
}
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 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.
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);
i have an assignment , i have been working on it all day, i finished it, and it works, but not in the way my teacher wants it, i have been racking my brain for hours without any luck
this is the assignment question
"write a program that inputs five each of which is between 10 and 100 inclusive,as each number i read, display it only if it is not a duplicate number already read, provide for the "worst case," in which all five numbers are different, use the smallest possible array to solve this problem. Display the complete set of unique values input after the user inputs each new value."
this is the code i wrote
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sid[] = new int[5];
int count = 0;
int x = 0;
int num = 0;
while (x < sid.length)
{
System.out.println("Enter number: ");
num = input.nextInt();
if ((num >= 10) && (num <= 100)) {
boolean digit = false;
x++;
for (int i = 0; i < sid.length; i++)
{ if (sid[i] == num)
digit = true;
}
if (!digit) {
sid[count] = num;
count++;
}
else
System.out.printf("the number was entered before \n");
}
else
System.out.println("number must be between 10 and 100");
for (int i =0; i < x; i++) {
System.out.print(sid[i] +" ");
}
System.out.println();
}
}
}
my problem is in the output the output is like this
{
Enter number:
11
11
Enter number:
21
11 21
Enter number:
34
11 21 34
Enter number:
11
the number was entered before
11 21 34 0
Enter number:
44
11 21 34 44 0
}
But my teacher wants the output too look like this, without the 0's at the end, and without changing the value of the array sid from sid[5] to sid[4]
{
Enter number:
11
11
Enter number:
21
11 21
Enter number:
34
11 21 34
Enter number:
11
the number was entered before
11 21 34
Enter number:
44
11 21 34 44
}
i have been trying for hours now without any luck.
ANY help is appreciated.
Thank you.
cheers.
You only have to add an if condition to your output loop.
for (int i =0; i < x; i++) {
if(sid[i]!=0)
System.out.print(sid[i] +" ");
}
When you print the answer check for '0' and ignore them. or else decrements x when you found out the current number is a duplicate.
for (int i = 0; i < sid.length; i++)
{ if (sid[i] == num)
digit = true;
x--;
}
or
for (int i =0; i < x; i++) {
if(sid[i]!=0)
System.out.print(sid[i] +" ");
}
And if it is not necessary to use arrays you can use Sets. Then It would be much easier.
Put the x increment (x++) in the if (!digit)
if (!digit) {
sid[count] = num;
count++;
x++;
}
remove the x-increment (x++) from the if statement below
if ((num >= 10) && (num <= 100)) {
boolean digit = false;
x++;
}
that way the zeros are eliminated and the program still runs no matter the number of duplicates tried.