java array searching method - java

I have to make an array whose 10 numbers are chosen by the user through a scanner. The program orders the 10 numbers in ascending order, then prints out the new list. Then It asks the user to enter any number and then uses a binary search to see if the number is in the list of 10 numbers.
Here is what I have so far:
import java.util.Scanner;
public class lab11 {
public static void main(String[] args){
double[] numbers = new double[10];
System.out.println("Please enter 10 double values:");
for (int i=0;i<10;i++){
numbers[i] = inputArray();
}
System.out.println("sorting");
print(selectionSort(numbers));
System.out.println("Please enter a search key:");
}
public static double inputArray(){
Scanner input = new Scanner(System.in);
System.out.print(">");
double d = input.nextInt();
return d;
}
public static double[] selectionSort(double[] list){
double temp;
for(int i=0; i < (list.length-1); i++){
for(int j = i+1; j < list.length; j++){
if(list[j] < list[i]){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void print(double[] arr){
for(double d:arr){
System.out.println("list["+j+"]"+" = "+d);
}
}
public static int binarySearch(double[]list, double key){
int low=0,high=list.length -1;
key =input.nextInt();
while(high>=low){
int mid=(low+high)/2;
if(key<list[mid])
high=mid-1;
else if(key==list[mid]) return mid;
else low=mid+1;
}
return-1;
}
}
I need help with 2 things.
(1) is under the Print method. I want the program to print out like "list[i] = d" The d a number that the user puts in and it works fine, but the i doesn't. I want it to be the array number which is 0 through 9.
(2) I need help with invoking the binary search so I can have an output for the search.

Just for the right input, you can write a do...while loop, which loops till the input is valid:
for (int i = 0; i < 10; i++) {
double number;
Scanner input = new Scanner(System.in);
do {
System.out.print(">");
number = input.nextDouble();
} while (number < 0 || number > 10);
}
}

For the output you seem to want use
// [...] perform the sorting [...]
// enter the search key
System.out.println("Please enter a search key:");
final int position = Arrays.binarySearch(numbers, input.nextDouble());
if (position < 0) {
System.out.println("key is not in the list");
} else {
System.out.println("key is at position " + position);
}

I would write like this
public static void main(String[] args) {
// initialize
double[] numbers = new double[10];
Scanner input = new Scanner(System.in);
// insert variables into array
inputArray(numbers, input);
// start sorting
System.out.println("sorting");
selectionSort(numbers);
// print the sorted array
print(numbers);
// binary search
binarySearch(numbers, input);
// close scanner
input.close();
}
public static void inputArray(double[] numbers, Scanner input) {
System.out.println("Please enter 10 double values:");
for (int i = 0; i < 10; i++) {
System.out.print(">");
numbers[i] = input.nextDouble();
}
}
public static void print(double[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.println("list[" + i + "]" + " = " + numbers[i]);
}
}
public static double[] selectionSort(double[] list) {
double temp;
for (int i = 0; i < (list.length - 1); i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[i]) {
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
return list;
}
public static void binarySearch(double[] numbers, Scanner input) {
System.out.println("Please enter a search key:");
double key = input.nextDouble();
int index = Arrays.binarySearch(numbers, key);
if (index < 0) {
System.out.println(key + " is not in the list");
} else {
System.out.println(key + " is in the list, index = " + index);
}
}

Related

I am unable to delete elements from within my array when i ask for user input

When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.

Comparing an element of an array to an integer

Here is my assignment:
create an array of N random integers in the range of 1 to 100 (you can use the Java random class for this). Get the value of N from the user. Next ask the user to input a number in this range (1 to 100) and then search the array to locate all occurrences of the search number. For each occurrence, print out the number and the position at which it was found.
Then sort the array and search again, displaying all occurrences of the search number. If the search number is not found, then display a message to that effect.
Finally, print the sum of all of the numbers in the array.
I cannot figure out to how compare elements of the array to an integer. Please help! Here is what I have so far
public class Array {
public static void main(String[] args)
{
int num;
int searchNum;
int position = 0;
Scanner in= new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
num = in.nextInt();
int[] myList = new int[num];
for (int i = 0; i < num; i++)
{
Random r = new Random();
int j = r.nextInt(101);
myList[i] = j;
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + (position+1));
}
else
{
position += 1;
}
}
}
}
System.out.println("Enter a number from 1-100 to search");
searchNum = in.nextInt();
for (int i = 0; i < num; i++)
if (searchNum == myList[i])
System.out.println(searchNum + " found at location: " + (i+1));
You was nearly done, I believe.
public class Array {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many random integers you want to create in range (1, 100)");
final int num = in.nextInt();
int[] myList = new int[num];
Random r = new Random();
for (int i = 0; i < num; i++)
{
myList[i] = r.nextInt(101);
}
System.out.println("Enter a number from 1-100 to search");
final int searchNum = in.nextInt();
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found at location: " + i);
}
}
Arrays.sort(myList);
boolean any = false;
for (int i = 0; i < num; i++)
{
if (searchNum == myList[i])
{
System.out.println(searchNum + " found ");
any = true;
}
else if (searchNum > myList[i])
{
break;
}
}
if (!any)
{
System.out.println("the search number is not found");
}
}
}

set each array value with input

I want make like this:
input number[0][0]=201
input number[0][1]=202
input number[1][0]=203
input number[1][1]=204
input last = 203
then find if last input same with above, if true, s.o.p find, else not found
my code:
import java.util.Scanner;
public class array_input {
public static void main(String[] args) {
int a[][];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print("input number[" + i + "][" + j + "]");
int b = scan.nextInt();
a[i][j] = b;
}
}
System.out.print("input what u want");
if (a[i][j] == b) {
System.out.print("found");
} else {
System.out.print("not found");
}
}
}
Maybe you mean something like this ?
import java.util.Scanner;
public class array_input
{
public static void main(String [] args){
int a [][] = new int[2][2];
Scanner scan = new Scanner(System.in);
for(int i = 0;i < 2; i++){
for(int j = 0; j < 2; j++){
System.out.printf("input number[%d][%d]=", i, j);
int b = scan.nextInt();
a[i][j]=b;
}
}
System.out.print("input last = ");
int needle = scan.nextInt();
for (int[] row : a){
for (int col : row){
if(col == needle){
System.out.println("found");
return;
}
}
}
System.out.print("not found");
}
}
Ok, I guess that this is what you want. This checks if the last input of the array is in the array (excluding the last input).
boolean valueInArray = false;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
if(a[i][j]==b && (i != 2 || j != 2)){
valueInArray = true;
}
}
}
if(valueInArray){
System.out.print("found");
} else {
System.out.print("not found");
}

printing distinct numbers java

I am having a hard time with this code. The code is finished but the output is wrong.
My code prints Enter ten numbers: 1 2 3 5 6 6 8 7 4 1
It should print
The distinct numbers are:
1 2 3 5 6 8 7 4
but it doesn't. It prints:
10 10 10 10 10 7
How can I fix it?
Here is my code:
import java.util.*;
public class homework1 {
public static void main(String[] args){
// input from user
Scanner input = new Scanner(System.in);
int [] numbers = new int[10];
boolean[] distinct = new boolean[10];
System.out.println("Enter ten numbers");
for (int i=0; i<numbers.length; i++){
System.out.println("Number " + (i + 1) +": ");
numbers [i] = input.nextInt();
distinct[i] = true;
for(int j = 0;j<10; j++){
if(numbers[i] == numbers[j] && i != j) {
distinct[i] = false;
}
}
}
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=distinct.length;
count++;
}
}
System.out.println("The number of distinct number is: "+numbers[count]);
System.out.println("The distinct numbers are: ");
for(int i= 0; i < 10; i++) {
if(distinct[i]) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
}
}
This line:
numbers[count]=distinct.length;
Is setting your outputs to be the length of the array (Which in this case is hard coded to 10. Try:
int count=0;
for(int j = 0;j<10; j++){
if (distinct[j]){
numbers[count]=numbers[j];
count++;
}
}
Which will set your output to be the distinct number.
Plug: Check out Code Review
This will solve your problem.
If you use HashMap, you will have less code.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> distinctNumbers = new HashMap<Integer, String>();
// input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers");
for (int i = 0; i < 10; i++) {
System.out.println("Number " + (i + 1) + ": ");
Integer numberEntered = input.nextInt();
distinctNumbers.put(numberEntered, null);
}
System.out.println("The number of distinct number is: " + distinctNumbers.size());
System.out.println("The distinct numbers are: ");
Set<Integer> keys = distinctNumbers.keySet();
for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.print(" "+ integer);
}
}
}
Remove line numbers[count] = distinct.length; This make your output are all 10
Then, I change your code a little to make it run right:
...
int count = 0;
for (int j = 0; j < 10; j++) {
if (distinct[j]) {
//numbers[count] = distinct.length; //remove it, it nonsense
count++;
}
}
// distinct number should be count, not number[count]
System.out.println("The number of distinct number is: " + count);
....
public static void main(String[] args) {
int arr[] = {1,3,5,4,7,3,4,7};
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.containsKey(arr[i])){
int value = frequency.get(arr[i]);
frequency.put(arr[i], value + 1);
}
else {
frequency.put(arr[i], 1);
}
}
for(Map.Entry<Integer, Integer> entry : frequency.entrySet()) {
System.out.println(entry.getKey());
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_5 {
public static void main(String[] args) {
// Print distinct numbers
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers: ");
for (int i = 0, j = 0; i < 10; i++) {
if (storeDistinctNumbers(j,input.nextInt(), numbers))
j++;
}
for (int i = 0; numbers[i] != 0 ; i++)
System.out.print(numbers[i] + " ");
}
public static boolean storeDistinctNumbers(int j, int num, int[] numbers) {
for (int e: numbers) {
if (e == num)
return false;
}
numbers[j] = num;
return true;
}
}

Java InputMismatchException?

I'm try to do an exception on my codes if ever the user puts a string instead of an integer. My codes will swap the position of the largest index to the smallest index. Can you try to rectify this with me?
import java.util.Scanner;
import java.util.InputMismatchException;
public class ArraySwap
{
static int h;
static Scanner data = new Scanner(System.in);
static int[] list = new int[10];
public static void main(String[] args)throws InputMismatchException
{
System.out.println("Please enter 10 numbers: ");
for(h = 0; h < list.length; h++)
{
try
{
list[h] = data.nextInt();
}
catch(InputMismatchException h)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ h.toString());
continue;
}
}
swap();
}
public static void printArray(int[] list)
{
int counter;
for(counter = 0; counter < list.length; counter++)
System.out.print(list[counter] + " ");
}
public static int smallestIndex(int[] list)
{
int length1 = list.length;
int counter;
int minIndex = 0;
for (counter = 1; counter < length1; counter++)
if (list[minIndex] > list[counter])
minIndex = counter;
return minIndex;
}
public static int largestIndex(int[] list)
{
int length2 = list.length;
int counter;
int maxIndex = 0;
for (counter = 1; counter < length2; counter++)
if (list[maxIndex] < list[counter])
maxIndex = counter;
return maxIndex;
}
public static void swap()
{
System.out.print("List of elements: ");
printArray(list);
System.out.println();
int min_index = smallestIndex(list);
int max_index = largestIndex(list);
int min_num = list[min_index];
System.out.println("Largest element in list is: "
+ list[max_index]);
System.out.println("Smallest element in list is: "
+ list[min_index]);
min_num = list[min_index];
list[min_index] = list[max_index];
list[max_index] = min_num;
System.out.print("Revised list of elements: ");
printArray(list);
System.out.println();
}
}
You are already doing exception handling on the integer inputs:
try
{
list[h] = data.nextInt();
}
catch(InputMismatchException h)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ h.toString());
continue;
}
}
Your issue is that in your catch block, you are naming your InputMismatchException object as h. This is also your loop count variable. Change that.
catch(InputMismatchException ex)
{
System.out.println("Please re-enter 10 numbers as an exception "
+ ex.toString());
continue;
}
Also your second issue is that the print statement in your catch block is being automatically taken as Scanner input for your next loop. So the program isn't allowing input of any more numbers once an error string has been entered. What you need to do is first use a data.next() to consume your error message.
catch (InputMismatchException ex) {
System.out.print("Please re-enter 10 numbers as an exception "
+ ex.toString());
data.next();
}

Categories

Resources