Finding the middle element of an array - java

Java newbie here.
I have the following code from which I would want it to return the middle elements of the array. How do I go about that? I don't want to just manually return the elements at position 5 and 6, which are the median elements here. I would it in a way that would work for any array type, even or odd.
/**
* Created by root on 2/11/15.
*/
import java.util.Scanner;
import java.util.Arrays;
public class test {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Create a string array to store the names
String arrayOfNames[] = new String[10];
System.out.print("Enter 10 names\n");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("\n" + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//show name one by one
Arrays.sort(arrayOfNames);
System.out.print("Names ");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("" + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}

Write a method like :
void printMiddleofArray(String[] arrayOfNames) {
if (arrayOfNames.length %2 ==0)
{
System.out.println(arrayOfNames[arrayOfNames.length /2]);
System.out.println(arrayOfNames[(arrayOfNames.length /2)-1]);
} else {
System.out.println(arrayOfNames[(arrayOfNames.length /2)-1]);
}
}

Here is another solution step by step. It is less elegant of course, but tailored for beginners. It uses the modulus operator to check for even or odd lengths, adjusts for using zero indexed arrays, then makes a decision based on the outcome.
In main() declare a String and initialize it with a call to this method, with your names array passed in as a parameter. Then in the next line, print the String.
public String returnMiddleElement( String[] input ){
/* Initialize result variable */
String result = "";
/* Determine if the array is odd or even */
int value = input.length % 2;
/* Obtain the middle index */
int middleIndex = input.length/2;
/* Adjust for the zero index of arrays */
int evenMid = middleIndex - 1;
if( value == 0 ){
/* The array is even, so obtain the two middle elements */
result += input[evenMid] + "\n" + input[(evenMid+1)];
}
else{
/* The array is odd, so obtain the single middle element */
result += input[middleIndex];
}
return result;
}

Related

How to sort insert and prioritize most recent in an Array List?

I tried checking the array to see if the number is already listed, if the user happens to input a number twice thus number should be placed to the top being its most recent and everything else should be shifted down. in Short given the array [ 4, 5, 6, 7, 9] if the users inputs 7 it should be changed to [7, 4, 5, 6, 9].
//Array Created
int intArray[] = new int[5];
//Number of values in the array
int count = 0;
//Value user enters
int userInput = 0;
//Receive user inputs
Scanner in = new Scanner(System.in);
//First Prompt
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
//Keep asking for number if invalid
while((userInput < 0) || (userInput > 10)){
System.out.println("Invalid number. Must be between 1 - 10\n");
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
}
intArray[count] = userInput;
count++;
while(userInput != 0){
//Keeps Track of the numbers inputed
System.out.println("There is currently " + count + " On The Table.");
for(int i = 0; i < count; i++){
System.out.print(intArray[i] + " ");
}
System.out.print("\n\n");
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
//Don't Allow numbers bigger than 10 or less than 1
while(userInput < 0 || userInput > 10){
System.out.println("Invalid number.\n");
System.out.println("Enter The File You Wish To Use. Enter 0 to stop:");
userInput = in.nextInt();
}
if(count == intArray.length){
int tempPrev;
for(int i = (intArray.length - 1); i > 0; i--){
//Store the previous value
tempPrev = intArray[i - 1];
//Assign current index to what was in previous
intArray[i] = tempPrev;
}
intArray[0] = userInput;
count = intArray.length;
} else {
intArray[count] = userInput;
count++;
}
}
System.out.println("The end.");
}
}
I will provide a solution for arrays and I will presume that if a new item is specified by the user, it will get to the head of the array and pulling everything to the right, with the oldest falling out of the array:
int index = intArray.indexOf(input);
if (index < 0) {
index = intArray.length; //we default to the last item that would disappear
for (int i = index; i > 0; i--) {
intArray[i] = intArray[i - 1];
}
intArray[0] = input;
Let's start with the fact that you need to have uniqueness in your array, so you want a set.
The best (quick) implementation you can find using the standard libraries is LinkedHashSet<Integer>.
If we analyze its documentation for a second we can see that by default it preserves the insertion order, which is perfect for your case, however, we also notice that it ignores re-insertions if the element is present:
This linked list defines the iteration ordering, which is the order in
which elements were inserted into the set (insertion-order). Note that
insertion order is not affected if an element is re-inserted into the
set. (An element e is reinserted into a set s if s.add(e) is invoked
when s.contains(e) would return true immediately prior to the
invocation.)
To get around this problem, you can create a utility function that first attempts to remove the number you want to insert from the set, then reinserts it again, thus changing the insertion order.
E.g.
final var set = new LinkedHashSet<Integer>();
...
static void addFirst(Set<Integer> set, int val) {
set.remove(val);
set.add(val);
}
At this point you can take its iterator and read the set values as you need it most.
Note:
Since this is only efficient if the reads are in the direction of the iterator or if they are few compared to the inserts, so, if you have to iterate often in reverse then you are better off using a LinkedList<Integer>
directly and doing the same little game as remove() and add().
That's because, unfortunately although the set is doubly linked, the only way you can scroll through it in reverse is as follows:
final var list = new LinkedList<>(set);
final var it = list.descendingIterator();
while(it.hasNext()) {
int item = it.next();
// do something
}
Keeping to you existing scheme, here is one way this could be accomplished. Read the comments in code:
Runnable code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AddNewButDeleteDuplicate_Demo {
// System related newline character sequence. Could be used anywhere.
public static final String LS = System.lineSeparator();
// Open a keyboard input stream. Could be used anywhere.
public static final Scanner userInput = new Scanner(System.in);
// Application Entry Point:
public static void main(String[] args) {
// App started this way to avoid the need for statics:
new AddNewButDeleteDuplicate_Demo().startApp(args);
}
private void startApp(String[] args) {
// This code can create an int[] array of any size:
int[] intArray; // Declare our int[] array
int count = 1; // Counter used for 'number of entries' display:
// Inform of upcomming prompt:
System.out.println("Enter integer numbers (1 to 10) to add to Array" + LS
+ "or enter 's' at any time to stop.");
/* List Interface of Integer to hold all integer values supplied
by User.This List is later converted to an int[] Array. List
is used because it can grow dynamically whereas Arrays can not.
This then allows the User to enter as many elements as desired
which the rules specify 10 elements max since we can only enter
values from 1 to 10. */
List<Integer> intList = new ArrayList<>();
// To hold the current value supplied by User:
String inputValue = "";
// Repeatable User Entry Prompt with a Stop mechanism and entry Validation:
while (inputValue.isEmpty()) {
// Prompt:
System.out.print("Entry #" + count + ": -> ");
// Get User Entry:
inputValue = userInput.nextLine().trim();
// Is 'Stop' desired?
if (inputValue.equalsIgnoreCase("s")) {
// Yes...Inform and exit `while` loop
System.out.println("Done Creating Array!");
break; // Exit `while` loop.
}
/* Validate User Entry. If the entry IS NOT a string representation
of a unsigned integer value from 1 to 10 then indicate as invalid
and allow the User to try again. */
if (!inputValue.matches("\\d+") || Integer.parseInt(inputValue) < 1 ||
Integer.parseInt(inputValue) > 10) {
System.out.println(">> Invalid Entry (" + inputValue + ")! Try again... <<" + LS);
inputValue = ""; // Empty variable to ensure re-loop.
continue; // Jump to top of loop:
}
/* If we made it to this point, then the User supplied value is
valid. Convert the User supplied string numerical value to
int data type. */
int val = Integer.parseInt(inputValue);
/* For demo purposes, display the Current List before checking
for duplicates: */
System.out.println("List Previous: -> " + intList);
// Check for duplicate...
/* If List is not empty and the int value of the User supplied
number IS currently contained within the List then remove the
duplicate value already contained within the List and insert
the new (same) value to the beginning of the List at index 0. */
if (!intList.isEmpty() && intList.contains(val)) {
int idx = intList.indexOf(val);
/* If the duplicate is already located at index 0 of the List
then there is no point doing any modification to the List
since this is where we would place the new value anyways. */
if (idx != 0) {
intList.remove(idx);
intList.add(0, val);
// Inform of duplicate entry:
System.out.println(">> Duplicate Entry (" + inputValue + ")! "
+ "Old value removed at index " + idx + " and New value inserted "
+ "into index 0. <<" + LS);
}
}
// Otherwise, just add the int value to the List:
else {
intList.add(val);
}
/* For demo purposes, display the Current List after checking
for duplicates: */
System.out.println("List Current: -> " + intList);
inputValue = ""; // Empty variable to ensure re-loop.
count++; // Increment User entry count:
}
// Convert the List to an int[] Array using Streams:
intArray = intList.stream().mapToInt(d -> d).toArray();
// Display int[] Array:
System.out.println("The intArray[] Array: -> " + Arrays.toString(intArray));
}
}

How to sum integer inputs in Java, and display the results in an array at the end of the program?

I am trying to create a "calculator", except it needs to print each element that was used to compose the sum total. This printing of the array elements needs to happen at the end of the program, when the user inputs 0 twice in a row.
Upon entering an input, the integer values will be stored in an array. Once the end of the program has been reached, the contents of this array will be printed. However, if the end of the program has not been reached, the program continues while the user adds consecutive inputs.
Currently, the program will only print one element at a time, instead of every element that was used to calculate the total. I've spent hours trying to debug, and any guidance would be greatly appreciated!
import java.util.*;
public class AddingMachine {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean justStarting = true;
int total = 0;
int subtotal = 0;
int input;
int last = 1;
int MAXIMUM_NUMBER_OF_INPUTS = 100;
while (true) {
input = scanner.nextInt();
if (input == 0) {
if (last == 0) {
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
subtotal += input;
last = input;
int[] numbers = new int[args.length];
for (int i = 0; i < args.length; i++) {
numbers[i] = last;
}
System.out.println(Arrays.toString(numbers));
}
}
When summing the input in your loop, you could store the users input into a List of integers. Once you need to reprint them, you can iterate over the List and print the elements you stored.
Example:
List<Integer> storedUserInput = new ArrayList<>();
while (true) {
input = scanner.nextInt();
storedUserInput.add(input);
if (input == 0) {
if (last == 0) {
for(Integer i : storedUserInput){
System.out.print(i + " + ");
}
System.out.println("total " + total);
return;
}
System.out.println("subtotal " + subtotal);
total += subtotal;
subtotal = 0;
}
}
Within the while loop, the array is re-initialized each time:
int[] numbers = new int[args.length];
so any previously entered value is lost. Also, the purpose of the for loop within the while is not clear.
Also, unless using an array is a requirement, you really don't need an array. You could just use a StringBuffer and append the entered values.

Frequency Array and Histogram in Java

I have to make the following program.
Write a program that builds a frequency array for data values in the range 1 to 20 and then prints their histogram. The data is to be read as input from the user. Add the following functions to your program:
a. The getData function takes input from the user and stores the data in an array.
b. The printData function prints the data in the array.
c. The makeFrequency function examines the data in the array, one element at a time, and adds 1 to the corresponding element in a frequency array based on the data value.
d. The makeHistogram function prints out a vertical histogram using asterisks for each occurrence of an element. For example, if there were five value 1s and eight value 2s in the data, it would print
1: *****
2: ********
I managed to make getData function but I can't make the other 3. Any help would be appreciated. Here is my code
import java.util.Scanner;
public class FrequencyArray {
static Scanner scan = new Scanner(System.in);
public void getData() {
System.out.println("Enter the size of array: ");
int nums = scan.nextInt();
int[] a = new int[nums];
for (int i = 1; i < a.length; i++) {
System.out.print("Enter the numbers: " + i + ":");
a[i] = scan.nextInt();
}
}
public void printData() {
getData();
}
public static void main(String[] args) {
FrequencyArray array = new FrequencyArray();
array.getData();
}
}
To print such an array, all you would need is another for-loop - loop from 0 to the array's length, and print both the loop counter's value, and the value stored in the array at that index.
System.out.println(index + ":" + array[index]);
For the histogram, do a similar loop, but for each value of the array, append an asterisk to the current line for however many instances of said number there are.
System.out.print(index);
//from 0 to the amount of this number, call System.out.print("*");
System.out.println();
Use TreeMap to store the number and their frequency in a sorted order once you get the data
then iterate over the TreeMap to print the number followed by the stars denoting the count of the value
public void printData() {
int [] numArray = getData();
Map<Integer,Integer> valueCountMap = new TreeMap();
for(int i=0;i<numArray.length;i++) {
int num = numArray[i];
if(valueCountMap.get(num) == null) {
valueCountMap.put(num,0);
}
int count = valueCountMap.get(num);
valueCountMap.put(num,count+1);
}
for(Map.Entry<Integer,Integer> entry:valueCountMap.entrySet()) {
int num = entry.getKey();
int value = entry.getValue();
System.out.print(num+":");
for(int i=0;i<value;i++) {
System.out.print("*");
}
System.out.print(" ");
}
}
Following assumptions i have made getData must return interger array and you need to print in one line. Following rectification i have done to your code
in getData i = 0 not i = 1

Odd and Even Numbers [duplicate]

This question already has an answer here:
Odds and Evens Applications
(1 answer)
Closed 8 years ago.
How can I display all the evens on one line and all the odds on the next line? need to display 25 integers.
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
System.out.print ("EVENS & ODDS");
for(int i=0; i < 25; i++)
{
numbers [i] = (int) (Math.random()*99) + 1;
if(numbers[i]%2 == 0)
System.out.println(numbers[i] +" " );
else
System.out.println(numbers[i] +" " );
}
}
}
Instead of printing each number immediately, consider building up two strings (the first made up of the evens, and the second the odds). Then print the result strings when you're done. This should require just one loop.
In your providing code you print every number at time when it processed.if you want to print in one line so one possible solution is that you have store numbers in some array, or a string instead of display the number.
So in your code this line must change
System.out.println(numbers[i] +" ");
like this (if you want to store them in string variable)
even += numbers[i] +" ";
and later when loops end you can print out both line one by one.
Hope this will help you
//Snippet
if(numbers[i]%2 == 0)
even += numbers[i] +" ";
else
odd += numbers[i] +" ";
//after loops ends
System.out.println(even);
System.out.println(odd);
Just save all the evens in one array and all the odds in another and then print them seperately.
Well right now you are printing them all individually. what you could do is before the for loop declare a String for the odds and a String for the evens. and initialize them to "". then in the for loop instead of printing, just add the numbers[i] to the string and print them outside of the for loop
Alternatively ...
Read the javadoc for PrintStream, 'cos System.out is a PrintStream. Look at the different print methods available.
Create a string to hold them and just display them at once at the end:
public class OddsOrEvens
{
public static void main(String[] args)
{
int[] numbers = new int[25];
String evens = "";
String odds = "";
System.out.print ("EVENS & ODDS");
for(int i = 0; i < 25; i++)
{
numbers [i] = (int) (Math.random() * 99) + 1;
if(numbers[i] % 2 == 0)
evens += numbers[i] + " "; // save it to evens string
else
odds += numbers[i] + " "; // save it to odds string
}
// now print them
System.out.println("Evens: " + evens);
System.out.println("Odds: " + odds);
}
}

How to check if array indexes are empty and if so check the next?

Anybody got any idea on how I can check if an array indexes(not just one index) are empty and if is empty or zero put a value there. And also if all the indexes are all not empty print an error.
Sorry unfortunately I can't give rep.
import java.util.Scanner;
public class Myhash {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] myData = new int[17];
int [] newData = new int [17];
System.out.println("Please enter 16 integer numbers");
for(int i= 0; i<myData.length; i++){
//System.out.print("Please enter 16 numbers");
Scanner input = new Scanner(System.in);
int data =input.nextInt();
myData[i]=data;
int num3 = data % 17;
newData[num3]=data;
}
System.out.println("These are the numbers you entered\n");
System.out.printf("%s%8s \n", "Index", "Value");
for(int t=0; t<myData.length; t++){
System.out.printf("%5d%8d\n", t, myData[t]);
}
System.out.println("\n");
System.out.println("The Hash Function:\n\n");
System.out.printf("%5s%8s \n", "Index", "Value");
for(int s=0; s<newData.length; s++){
System.out.printf("%5d%8d\n", s, newData[s]);
}
}
}
on here:
for(int s=0; s<newData.length; s++){
System.out.printf("%5d%8d\n", s, newData[s]);
}
how do check for more than one index(if empty?
If the index is empty how do check for the next index and if that one is not empty how do i check the next one, etc?
Elements in primitive arrays can't be empty. They'll always get initialized to something
If you declare the array like so
int [] newData = new int [17];
then all of the elements will default to zero.
For checking if an element is not entered, you can use a simple loop :
for(int i=0;i<newData.length;i++)
{
if(newData[i]==0)
System.out.println("The value at " + i + "is empty");
}
Although , the above code will not work in your case, because the user might enter 0 as an input value and still this code will consider it to be empty.
What you can do is, initialize the array with all values as -1, and specify at the input prompt that only values >=0 can be entered .
The initialization can be done like this:
int[] newData = new int[17];
for(int i=0;i<newData.length;i++)
{
newData[i]= -1;
}
Then you can ask the user for input and do the processing. Then you can use this:
for(int i=0;i<newData.length;i++)
{
if(newData[i]==-1)
System.out.println("The value at " + i + "is empty");
}
Here:
for(int i = 0; i < array.length; i++)
{
if(array[i] == null)
continue;
}

Categories