How do i make java output number decreasing order - java

So far this is my code and I need it to output from 66 down to 11. Right now it does 11 upto 66.
public class ListNumbers {
public static void main(String[] args) {
//define limit
int limit = 66;
System.out.println("Printing Even numbers between 1 and " + limit);
for(int x=11; x <= limit; x++){
if(x != 44 && x != 22){
System.out.print(x + " ");
}
}
}
}

You just need to start from limit and ends when it reaches 11
for(int x = limit; x > 10; x--){
if(x! = 44 && x != 22){
System.out.print(x + " ");
}
}

You start the loop at the upper limit (66) and decrements down to the lower limit (1). Then you check if they are even or odd but only output the even numbers.
int lowerLimit = 1;
int upperLimit = 66;
System.out.println("Printing Even numbers between " + lowerLimit + " and " + upperLimit);
for (int x = upperLimit; x >= lowerLimit; x--)
{
if ((x & 1) == 0)
{
// even
System.out.print(x + " ");
}
else
{
// odd
}
}

Related

How possible to display the 2 digit sum of the inputted number (prime numbers)

It will only accept a non-negative even number (higher than 2) and extract the 2 prime numbers. Here is the sample output:
Enter the number: 20
The twin prime numbers of 20 are: 17 and 3 / 13 and 7
(17 + 3 = 20 and 13 + 7 = 20 also) But 17,3,13, and 7 is a prime number. I don't know how to do it, please, thankyou!
But here is my output, my output is just to print all twin prime between 3-20 (that is inputted number)
run:
Enter the number: 20
The twin prime numbers of 20 are:
3 / 5
5 / 7
11 / 13
17 / 19
I don't know how to do the specific problem.
Here is my code btw:
import java.util.Scanner;
class Prime {
boolean prime(int a) {
int count = 0;
for (int x = 1; x <= a; x++) {
if (a % x == 0) {
count++;
}
}
switch (count) {
case 2:
return true;
default:
return false;
}
}
public static void main(String args[]) {
Prime twin = new Prime();
Scanner sc = new Scanner(System.in);
int higherThan2 = 3;
System.out.print("Enter the number: ");
int number = sc.nextInt();
if (higherThan2 >= number) {
System.out.println("Must be higher than 3!");
} else {
System.out.println("\nThe twin prime numbers of " + number + " are: ");
for (int i = higherThan2; i <= (number - 2); i++) {
if (twin.prime(i) == true && twin.prime(i + 2) == true) {
System.out.print(i + " / " + (i + 2) + "\n");
}
}
}
}
}
You can try this. It works, but I don't think it's the best
System.out.println("\nThe twin prime numbers of " + number + " are: ");
for(int i = higherThan2; i < number; i++)
for(int j = number; j > higherThan2; j--)
if(twin.prime(i) && twin.prime(j) && i + j == number)
System.out.print(i + " / " + j + "\n");

How to write an even or odd program in java?

My instructions are "Write a program that prompts the user for a number, then counts up (a ‘for’ loop) from one to that number and prints whether that loop number is even or odd (which will require an ‘if-else’ structure inside the loop)." So it needs to list:
1 is odd
2 is even
3 is odd...
public class AssmtEvenOrOddJulianP {
public static void main(String[] args) {
//variable
int num = 0;
//input
System.out.print("\nEnter a number less than 100: ");
num = Expo.enterInt();
//output
for (int i = 1; i <= num; i++)
if ((num % 2) == 0)
System.out.print("\n" + i + " Is Even");
else if ((num % 2) >= 0)
System.out.print("\n" + i + " Is Odd");
Right now if I input 3 it will print:
1 is odd
2 is odd
3 is odd
Minor mistake:
You should calculate the remainder of i by 2, not num by 2.
Always wrap for and if/else blocks in curly braces:
for (int i = 1; i <= num; i++) {
if ((i % 2) == 0) {
System.out.print("\n" + i + " Is Even");
} else if ((num % 2) >= 0) {
System.out.print("\n" + i + " Is Odd");
}
}
Avoid using redundant parantheses:
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.print("\n" + i + " Is Even");
} else if (num % 2 >= 0) {
System.out.print("\n" + i + " Is Odd");
}
}
The else if condition has a minor bug that is "unreachable" right now, but could cause pain in the future
num % 2 >= 0 should be i % 2 < 0 || i % 2 > 0
The else if condition can be simplified to else:
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.print("\n" + i + " Is Even");
} else {
System.out.print("\n" + i + " Is Odd");
}
}
Final result:
With some other minor improvements:
public class EvenOdd {
public static void main(String[] args) {
// input
System.out.print("\nEnter a number less than 100: ");
// variable
int num = Expo.enterInt();
System.out.println();
// output
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.println(i + " Is Even");
} else {
System.out.println(i + " Is Odd");
}
}
}
}
The Following program will help you . for odd and Even number we need to divide by 2 and if number is divisible by 2 then number is Even Number (in this case reminder will be 0) and if the reminder is 1 then its Odd Number
public class EvenAndOddNumber {
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
for (int i = 1; i <= num; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even number");
} else {
System.out.println(i + " is odd number");
}
}
}
}

Two dimensional array input from user in java from a sequence of lines, ending with a line input "end"

Here is my code. I think that there is much better way to fill matrix with integers from String lines. My output shows correct output, but it is too complicated. How to make it less complex?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int [][]matrix = new int [7777][7777];
int counter = 0;
int counter1 = 0;
for (int i = 0; i < 7777; i++) {
String s = scanner.nextLine();
if (!"end".equals(s)) {
counter++;
String s1[] = s.split(" ");
for (int j = 0; j < s1.length; j++) {
matrix[i][j] = Integer.parseInt(s1[j]);
counter1++;
}
} else {
break;
}
}
int v = counter;
int h = counter1/counter;
for (int i = 0; i < v; i++) {
for (int j = 0; j < h; j++) {
if (v == 1 || h == 1) {
System.out.print(matrix[i][j]*4 + " ");
} else if (i == 0){
if (j == 0){
System.out.print(matrix[v-1][j] + matrix[i+1][j] + matrix[i][h-1] + matrix[i][j+1] + " ");
} else if (j != h-1){
System.out.print(matrix[v-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][j+1] + " ");
} else {
System.out.print(matrix[v-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][0] + " ");
}
} else if (j == 0 && i != v-1){
System.out.print(matrix[i-1][j] + matrix[i+1][j] + matrix[i][h-1] + matrix[i][j+1] + " ");
} else if (j != 0 && j != h-1 && i != v-1) {
System.out.print(matrix[i-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][j+1] + " ");
} else if (j == h-1 && i != v-1){
System.out.print(matrix[i-1][j] + matrix[i+1][j] + matrix[i][j-1] + matrix[i][0] + " ");
} else if (i == v-1) {
if (j == 0) {
System.out.print(matrix[i-1][j] + matrix[0][j] + matrix[i][h-1] + matrix[i][j+1] + " ");
} else if (j != h-1) {
System.out.print(matrix[i-1][j] + matrix[0][j] + matrix[i][j-1] + matrix[i][j+1] + " ");
} else {
System.out.print(matrix[i-1][j] + matrix[0][j] + matrix[i][j-1] + matrix[i][0] + " ");
}
}
}
System.out.println();
}
}
}
Here is the task assignment.
Write a program, which inputs the rectangular matrix from a sequence of lines, ending with a line, containing the only word "end" (without the quotation marks).
The program should output the matrix of the same size, where each elements in the position (i, j) is equal to the sum of the elements from the first matrix on the positions (i-1, j), (i+1, j), (i, j-1), (i, j+1). Boundary elements have neighbours on the opposite side of the matrix. In the case with one row or column, the element itself maybe its neighbour.
Sample Input:
9 5 3
0 7 -1
-5 2 9
end
Sample Output:
3 21 22
10 6 19
20 16 -1
Yes this code could be simplified.
Starting off, using array is not the best choice for containing the input because you don't know the input size. Using a List that can expand to fit the data will be easier. Further, using the Stream api, we can convert the input into a List<List<Integer>> fairly easily.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<List<Integer>> matrix = reader.lines()
.takeWhile(line -> !line.equals("end"))
.map(line -> Arrays.stream(line.split(" "))
.map(Integer::valueOf)
.collect(Collectors.toList()))
.collect(Collectors.toList());
Now that we have the data in our list we will compute the size of the width and height.
int height = matrix.size();
int width = matrix.get(0).size();
Computing the locations of (i-1, j), (i+1, j), (i, j-1), (i, j+1) without an IndexOutOfBoundsException is a little more tricky, however you can use this modulo formula. As long as the offset isn't negatively larger than the size this will work. You can also that the modulo of the offset if that is a concern
(size + index + offset) % size
// or
(size + index + (offset % size)) % size
To add the strings together with a space you can use a StringJoiner.
for (int i = 0; i < height; i++) {
StringJoiner joiner = new StringJoiner(" ");
for (int j = 0; j < width; j++) {
int value = matrix.get((height + i - 1) % height).get(j)
+ matrix.get((height + i + 1) % height).get(j)
+ matrix.get(i).get((width + j - 1) % width)
+ matrix.get(i).get((width + j + 1) % width);
joiner.add(String.valueOf(value));
}
System.out.println(joiner.toString());
}

How do I terminate this loop?

"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.
Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}
Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}
I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));
Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .

Recursive Summation Method

I am currently working on a recursive summation method in java, this is my code so far however I am running into some issues during runtime with ArrayIndexOutOfBoundsException. This is the completed code to this point.
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
input();
}
private static void input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Lower bound: ");
int lower = scanner.nextInt();
System.out.print("Upper bound: ");
int upper = scanner.nextInt();
arrayForm(upper, lower);
}
private static void arrayForm(int upper, int lower) {
int b = 0;
int a = Math.abs(lower) + Math.abs(upper);
int array[] = new int[a];
for (int i = 0; i < array.length; i++) {
array[i] = lower + i;
}
summation(array, b);
}
public static int summation(int array[], int b) {
if (b > array.length) {
System.out.println("Cannot continue");
return 0;
} else{
int result = array[b] + summation(array, b + 1);
System.out.println("recursion call: " + b);
System.out.println("sum: " + result);
System.out.println("parameter 1: " + array[b]);
System.out.println("parameter 2: " + array[b + 1]);
return result;
}
}
}
There are two errors in your code:
fix b >= array.length: If i give the bounds 1 to 10 The array has 11 elements. That leads to an index of 0 to 10. If you call array[b] with b = array.length, length is 11 and that's out of bounds.
array.length - 1: Becouse you are calling summation(array, b + 1) the index b must not exceed max-index - 1. E.g. bounds: 1 to 10. So summation(array, 10) calls summation(array, 11) and thats the last element in the array.
so the summation(a,b) function looks like this:
public static int summation(int array[], int b) {
if (b >= array.length - 1) {
System.out.println("Cannot continue");
return 0;
} else {
int result = array[b] + summation(array, b + 1);
System.out.println("recursion call: " + b);
System.out.println("sum: " + result);
System.out.println("parameter 1: " + array[b]);
System.out.println("parameter 2: " + array[b + 1]);
System.out.println();
return result;
}
In the else-part:
System.out.println("parameter 2: " + array[b + 1]);
requires for a valid index:
b + 1 < array.length
b < array.length - 1
But the if-else merely guarantees:
b <= array.length
b < array.length + 1
Hence it should be
if (b >= array.length - 1) { ... } else { ... }
Amd then there is probably an error in the logic if you intended:
sum of lower + (lower + 1) + (lower + 2) + ... + upper
These are (upper - lower + 1) terms of average (upper + lower)/2:
int sum = (upper - lower + 1) * (upper + lower) / 2;
Either one of the factors is even as they differ by 2*lower+1, so integer calculation is okay: integer division by does not loose anything.
Example
sum(7, 9) = (9 - 7 + 1) * (9 + 7) = 3 * 16 = 48

Categories

Resources