Ascending order and Descending Java - java

Hi here's my problem i cant seem to print my outputs correctly i guess i'm having a logical error in my code, it doesn't print when i put an ascending number then a descending. i'm kind of new to programming too.
Code:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
int n, i, k, j;
int asc = 0,
Scanner x = new Scanner(System.in);
do {
System.out.print("How many numbers to process : ");
k = x.nextInt();
if(k<=1) {
System.out.println("Enter a number greater than 1");
}
} while(k<=1);
System.out.printf("Please enter %d numbers: ",k);
n = x.nextInt();
for(i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
}
}
Here are the outputs
Example outputs (what i'm trying to get)
How many numbers to process : 4
Please enter 4 numbers : 1 2 3 4
Growing up.
How many numbers to process : 4
Please enter 4 numbers : 4 3 2 1
Not Growing up.
This is my problem :
How many numbers to process : 4
Please enter 4 numbers : 1 2 1 3
Growing up. // it should be not growing up.

There is no need to iterate through all numbers. You can just check if the previous number is lower (if growing). If not, print and return. Check my example code.
Replace
n = x.nextInt();
for (i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
With
int prev = x.nextInt();
for (i=0; i<k-1; i++) {
j = x.nextInt();
if (j < prev) { System.out.print("Not Growing Up."); return; }
prev = j;
}
System.out.print("Growing Up.");

String numbers = "1 2 3 4"; // Let's take this input for example
int temp = 0; // This use to compare previous integer
boolean isAsc = false; // This store whether the digits is growing up or not
StringTokenizer st = new StringTokenizer(numbers); // Declare StringTokenizer
while (st.hasMoreTokens()) {
int next = Integer.parseInt(st.nextToken()); // Put the first integer in next (1)
if(next > temp){ // if (1) > 0
temp = next; // Assign 1 to temp, next time digit 2 will compare with digit 1
isAsc = true; // Assign the ascending to true
} else
isAsc = false;
}
if(isAsc)
System.out.print("Growing up.");
else
System.out.print("Not growing up.");
}
Your can store the user input as a string like the variable numbers I've declared and break them into each token for compare purpose.

import java.lang.reflect.Array;
import java.util.*;
public class A1 {
public static void main(String[] args) {
int a[]={2,5,0,1};
Arrays.sort(a);
int b= a.length;
for(int i=0;i<a.length;i++)
{
System.out.println(+a[i]+"\t"+a[b-1]);
b--;
}
}
}

Related

Lucky number with User Input

I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)

delete prime numbers from an array-java

How can I do in order to delete prime numbers not including 0 and 1 and I want to find just prime numbers excluding 0 and 1?Now if I have{0,1,3,5,8}----> after compiling it will find 0 and 1 as prime numbers ."Prime Number Found=0 Prime Number Found=1 Prime Number Found=3 Prime Number Found=5" Here's my program:
Thank you for your help.
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int i,j,size;
boolean status;
System.out.print("Enter size of array=");
size=s.nextInt();
int arr[]=new int[size];
int tmp[]=new int[size];
System.out.println("Enter Elements in array...");
for(i=0;i<size;i++)
{
arr[i]=s.nextInt();
}
for( i=0;i<size;i++)
{
status=true;
for(j=2;j<arr[i]-1;j++)
{
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
}
if(status==true)
{
System.out.println("Prime Number Found="+arr[i]);
}
}
System.out.println("New Array....");
for(i=0;i<size;i++)
{
System.out.println(tmp[i]);
}
}
}
Your code was full of problems, but in the code below I did fix the following major problems:
you were not handling the base case of 0 and 1 being not prime correctly
your loop for scanning for possible whole number divisors had the wrong bounds
you were not writing the found prime numbers correctly to the output array which you were printing at the end of the main() method.
Have a look at the code below for a sample of what you probably intended to do.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean status;
System.out.print("Enter size of array=");
int size = s.nextInt();
int arr[] = new int[size];
int tmp[] = new int[size];
System.out.println("Enter Elements in array...");
int primerCounter = 0;
for (int i=0; i < size; i++) {
arr[i] = s.nextInt();
}
for (int i=0; i < size; i++) {
status = true;
if (arr[i] == 0 || arr[i] == 1) {
status = false;
}
else {
for (int j=2; j <= arr[i]-1; j++) {
if (arr[i] % j ==0) {
status = false;
break;
}
}
}
if (status == true) {
tmp[primerCounter++] = arr[i];
System.out.println("Prime Number Found="+arr[i]);
}
}
System.out.println("New Array....");
for (int i=0; i < primerCounter; i++) {
System.out.println(tmp[i]);
}
}
For an input of the numbers from 0 to 20 inclusive, I got the following output:
{2, 3, 5, 7, 11, 13, 17, 19}
Your question is not very clear, but I am assuming your problem is that the code you posted considers 0 and 1 as prime numbers, and you don't want that. If that's the case. the error is that the check
(arr[i]==0)||arr[i]==1)
is within the for loop
for(j=2;j<arr[i]-1;j++)
In fact, when arr[i] is equal to 0 or 1, the condition
j<arr[i]-1
will evaluate to false immediately, because j=2 and arr[i]-1 evaluates to either -1 or 0. As a consequence, the code
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
will never be executed, and in the following loop
status==true
will evaluate to true.
One solution is to remove the check
arr[i]==0)||arr[i]==1
from where it is now and put it in the same if as the one whose condition is
status==true
after changing == with !=.
In a nutshell,
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
should become
if(arr[i]%j==0)
{
status=false;
tmp[i]=arr[i];
break;
}
and
if(status==true)
{
System.out.println("Prime Number Found="+arr[i]);
}
should become
if(status==true || arr[i]!=0 || arr[i]!=1)
{
System.out.println("Prime Number Found="+arr[i]);
}
There's another mistake in the code you posted: you use the same index i to iterate over arr and to select the elements of tmp to whom assign values. As not every element of arr is prime and will not therefore be copied to tmp, this results in an array tmp with some "holes", i.e, unassigned elements. You should keep a different index k initialized to 0 to access the elements of tmp and increment it manually:
tmp[k]=arr[i];
k++;
instead of
tmp[i]=arr[i];
Also, when you eventually iterate over tmp bear in mind that its size won't be the same as arr, but smaller (for the reason I have just explained). Thus,
for(i=0;i<size;i++)
{
System.out.println(tmp[i]);
}
should be replaced with
for(i=0; i < actual-size-of-tmp; i++)
{
System.out.println(tmp[i]);
}

Coding Bubble Sort using Java

I don't know if I did this coding correctly, but can someone confirm if my doBubbleSort method and its implementation in the main method are programmed correctly? My coding requires me to create an array of size 20 and populate it with random integers between 1 and 1000 without hard coding them. The result should display the original, unsorted list of integers; and then display each pass of the bubble sorting algorithm on a separate line. I have to repeat the program until the user chooses to quit. **I have made edits to make sure that whatever variables I use, it is declared according to ArrayLists.
An example of how I want my output to come out as is shown below (although it only shows 5 integers when I'm trying to do 20):
Unsorted list: 68 3 298 290 1
Pass 1: 3 68 290 1 298
Pass 2: 3 68 1 290 298
Pass 3: 3 1 68 290 298
Pass 4: 1 3 68 290 298
// Used to capture keyboard input
import java.util.*;
// Our class called BubbleSort
public class BubbleSort {
// Create doBubbleSort method
public static void doBubbleSort(ArrayList<Integer> arr) {
boolean needNextPass = true;
while (needNextPass) {
// Array may be sorted and next pass not needed
needNextPass = false;
// Swap list
for (int i = 0; i < arr.size()-1; i++) {
if (arr.get(i) > arr.get(i+1)) {
int temp = arr.get(i);
arr.set(i, arr.get(i+1));
arr.set(i+1, temp);
printOut(i+1, arr); // using printOut method
needNextPass = true; // Next pass still needed
}
}
}
}
private static void printOut(int pass, ArrayList<Integer> list) {
System.out.print("PASS " + pass + ": ");
for (int i = 0; i < list.size()-1; i++) {
System.out.print(list.get(i) + ", ");
}
// Shows very last integer with a period
System.out.print(list.get(list.size()-1) + ".");
System.out.println();
}
// Main method
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>(); // Declare and instantiate a new ArrayList object
Scanner userChoice = new Scanner(System.in); // User input for quitting program
String choice = ""; // Will hold user choice to quit program
boolean inputFlag = false; // True if input is valid, false otherwise
// Repeat program until user chooses to quit
while (inputFlag = true) {
System.out.print("\nWould you like to continue the program? (Y/N): ");
choice = userChoice.nextLine();
if (choice.equalsIgnoreCase("Y")) {
try {
/* Create an array of size 20 and populate it with random integers between 1 and 1000.
Do not ask user for the numbers and do not hard code them */
for (int i = 0; i < 20; i++) {
int integer = (int)(1000.0 * Math.random());
array.add(integer);
}
System.out.print("\nUNSORTED LIST: ");
//Display the 20 size of the unsorted ArrayList
for (int i = 0; i < array.size() - 1; i++) {
System.out.print(array.get(i) + ", ");
}
// Shows very last integer with a period
System.out.print(array.get(array.size() - 1) + ".");
System.out.println();
doBubbleSort(array);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
}
else if (choice.equalsIgnoreCase("N")) {
break;
}
// Error message when inputting anything other than Y/N
else {
System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
System.out.println("Please try again.");
}
}
}
}
Going with your implementation, since you seem to be newly learning this, there are a few things you should change. First of all, since you're using an int array for the doBubbleSort method, use an int array in the main method as well.
The implementation of bubblesort needs to be changed too. You should first look into its logic carefully. Going through the whole array every time is not necessary.
// Create doBubbleSort method
public static void doBubbleSort(int[] arr) {
boolean needNextPass = true;
// Array may be sorted and next pass not needed
// Swap list
for (int i = 0; i < arr.length - 1; i++) {
if (needNextPass) {
needNextPass = false;
for (int j = arr.length - 1; j > i; j--) {
int temp;
if (arr[j] < arr[j - 1]) {
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
needNextPass = true; // Next pass still needed
}
}
printOut(i + 1, arr); // using printOut method
}
}
}
And then, printing the array.
private static void printOut(int pass, int[] list) {
System.out.print("PASS " + pass + ": ");
for (int i = 0; i < list.length - 1; i++) {
System.out.print(list[i] + ", ");
}
// Shows very last integer with a period
System.out.print(list[list.length - 1] + ".");
System.out.println();
}
Now the main method. I've changed the input handling part for re-running the program, and used an int array as you had originally posted.
// Main method
public static void main(String[] args) {
int[] array = new int[20]; // Declare and instantiate a new ArrayList object
Scanner userChoice = new Scanner(System.in); // User input for quitting program
boolean inputFlag = true; // True if input is valid, false otherwise
String choice;
// Repeat program until user chooses to quit
while (inputFlag == true) {
try {
/* Create an array of size 20 and populate it with random integers between 1 and 1000.
Do not ask user for the numbers and do not hard code them */
for (int i = 0; i < 20; i++) {
int integer = (int) (1000.0 * Math.random());
array[i] = integer;
}
System.out.print("\nUNSORTED LIST: ");
//Display the 20 size of the unsorted ArrayList
for (int i = 0; i < array.length - 1; i++) {
System.out.print(array[i] + ", ");
}
// Shows very last integer with a period
System.out.print(array[array.length - 1] + ".");
System.out.println();
doBubbleSort(array);
} catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
System.out.print("\nWould you like to continue the program? (Y/N): ");
choice = userChoice.nextLine();
while (!(choice.equalsIgnoreCase("Y")) && !(choice.equalsIgnoreCase("N"))) {
// Error message when inputting anything other than Y/N
System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
System.out.println("Please try again.");
choice = userChoice.nextLine();
}
if (choice.equalsIgnoreCase("N")) {
inputFlag = false;
}
}
}
}
You wrote too much boiler plate code for bubble sort. For bubble sort, use recursive method. I wrote for you simple bubble method, do what you want with output
private int[] bubbleSort(int[] arr){
int c;
boolean isArranged = false;
for (int i = 0; i < arr.length; i++) {
if (i < (arr.length - 1) && arr[i] > arr[i+1]){
c = arr[i];
arr[i] = arr[i+1];
arr[i+1] = c;
isArranged = true;
}
}
if (isArranged){
return bubbleSort(arr);
}else{
return arr;
}
}
Call this like:
Scanner in = new Scanner(System.in);
int length = in.nextInt();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = in.nextInt();
}
Main main = new Main();
int[] newArr = main.bubbleSort(arr);
for (int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i] + " ");
}
You can write ArrayList instead int array.

Java number sequence loop

So hi i'm getting infinite loop problem i don't know whats wrong with my code i'm trying to make a number sequence format is at the bottom i think the problems are in my condition?
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
while(n!=0) { //is this right?
for ( int i = 0; i<=n; i++) {
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
Outputs i'm trying to get
Enter how many numbers to display : 5
1 3 6 8 11
2.
Enter how many numbers to display : 16
1 3 6 8 11 13 16 18 21 23 26 28 31 33 36 38 //but im getting infinite loops
// the sequence pattern is +2 then +3
The problem is here: while(n!=0) and here: for ( int i = 0; i<=n; i++). For the while loop, will keep on going until n is equal to 0. For the for loop, this will most likely keep on going for ever.
Your code has two problems:
If you provide a non negative value, this will keep on going for ever (since you are always only incrementing n).
Even if you do supply a negative number, n would n need to become exactly 0 to stop.
Depending on what you need to do, you will need to change the condition. Judging by the output, n would need to be positive and thus you would need to stipulate some upper range for n in which the while loop would stop.
EDIT: You only need to have 1 loop to do what you are after. Also, n denotes the amount of elements, thus it needs to stay fixed throughout the execution of the program. In your case, you where increasing it all the time.
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int count = 0;
int i = 1;
while (count < n) { //is this right?
if (count % 2 == 0) {
System.out.print(i + " ");
i += 2;
} else {
System.out.print(i + " ");
i += 3;
}
count++;
}
Two problems:
int stop = n; // declare one local var to stop the for loop
if (n != 0) { //switch to if condition
for (int i = 0; i <= stop; i++) {
//loop's exit condition wasn't met because 'n' was also being incremented
if (i % 2 == 0) {
n += 2;
System.out.print(n+" ");
} else {
n += 3;
System.out.print(n+" ");
}
}
}
Use 'if' condition in place of 'while' loop
You have to replace your while-loop with an if-condition like so:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int stop = n;
if(n!=0) { //if statement checks if n!=0
for ( int i = 0; i<=stop; i++) {
//stop replaces n because n is incremented in your for-loop
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
Based on your answers I found a solution that works:
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int k = -2; // so that it starts with 1 when i add +3
int stop = n-1;
if(n!=0) {
for ( int i = 0; i<=stop; i++) {
if(i%2==0) {
k += 3;
System.out.print(k+" ");
} else {
k += 2;
System.out.print(k+" ");
}
}
}

Print Fibonacci sequence up to nth place?

I am trying to print the entire fibonacci sequence up to a given place. So the user would decide how many numbers of the fibonacci sequence they want to see (up to 16 repetitions) and it would print the entire sequence.
My current code only prints the number in the sequences for the place that you choose.
ex: 4 prints 2 instead of 0 1 1 2.
public int Fibonacci(int number){
if(number == 1 || number == 2){
return 1;
}
int fib1=1, fib2=1, fibonacci=1;
for(int count= 3; count<= number; count++){
fibonacci = fib1 + fib2;
fib1 = fib2;
fib2 = fibonacci;
}
return fibonacci;
}
Here is my main method:
import java.util.Scanner;
public class FibonacciPrinter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
int input = in.nextInt();
FibonacciGenerator newNumber = new FibonacciGenerator();
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
}
}
I think here,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(input));
}
You almost certainly wanted,
for(int fibCount = 0; fibCount < input; fibCount++)
{
System.out.println(newNumber.Fibonacci(fibCount)); // <-- fibCount not input
}
You need to update your method to handle the zero case, for example
public int Fibonacci(int number) {
if (number == 0) return 0;
// ...
}
and in Java, the convention would name Fibonacci to fibonacci because method names are camel case starting with a lower case letter (classes start with a capital letter by convention).

Categories

Resources