Sorting Strings as inserted into array in Java - java

I'm trying to create a program that takes user input and sorts it alphabetically as it comes in using compareTo String operations (not array.sort) and prints the final sorted array at the end. I've got most of the body of this problem down but am lost once I get to the sort function. Does anyone have any ideas on how I might be able to finish out the SortInsert method?
import java.util.*;
public class SortAsInserted {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int array_size = GetArraySize();
String[] myArray = new String[array_size];
for (int i = 0; i < array_size; i++){
String nextString = GetNextString();
String[] sortedArray = SortInsert(nextString, myArray);
}
PrintArray(sortedArray);
}
input.close();
}
}
public static String[] SortInsert(String nextString, String[] myArray){
for(int i = 0; i < myArray.length;)
if (nextString.compareToIgnoreCase(myArray[i]) > 0) {
i++;
//if current text is less(alphabetically) than position in Array
}else if (nextString.compareToIgnoreCase(myArray[i]) < 0){
}
}
public static int GetArraySize(){
Scanner input = new Scanner(System.in);
System.out.print("How many items are you entering?: ");
int items_in_array = input.nextInt();
return items_in_array;
}
public static void PrintArray(String[] x) {
for (int i = 0; i < x.length; i++){
System.out.print(x[i]);
}
}
public static String GetNextString(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the next string: ");
String next_string = input.nextLine();
return next_string;
}
}

There are a number of problems with this code. First I'll answer your immediate question, then enumerate some of the other problems.
The SortInsert method takes a String[] that will have been initialized with null values, so you will need to take that into account. The for loop would look something like this. (I'm using comments instead of writing the actual code since I'm not doing the project)
for (int i=0; i<myArray.length; ++i) {
if (myArray[i] == null) {
// we found a blank spot. use it to hold nextString.
break;
} else if (nexString.compareToIgnoreCase(myArray[i]) < 0) {
// nextString should be in spot i, so make room for it
// by shuffling along whatever is in the array at "i" and later
// by one place, then put nextString into position "i"
break;
}
// otherwise we'll just move to the next position to check
}
Now for the other issues.
You have a Scanner object in main that is never used. There's no point in having it and closing it at the end if your other methods make their own.
myArray will always be the sorted array so there's no point in making a local variable called sortedArray and return it from SortInsert. Note that your attempt to print sortedArray would fail anyway because that local variable is only in scope within the for loop.
When printing it should be myArray being passed to PrintArray.

If you're going to sort as you go, the TreeMap data structure is what you should be using, not an array. However, if you want to sort as you go with an array, you need to add some lines into your else if clause in SortInsert (should be sortInsert, BTW). (Another question: why is it else if rather than just else?)
The lines should create a new array of size one greater than the existing array, copy the first i-1 elements of the old array to the new array, put the new element in position i, then copy the remaining elements of the old array into positions one greater in the new array.

Once you find the position you wish to insert at, you have to shift all of the following elements down by one. Something like the following:
String temp = array[position];
for (int j = position+1; j < array_size-1; j++) {
String temp2 = array[j];
array[j] = temp;
temp = temp2;
}
array[array_size-1] = temp;

Related

Java: How to fill out two arrays, alternating between the two

I have a program that has two String arrays defined and initialized. I now want to accept inputs from the user to fill out the indexes of each array. I want the user to input index[i] for array 1 and then index[i] for array 2 and so on until both arrays are filled.
I attempted to use a nested loop to do this, but I was getting an out of bounds error.
Unfortunately, Google was not helpful as I kept finding the .fill() method, which I cannot currently use in my course.
The code below contains elements for the rest of the program which I haven't written. The below code is meant to complete the first part of the program and that is to get the list of words into the first two arrays and then output them to make sure they were filled correctly.
EDIT: Even though I got my answer, I tried updating the question for clarity. It looks like I was vastly overthinking the problem. It was my first time working with more than one array.
import java.util.Scanner;
public class LabProgram {
public static int findWordInWordList(String[] wordList, String wordToFind, int numInList) {
return -1; //Will replace words in a sentence, to be used coded and used later.
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] ogWords; //words to replace.
String[] newWords; //words to replace with.
String[] sentence; //the sentence that will be searched and have words replaced.
int pairSize; //size of the first two arrays.
pairSize = sc.nextInt();
ogWords = new String[pairSize];
newWords = new String[pairSize];
for (int i = 0; i < ogWords.length; i++) {
ogWords[i] = sc.next();
for (int j = 0; j < newWords.length; j++) {
newWords[j] = sc.next();
}
}
for (int i = 0; i < pairSize - 1; i++) { //Testing arrays
System.out.println(ogWords[i] + " " + newWords[i]);
}
}
}
The final for loop is just to test that the arrays were filled correctly, which isn't working right now :p.
Unless I've misunderstood your question, I think you're after:
for (int i = 0; i < pairSize; i++) {
ogWords[i] = sc.next();
newWords[i] = sc.next();
}

Cycle while with scanner hasNext()

I have a problem when I try to run my work.
I have to put in some numbers by console and It should arrange in ascending order them and save to an array.
I thought that method hasNext worked well with String.nextLine(), but it seems to still in loop.
thanks for help
import java.util.Scanner;
public class OrdinamentoMaggiore{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Digita dei numeri e te li mettero' in ordine crescente: ");
String Numeri = sc.nextLine();
int dimArray = 0;
while (sc.hasNext(Numeri)){
dimArray++;
System.out.println("Dimensione array: " + dimArray);
}
int min = 0, max = 0, temp;
int[] mioArray = new int[dimArray];
for (int i = 0; i <= mioArray.length; i++){
mioArray[i] = Integer.parseInt(sc.next(Numeri));
}
for (int j = 0; j <= mioArray.length; j++){
for (int h = 1; h <= mioArray.length; h++){
if (mioArray[j] < mioArray[h]){
continue;
}
else {
temp = mioArray[j];
mioArray[j] = mioArray[h];
mioArray[h] = temp;
}
}
}
System.out.println("Min: " + mioArray[0]);
System.out.println("Max: " + mioArray[dimArray]);
sc.close();
}
}
The problem is that you are reading the first line of input into the variable Numeri. Then, you are calling hasNext on Numeri which isn't working the way you think it is. Scanner.hasNext is defined here as:
Returns true if the next token matches the pattern constructed from
the specified string.
So it is using the string in Numeri as the pattern it needs to match. Definitely not what you want.
I would recommend a list and doing something like this:
List<Integer> numberList = new ArrayList<>();
while (sc.hasNextInt()) {
numberList.add(sc.nextInt());
}
Collections.sort(numberList);
A list is nice because you don't have to explicitly tell it the size. That avoids your first loop. Now, the loop goes continues reading from System.in until it encounters something that isn't an integer and adds them to the list.
Finally, it uses Collections.sort to sort the list. How beautiful is that? Your whole program can be reproduced in just a few lines. Definitely try and learn the libraries and functions that are available to you. It can save you a lot of time and effort. Let me know if you have questions.

How to remove an element from an array

In Java, The teacher taught us how to remove an element from an array without using array utils and so on. So I tried the method he gave to us. It updates the index value exactly as I want. after it changes the index value, I want it to delete the last index, "sizeOfArray-1"
but I couldn't do that! Any help?
Here the code:
import java.util.Scanner;
public class Arrays {
static int x[] = { 1, 2, 3, 4, 5, 6, 7 };
static Scanner input = new Scanner(System.in);
public int search(int target) {
for (int index = 0; index < x.length; index++) {
if (x[index] == target)
return index;
}
return -1;
}
public void deleteIndex(int target) {
int deleted = search(target);
if (deleted == -1)
System.out.println("Entry Not Found!");
else {
x[target] = x[7-1];
}
}
public static void main(String[] args) {
Arrays f = new Arrays();
int counteri = 0;
int counterj = 0;
for (int j = 0; j < x.length; j++) {
System.out.print(counterj + "=>" + x[j] + " \n");
counterj++;
}
f.deleteIndex(input.nextInt());
for (int i = 0; i < x.length; i++) {
System.out.print(counteri + "=>" + x[i] + " \n");
counteri++;
}
}
}
First of all you have to change this line
x[target] = x[7-1];
to this :
x[deleted] = x[7-1];
because you find an element in your search function, and return its index to deleted so you have to do your action in x[deleted] not x[target]
Your code just replace the actual value of element with amount of last element in here :
else {
x[target] = x[7-1];
}
So when you want to (so as you call it) delete the last element it just replace last element with it self so it didnot do anything.
You can just simply assign another value that doesnt exist in your array for instance -1 and you could see your function works as you want.
a thing like this :
else {
x[deleted] = -1;
}
But it is not delete actually, and you cant delete items of array in java.
You really cannot delete an item from an array in Java. Here is some pseudo code that shows what you can do instead:
create a new array that has size -1 of the original array
start looping, keep track of the current index
copy the item(s) from the original array to the new array corresponding to the current index if it should be kept (otherwise skip the item that should be removed)
return the new array
An array in Java has fixed predefined length, once you initialize the array you cannot actually remove an element from it. The best thing you can do is to create another array containing all the elements of the original array without that specific one.
//delete the element the perticular element in a position//
import java.util.*;
class main13
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range");
int no=sc.nextInt();
System.out.println("Enter the array elements");
int a[]=new int[no];
int i,j;
for(i=0;i<no;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter the element you want to delete");
int d=sc.nextInt();
for(i=0;i<no;i++)
{
if(d==a[i])
{
for(j=i;j<no-1;j++)
{
a[j]=a[j+1];
}
break;
}
else
{
System.out.println("Element not found");
System.exit(0);
}
}
System.out.println("After deletion:");
for(i=0;i<no-1;i++)
{
System.out.println(a[i]);
}
}
}

Read text file for integers and storing to array using scanner and exceptions

I'm trying to loop through a text file for integers and store integers found into an array.
Using a try-catch to determine which words are integers and which are not using InputMismatchException, removing the non-int strings from the input stream. As well as a NoSuchElementException for blank lines in the file.
My main issue is storing the integers and printing those integers in the array, in my second method :o . It also appears my loop is also recording non-ints as null as well. They aren't suppose be stored into the array.
public static void main(String[] commandlineArgument) {
Integer[] array = ReadFile6.readFileReturnIntegers(commandlineArgument[0]);
ReadFile6.printArrayAndIntegerCount(array, commandlineArgument[0]);
}
public static Integer[] readFileReturnIntegers(String filename) {
Integer[] array = new Integer[1000];
// connect to the file
File file = new File(filename);
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
}
// If file not found-error message
catch (FileNotFoundException Exception) {
System.out.println("File not found!");
}
// if connected, read file
if (inputFile != null) {
// loop through file for integers and store in array
while (inputFile.hasNextLine()) {
for(int i = 0; i<array.length; i++)
{
try{
array[i] = inputFile.nextInt();
}
catch(InputMismatchException excep1)
{
String word = inputFile.next();
}
catch(NoSuchElementException excep2){
}
}
}
}
return array;
}
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
//prints number of integers from file
//prints each integer in array
}
}
The approach taken in the first method is a bit flawed, since you're incrementing the i variable whether or not an integer is read.
So for example, if the file looked like this:
4
Hello
5
e
7
The beginning of your array would look like
[4, null, 5, null, 7...]
So you will end up with an array of size 1000, which has nulls at unpredictable places in there.
A slightly better approach would be this:
Keep a separate count variable that says how many integers you actually read.
Add items to the array at index count and not at i (since i just says how many lines you've looked at, whereas count will tell you how many integers you've come across).
When you're finished reading them, either
pass the count variable to the method that prints the array (so it knows only to look at the first count items), or
just copy the entire array into a new array of size count.
Example incorporating this into your code:
if(inputFile != null) {
// the number of integers we've read so far
int count = 0;
// loop through file for integers and store in array
while(inputFile.hasNextLine()) {
for(int i = 0; i < array.length; i++) {
try {
array[count] = inputFile.nextInt();
count++;
} catch(InputMismatchException excep1) {
String word = inputFile.next();
} catch(NoSuchElementException excep2) {
}
}
}
}
Then to copy into a correctly sized array,
Integer[] newArray = new Integer[count];
for(int i = 0; i < count; i++) {
newArray[i] = array[i];
}
and just return newArray instead of array.
Your print method will then simply have the same signature and functionality you'd expect:
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
for(int i = 0; i < array.length; i++) {
// print the number at array[i], and whatever else you want to print
}
}
This is probably the better approach, as you can still keep all the method signatures the same, and don't need to mess around with returning multiple variables or changing global state.
Or alternatively, if you don't want to copy the relevant bits into a new array, then you could just pass the count variable somehow to your second method, and do something like
for(int i = 0; i < count; i++) {
System.out.println("\tindex = " + i + ", element = " + array[i]);
}
Key difference there is you're iterating up to count, and not up to array.length.
You would need to find a way to return that from your first method along with the array (or maybe set a static variable somewhere), and you would then need to change the signature of your second method to be
public static void printArrayAndIntegerCount(Integer[] array, int count, String filename) {
...
}
Assuming all you logic for reading integers from file are correct and also hoping this is kind of home work. Though the following implementation is not the right approach, it just solves your purpose. All we are doing here is iterating all the elements in the array until it reaches the null and keep writing them into a buffer.
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
StringBuilder sb = new StringBuilder();
int count = 0;
for(Integer i : array) {
if(i != null) {
count++;
sb.append("index = ").append(i).append(", element = ").append(array[i]).append("\n");
} else {
break;
}
}
System.out.println("number of integers in file \""+filename+"\" = "+count);
System.out.println(sb);
}
Replace your catch statement with:
catch(InputMismatchException excep1)
{
String word = inputFile.next();
i-=1;
}
You were incrementing the array counter if it found a word. I have run my own test and this worked for me to fix your issue.
public static void printArrayAndIntegerCount(Integer[] array, String filename) {
String message = "";
int i = 0;
while(i < array.length && array[i]!=null){
message = message + "index = "+i+", element = "+array[i]+"\n";
i+=1;
}
System.out.println("number of integers in file \""+filename+"\" = "+i);
System.out.println(message);
}

NullPointerException error while trying to remove a string word from an Array in a remove() method

I'm making this method remove() which takes a String word as argument, to delete from a global Array "words", but I keep getting a NullPointerException for some reason I cannot find, been stuck for hours.
Basically I check for if the word is in the first position, else if is in the last position, or else if it is in neither so I check all the array, and add the first half before the position of the word, and then add the second half after the position of the word in the array, as to skip it and "delete it". But I'm getting a NullPointerException in the for loop looking for the position of the word in the array. Code for the method is here:
public void remove(String a){
String[] temp_arr = new String[words.length-1]; // make array with 1 less length for deleted
if(words[0].equals(a)){ // if the word is the first in the array
for(int x=0, z=1; x<temp_arr.length; x++,z++)
temp_arr[x]=words[z];
words = temp_arr;
} else if(words[words.length-1].equals(a)){ // if the word is in the last position of the array
for(int x=0, z=0; x<temp_arr.length; x++,z++)
temp_arr[x] = words[z];
words = temp_arr;
} else{ // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop, in the if(words[k].equals(a))
int k=0;
for (; k<words.length; k++){ // find the position of the word to delete
if (words[k].equals(a)) {
break;
}
}
for (int i = 0; i < k-1; i++){ // add first part of array before the word
temp_arr[i] = words[i];
}
for(int c = k, b = k+1; c< temp_arr.length; c++,b++){
temp_arr[c] = words[b];
}
words = temp_arr; // assign the new values to global array
}
}
Also, if theres any suggestions for good coding practice would be appreciated, thanks!
** I can only use Arrays as my data structure for this method.
Modify the condition like this
a.equals(words[0])
because you know the string value a. But dont know what value will come from array. So even null value comes from the array it does allow the null pointer exception.
I run your code and find a few errors, I correct somethings without changing the core idea:
} else { // if the word is in neither first or last position of array
// THIS IS WHERE the exception is thrown, in this for loop.
int k = -1;
for (int i = 0; i < words.length; i++) { // find the position of the word to delete
if (words[i].equals(a)) {
k=i;
break;
}
}
if(k<0)//if not exists
return;
for (int i = 0; i < k /*- 1*/; i++) { // add first part of array before the word
temp_arr[i] = words[i];
}
for (int i = k; i < temp_arr.length; i++) {
temp_arr[i] = words[i+1];
}
words = temp_arr; // assign the new values to global array
}
If the original array could't have null elements I would do like this:
public static String[] remove(String words[] , String a) {
int counter = 0;
for (int i = 0; i < words.length; i++) {
if( a.equals(words[i]) ){
words[i] = null;
counter++;
}
}
if(counter==0){
return words;
}
String[] words2 = new String[words.length - counter];
int i=0;
for (String string : words) {
if(string!=null){
words2[i++]=string;
}
}
return words2;
}
I would do that like this:
public void remove(String a) {
List<String> tmp = new ArrayList<String>();
for (String word : words) {
if ((word != null) && (word.equals(a))) {
continue;
}
tmp.add(word);
}
words = tmp.toArray(new String[]);
}
I have a question for you:
Why oh why are you using an array? You should always use a collection (eg a List) unless you absolutely have to use an array (which is rare indeed).
If it were a List, you wouldn't even need this method, because List has the remove() method that does all this for you!

Categories