Arranging numbers in order for increasing - java

I am writing a program that arranges the elements in the array with the max being at the very end then would decrease in size as they move backwards in an array. I could just arrange them with smallest being first and so forth but I want to see if I could do the other way around. Below is my code.It does not work beyond the first iteration. Could anyone help me.
import java.util.Scanner;//Importing scanner class.
import java.util.Arrays;//Importing the array class.
{
public static void main(String[] args)
{
double [] numbers= {5,3,6,4,1};
double currentMax;
int currentMaxIndex;
int i,j,k;
// Scanner input = new Scanner(System.in);//Creating a scanner.
//The below lines are used to ask the user to enter 10 numbers.
/* for (k = 0;k<numbers.length;k++)
{
System.out.print("Enter number " + k +" : ");
numbers[k]=input.nextDouble();
}//end of for loop.
*/
for(i=numbers.length-1;i>1;i--)
{
currentMax=numbers[i];
currentMaxIndex=i;
for(j=numbers.length-2;j>0;j--)
{
if(currentMax<numbers[j])
{currentMax=numbers[j];
currentMaxIndex=j;
}
}
if(currentMaxIndex!=i)
{
numbers[currentMaxIndex]=numbers[i];
numbers[i]=currentMax;
}
}
System.out.print("The sorted new array is:\n");
for(i=0;i<numbers.length;i++)
{
System.out.print(numbers[i]+" ");
}
}
}

Although it doesn't directly answer your question, it does offer a reasonable alternative approach.
Refactor your code as follows:
Step 1: Delete all your code
Step 2: Type this instead:
Arrays.sort(numbers);

Obviously there are better ways to sort, but I think this should fix your code:
The outer loop should be checking for i >= 1 and the inner loop for j >= 0.

Related

How do I fix my duplicate detection code? Java

I have here a scanner in which collects series of numbers. I want it to scan the list every time user inputs a number so if the user inputs a number that is already in the list the new input will be disregarded/ignored and at the same time not adding increment to the loop.
The problem is the code can't seem to identify the duplicates. It continues to register the duplicate number even after few tries.
My code so far:
public class Number {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How Many Numbers You want to Enter:");
int n = input.nextInt();
List<Integer> number = new ArrayList<>();
for(int s=0;s<n;s++) {
int t = input.nextInt();
for (int j = 1; j < number.size(); j++) {
if (t == number.get(j)) {
System.out.print("Duplicate!");
s--;
continue;
} else {
number.add(t);
}
}
}
}
}
At the moment nothing at all is being saved in the number list, so the first thing to do is add debugging to work out why, or better yet, we can make use of the ArrayList.contains(...) method to solve this quite easily without needing the nested loop that that is causing your issue, for example the following works:
for(int s=0;s<n;s++) {
int t = input.nextInt();
if(number.contains(t)){
System.out.print("Duplicate!\r\n");
s--;
continue;
} else {
number.add(t);
}
}
//Print the result
System.out.println(Arrays.deepToString(number.toArray()));
And an output for a length of 5 and this number sequence 2,3,7,3,5,1 is:
How Many Numbers You want to Enter:5
2
3
7
3
Duplicate!
5
1
[2, 3, 7, 5, 1]

Variable number of inputs - Java

Need a refresher. I'm sure I know this already but I'm wracking my mind for a more efficient way to do this:
In short, the user is asked how many inputs they'd like to input (up to a certain maximum). For example, let's say they say 10.
Next, they're asked to input a number of single-digit integers equal to the number of inputs they wanted to input (in this case, they'd put in 10 different single-digit integers).
My issue is that I haven't coded Java in a while so I'm rusty. My immediate thoughts go to two options:
int input1 = 0, input 2=0, input3=0 ... inputN=0;
use an array
While option 1 is incredibly sophomoric it gets the job done. I'm just unsure if there's a simpler way to do it without using arrays.
import java.util.Scanner;
public class Histogram
{
public static void main(String[] args)
{
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 0;
boolean success = false;
//start of program
System.out.println("How many input values [max:20]?");
while (!success)
{
try
{
numInputs = keyboard.nextInt();
numInputChecker(numInputs);
success = true;
}
catch (Exception e)
{
keyboard.nextLine();
System.out.println("Single-digit integers only, please.");
}
}
System.out.println("Enter " + numInputs + " numbers.");
for(int i = 0; i < numInputs; i++)
{
// ?????????
}
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 20))
{
throw new Exception();
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer >= 10))
{
throw new Exception();
}
}
}```
i) If you're using multiple values, you're either going to need multiple variables or a collection of some sort. Agree with previous comments on choice of collection. (ii) If the amount of repetition required is counter controlled, why not set the loop to iterate that number of times? You would then need to nest while loops to ensure that your exception handling works but then you could limit the number of inputs. (iii) keyboard.nextInt() may be problematic because nextInt() does not discard the '\n'. It's better to Integer.parseInt(keyboard.nextLine()). (iv) If you're willing to work with strings, then you can do I/O once only and use the split() and Integer.parseInt() methods to get the necessary values.

I dont want to enter the size of List but I also want to dynamically add number in List

I am using List for dynamically storing the values, but I have to specify the size of List before taking input in the Binary search program.
I want help in that I don't want to take size as an input.
I have tried using length but that doesn't work, someone suggested me to use size(), but I don't know how to use it.
import java.util.*;
class Binary
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter size of array");
int n=s.nextInt();
System.out.println("Enter array elements in ascending order");
List<Integer> L=new ArrayList<>();
for(int i=0;i<n;i++)
{
int e=s.nextInt();
L.add(e);
}
System.out.println("Enter the element you want to search");
int h=s.nextInt();
int left=L.get(0);
int right=L.get(n-1);
while(left<=right)
{
if(h<=right){
int m=(left+right)/2;
if(m==h)
{
System.out.println("Element found at index:"+L.indexOf(m)+" starting from 0");
return;
}
if(m>h)
{
right=m-1;
}
if(m<h)
{
left=m+1;
}
}
else{
System.out.println("Element not present");
}
}
}
}
Now I am expecting the user to enter elements till he desires and then to find index of element using Binary Search
Your question is really a duplicate of How to terminate Scanner when input is complete?.
But here are a few pointers to get your program working.
This part of the code is incorrect.
int left=L.get(0);
int right=L.get(n-1);
You need to be setting the left and right to be the bounds of the search - not the values the user entered into those positions.
int left=0;
int right=L.size() - 1;
Then when you need to compare the values the user entered.
if (L.get(m) < h)
L.indexOf(m) doesn't really make sense. It would work if you had L.indexOf(L.get(m)) but that is the same as just m.
System.out.println("Element found at index:" + m + " starting from 0");

Keep Reversing the no. & adding it to the original no. until there is a Palindrome Number

It's not "Find the Palindrome of a Number" ! it's a bit twisted than that:
Step 1: Reverse the digits of a original number.
Step 2: Add the reversed number.
Step 3: If the new number is a palindrome number then print the output.
The limit is 15 steps & we can print the original number if that is a palindrome in itself. We have to use function calling in this program. Here I have used two functions() - FIRST to reverse the number & SECOND to add the original number and the reversed number & check if the sum is a Palindrome or not.
Please suggest your opinions if I can improve this long code in any way.
PS: newbie in Java & especially function calling!
Thank you!! Here's the code, it's a little bit long! I am sorry :(
import java.util.*;
public class PalindromicNumber
{
public int PalinReverse(int n)
{
int n1=n;
int x1=0, d1=0;
while (n1>0)//just used to store the reverse of the original number
{
d1=n1%10;
x1=(x1*10)+d1;
n1=n1/10;
}
return x1;
}
public int PalinCheck (int n, int p)
{
int F=0;
F=n+p;
int n1=F, x1=0, d1=0;
while(n1>0)//checks if the sum of reversed no. and the original number is palindrome or not
{
d1=n1%10;
x1=(x1*10)+d1;
n1=n1/10;
}
if (x1==F)
{
System.out.println("The number"+ F +"is a Palindrome");
return 1;
}
else
return F; //returns the sum if it is not a palindrome
}
public static void main (String args[])
{
Scanner sc=new Scanner(System.in);
PalindromicNumber ob=new PalindromicNumber();
System.out.println("Enter the original number");
int n=sc.nextInt();
int count=0;
int n1=n, x1=0, d1=0;
while(n1>0) //this checks if the original no. is a palindrome or not
{
d1=n1%10;
x1=(x1*10)+d1;
n1=n1/10;
}
if (x1==n)
System.out.println("The original number="+n+"is a palindrome number");
else
for (count=0;count<15;count++)
{
int a=ob.PalinReverse(n);
System.out.println("The reversed number is"+a);
int b=ob.PalinCheck(n,a);
if(b==1)
{
System.out.println("The no. of steps it took was"count+1);
break;// the palindromic no. is now found out
}
else
n=b;//used to update the value of n
}
}
}
The problem is in your PalinReverse method. Your while loop is running infinitely because the condition is always true.
Replace
while (n>0)
with
while (n1>0)
You should also learn how to debug a program. Your life will be 10 times easy after that.

Using a single-dimensional array, ask the user for input and display only NON-duplicate values

in my java class we were learning about arrays and this question came up. I have tried to solve it and can't seem to fulfill the requirements. I can read in the user inputs and have it limited to only 5 elements (one of the other requirements), also the values have to be between 10 and 100 I have also done that. But I cannot seem to "not print" the duplicate values. The array accepts the duplicate values. They don't have to be taken out, just not printed. Here is my code so far:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
while (InpNum[i] <= i){
System.out.println("Please type a number between 10 and 100: ");
InpNum[i] = in.nextInt();
while (InpNum[i] < 10 || InpNum[i] > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
InpNum[i] = in.nextInt();
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
}
while (Search(InpNum, i) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
InpNum[i] = in.nextInt();
}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for(int i : InpNum) {
if (i == searchedNum) {
return true;
}
}
return false;
}
}
I would consider restructuring your application.
Instead of placing the number the user inputs into the array immediately, store it in a local variable. Then run all the checks you need to run, and add it to the array only if it passes all of them.
You should only have one while loop in the whole program (the outer one). All those others are greatly confusing the issue and making the problem much harder than it has to be.
So, in psudo-code:
int index = 0;
while (true)
{
int num = in.nextInt();
// if not between 10 and 100, continue
// if it would make the array larger than 5, continue
// (or perhaps break out of the loop, since we've filled the array)
// if it is already in the array, continue
// all the checks passed, so add it to the array!
InpNum[index++] = num;
}
As a side note, what you really need is a Set. This is a collection which is guaranteed to have no duplicates and allows you to answer the question "do I contain this value?" in an efficient manner using the method Set.contains( Object ).
So I would create a TreeSet or HashSet and put every number the user types into it. Your Search function would then simply be a one liner calling contains( searchedNum ) on your set.
A lazy way is to just create a second array that can hold the values as you go.
Loop through the input array and put the current element into the new array IF that array doesn't have that element already.
Then replace the old array with the weened out one.
Easiest way
So what I do is first ask the number. Then save the number in a variable before entering it inside the array. Then I check if that number is already in it wih search. If it is I ask for a new number. If it is not I check if it is between 10 and 100, if it is not I ask for a new. I fit is I enter It inside the array. I have to check where an empty place is because the sort mixes up the array everytime
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
System.out.println("Please type a number between 10 and 100: ");
int number = in.nextInt();
//while (InpNum[i] <= i){
while (Search(InpNum, number) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
number = in.nextInt();
}
while (number < 10 || number > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
number = in.nextInt();
}
int counter = 0;
for (int j = 0; j < InpNum.length && counter == 0; j++){
if(InpNum[j] == 0){
InpNum[j] = number;
counter++;
}
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
//}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for (int i = 0; i < InpNum.length; i++){
if (InpNum[i] == searchedNum) {
return true;
}
}
return false;
}
}

Categories

Resources