Comparing an element of an array to an integer - java

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");
}
}
}

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.

java array searching method

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);
}
}

Problems with my for loops printing out my arrays

can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];

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;
}
}

How can I check if the user entered in an array is palindrome or not?

I need help guys I have been checking on google for similar question but I cant find the most suitable answer for this. Here is my output.
Enter 3 Elements
23
Is a palindrome
22
Is not a palindrome
11
Is not a palindrome
The program:
public static void main(String [] args)
{
int number = 0;
int reverse =0;
int numCopy = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many numbers you want to enter");
int num = scan.nextInt();
System.out.println("Enter "+num +" Elements");
numCopy = num;
int[] array = new int[num];
for(int i = 0; i < num; i++)
{
array[i] = scan.nextInt();
int digit = numCopy % 10;
numCopy = numCopy / 10;
reverse = (reverse * 10) +digit;
if(num == reverse)
{
System.out.println("Is a palindrome");
}
else
{
System.out.println("Is not a palindrome");
}
}
}
A Palindrome by definition is the same forwards and back so 11 would be and 22 would be. 23 would not etc.
Quick easy psudo code for checking if Palindrome as a STRING:
function isPalin(string str)
if(str.length() == 0) {
return true;
}
int end = str.length() - 1;
int start = 0;
while(start < end) {
if(str[start++] != str[end--]) {
return false;
}
}
return true;
If you have numbers just covert it to a string then use the function.
A palindrome, for example, we need to consider two difference case:
AA and ABA.
These two are all palindrome. So for integers, you need to confirm its length is even or odd. Then check from both sides: start, end.
This should get the correct result.
you should have your program like below:
public static void main(String[] args)
{
int number = 0;
int reverse =0;
int numCopy = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many numbers you want to enter");
int num = scan.nextInt();
System.out.println("Enter "+num +" Elements");
numCopy = num;
String[] array = new String[num];
for(int i = 0; i < num; i++)
{
array[i] = new Integer(scan.nextInt()).toString();
String rev="";
for(int k=array[i].length()-1;k>=0;k--){
rev +=array[i].charAt(k);
}
if(array[i].equals(rev))
{
System.out.println("Is a palindrome");
}
else
System.out.println("Is not a palindrome");
}
}

Categories

Resources