Deleting element from array and moving remaining element using nested loops? - java

This is my code so far:
public class CustomerListerArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
//creating the array
String[] customerName = new String [7];
customerName[0] = "Beth";
customerName[1] = "Jerry";
customerName[2] = "Rick";
customerName[3] = "Summer";
customerName[4] = "Morty";
// first loop/test
for(String x : customerName) {
System.out.println(x);
}
System.out.println(" ");
//second loop/test
customerName[5] = customerName[3];
customerName[6] = customerName[4];
customerName[3] = "Rick";
customerName[4] = "Jessica";
for(String x : customerName) {
System.out.println(x);
}
System.out.println(" ");
//third loop/test
int i = 0;
int p = 0;
for(String x : customerName) {
for(i = 0; i < customerName.length - 1; ++i) {
if((customerName[i] == "Rick")){
for (p = i; p < customerName.length; ++p){
customerName[i] = customerName[i +1];
}
}
}
System.out.println(x);
}
System.out.println(" ");
}
}
In the third loop test, I am trying to take the "Rick"s from the array, delete them and move the remaining elements up. The output should be this:
"Beth
Jerry
Jessica
Summer
Morty"
Right now, the program outputs this:
"Beth
Jerry
Rick
Summer
Morty
null
null
Beth
Jerry
Rick
Rick
Jessica
Summer
Morty
Beth
Jerry
Jessica
Jessica
Jessica
Summer
Morty"
I don't understand why three "Jessica"s are printing at the end. Any help would be appreciated!

FIRST OF ALL -- doing customerName[i] == "Rick" is a classic newbie mistake; whatever it looks like, it does NOT tell you whether that value is "Rick" (unless you've done some special things we won't go into). It will tell you whether the object at customerName[i] is the same object as your literal "Rick", which isn't likely in a production environment. You need the equals() method of the String class; look it up and remember this. For example, if (customerName[i].equals("Rick")).
Read this for more information: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
As for Jessica, if you move that value from [i] to [j], then she is still in [i]; if you want to "remove" jessica, you should set the value at [i] to something else.

Try this.
private static void output() {
String[] str_array = {"Beth", "Jerry", "Rick", "Summer", "Morty"};
List<String> list = new ArrayList<>(Arrays.asList(str_array));
list.remove("Rick");
str_array = list.toArray(new String[0]);
for (String x : str_array) {
System.out.println(x);
}
}
Please remember to import the appropriate API's above your class declaration.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

Related

printing "action not found". While "availaiblebooksbooks" should print

i want to print my availaiblebooksbooks array. I am doing this using for loop.
initial output
welcome..., what do you want to do in library
choose any one performable action
1.addbook
2.purchasbook
3.returnbook
4.showavilaiblebook
I am putting user input 4.showavilaiblebook
after putting input is m getting this.
action not found
action not found
action not found
where it should print:-
Think and grow rich
how to influence pepoles
Richest man in bablyon
Jeet ya har
great words win heart
Time management
positive thinking
power thinking
subconcious mind
My java code
public class OnlineLibrary {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("welcome..., what do you want to do in library");
String [] actionlist = {"choose any one performable action", "1.addbook","2.purchasbook","3.returnbook","4.showavilaiblebook"};
for(int i = 0; i<actionlist.length; i++) {System.out.println(actionlist[i]); }
//list of library books
String [] availaiblebooksbooks = {"Think and grow rich", "how to influence pepoles", "Richest man in bablyon", "Jeet ya har", "great words win heart","Time management", "positive thinking", "power thinking","subconcious mind"};
String input = scan.next();
for(int i = 1; i<actionlist.length; i++) {
String actionno = actionlist[i];
if (input.equals(actionno)) { }
else if (input.equals(actionno)) { }
else if (input.equals(actionno)) { }
else if (input.equals(actionno)) { for(int p = 0; p<availaiblebooksbooks.length; p++) { System.out.println(availaiblebooksbooks[p]); }}
else {System.out.println("action not found");}
}
}
}
The expected answer is obtained by keeping its direct value of the arrayitem. But I want to know what is the problem with this.
Try something like this, or use a switch statement based on the "input":
String input = scan.next();
if (input.equals("4")) {
for(int p = 0;p < availaiblebooksbooks.length; p++) {
System.out.println(availaiblebooksbooks[p]);
}
}... else if (otherinputs) {
.
.
}

Java 8 Search ArrayList with Streams algorithm failing

We are using a Stream to search an ArrayList of strings the Dictionary file is sorted & contains 307107 words all in lower case
We are using the findFirst to look for a match from the text in a TextArea
As long as the word is misspelled beyond the 3 character the search has favoriable results
If the misspelled word is like this "Charriage" the results are nothing close to a match
The obvious goal is to get as close to correct without the need to look at an enormous number of words
Here is the text we are tesing
Tak acheive it hommaker and aparent as Chariage NOT ME Charriag add missing vowel to Cjarroage
We have made some major changes to the stream search filters with reasonable improvements
We will edit the posted code to include ONLY the part of the code where the search is failing
And below that the code changes made to the stream filters
Before the code change if the searchString had a misspelled char at position 1 no results were found in the dictionary the new search filters fixed that
We also added more search information by increasing the number of char for endsWith
So what is still failing! If the searchString(misspelled word) is missing a char at the end of the word and if the word has an incorrect char from position 1 to 4 the search fails
We are working on adding & removing char but we are not sure this is a workable solution
Comments or code will be greatly appreciated if you would like the complete project we will post on GitHub Just ask in the comments
The question is still how to fix this search filter when multiple char are missing from the misspelled word?
After multiple hours of searching for a FREE txt Dictionary this is one of the best
A side bar fact it has 115726 words that are > 5 in length and have a vowel at the end of the word. That means it has 252234 words with no vowel at the end
Does that mean we have a 32% chance of fixing the issue by adding a vowel to the end of the searchString? NOT a question just an odd fact!
HERE is a link to the dictionary download and place the words_alpha.txt file on C drive at C:/A_WORDS/words_alpha.txt");
words_alpha.txt
Code Before Changes
}if(found != true){
lvListView.setStyle("-fx-font-size:18.0;-fx-background-color: white;-fx-font-weight:bold;");
for(int indexSC = 0; indexSC < simpleArray.length;indexSC++){
String NewSS = txtMonitor.getText().toLowerCase();
if(NewSS.contains(" ")||(NewSS.matches("[%&/0-9]"))){
String NOT = txtMonitor.getText().toLowerCase();
txtTest.setText(NOT+" Not in Dictionary");
txaML.appendText(NOT+" Not in Dictionary");
onCheckSpelling();
return;
}
int a = NewSS.length();
int Z;
if(a == 0){// manage CR test with two CR's
Z = 0;
}else if(a == 3){
Z = 3;
}else if(a > 3 && a < 5){
Z = 4;
}else if(a >= 5 && a < 8){
Z = 4;
}else{
Z = 5;
}
System.out.println("!!!! NewSS "+NewSS+" a "+a+" ZZ "+Z);
if(Z == 0){// Manage CR in TextArea
noClose = true;
strSF = "AA";
String NOT = txtMonitor.getText().toLowerCase();
//txtTo.setText("Word NOT in Dictionary");// DO NO SEARCH
//txtTest.setText("Word NOT in Dictionaary");
txtTest.setText("Just a Space");
onCheckSpelling();
}else{
txtTest.setText("");
txaML.clear();
txtTest.setText("Word NOT in Dictionaary");
txaML.appendText("Word NOT in Dictionaary");
String strS = searchString.substring(0,Z).toLowerCase();
strSF = strS;
}
// array & list use in stream to add results to ComboBox
List<String> cs = Arrays.asList(simpleArray);
ArrayList<String> list = new ArrayList<>();
cs.stream().filter(s -> s.startsWith(strSF))
//.forEach(System.out::println);
.forEach(list :: add);
for(int X = 0; X < list.size();X++){
String A = (String) list.get(X);
Improved New Code
}if(found != true){
for(int indexSC = 0; indexSC < simpleArray.length;indexSC++){
String NewSS = txtMonitor.getText().toLowerCase();
if(NewSS.contains(" ")||(NewSS.matches("[%&/0-9]"))){
String NOT = txtMonitor.getText().toLowerCase();
txtTest.setText(NOT+" Not in Dictionary");
onCheckSpelling();
return;
}
int a = NewSS.length();
int Z;
if(a == 0){// manage CR test with two CR's
Z = 0;
}else if(a == 3){
Z = 3;
}else if(a > 3 && a < 5){
Z = 4;
}else if(a >= 5 && a < 8){
Z = 4;
}else{
Z = 5;
}
if(Z == 0){// Manage CR
noClose = true;
strSF = "AA";
String NOT = txtMonitor.getText().toLowerCase();
txtTest.setText("Just a Space");
onCheckSpelling();
}else{
txtTest.setText("");
txtTest.setText("Word NOT in Dictionaary");
String strS = searchString.substring(0,Z).toLowerCase();
strSF = strS;
}
ArrayList list = new ArrayList<>();
List<String> cs = Arrays.asList(simpleArray);
// array list & list used in stream foreach filter results added to ComboBox
// Code below provides variables for refined search
int W = txtMonitor.getText().length();
String nF = txtMonitor.getText().substring(0, 1).toLowerCase();
String nE = txtMonitor.getText().substring(W - 2, W);
if(W > 7){
nM = txtMonitor.getText().substring(W-5, W);
System.out.println("%%%%%%%% nE "+nE+" nF "+nF+" nM = "+nM);
}else{
nM = txtMonitor.getText().substring(W-1, W);
System.out.println("%%%%%%%% nE "+nE+" nF "+nF+" nM = "+nM);
}
cs.stream().filter(s -> s.startsWith(strSF)
|| s.startsWith(nF, 0)
&& s.length()<= W+2
&& s.endsWith(nE)
&& s.startsWith(nF)
&& s.contains(nM))
.forEach(list :: add);
for(int X = 0; X < list.size();X++){
String A = (String) list.get(X);
sort(list);
cboSelect.setStyle("-fx-font-weight:bold;-fx-font-size:18.0;");
cboSelect.getItems().add(A);
}// Add search results to cboSelect
break;
Here is a screen shot of the FXML file the controls are named the same as the names used in our code with the exception of the ComboBox
I am adding a JavaFX answer. This app uses Levenshtein Distance. You have to click on Check Spelling to start. You can select a word from the list to replace the current word being checked. I notice Levenshtein Distance returns lots of words so you might want to find other ways to reduce the list down even more.
Main
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class App extends Application
{
public static void main(String[] args)
{
launch(args);
}
TextArea taWords = new TextArea("Tak Carrage thiss on hoemaker answe");
TextField tfCurrentWordBeingChecked = new TextField();
//TextField tfMisspelledWord = new TextField();
ListView<String> lvReplacementWords = new ListView();
TextField tfReplacementWord = new TextField();
Button btnCheckSpelling = new Button("Check Spelling");
Button btnReplaceWord = new Button("Replace Word");
List<String> wordList = new ArrayList();
List<String> returnList = new ArrayList();
HandleLevenshteinDistance handleLevenshteinDistance = new HandleLevenshteinDistance();
ObservableList<String> listViewData = FXCollections.observableArrayList();
#Override
public void start(Stage primaryStage)
{
setupListView();
handleBtnCheckSpelling();
handleBtnReplaceWord();
VBox root = new VBox(taWords, tfCurrentWordBeingChecked, lvReplacementWords, tfReplacementWord, btnCheckSpelling, btnReplaceWord);
root.setSpacing(5);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public void handleBtnCheckSpelling()
{
btnCheckSpelling.setOnAction(actionEvent -> {
if (btnCheckSpelling.getText().equals("Check Spelling")) {
wordList = new ArrayList(Arrays.asList(taWords.getText().split(" ")));
returnList = new ArrayList(Arrays.asList(taWords.getText().split(" ")));
loadWord();
btnCheckSpelling.setText("Check Next Word");
}
else if (btnCheckSpelling.getText().equals("Check Next Word")) {
loadWord();
}
});
}
public void handleBtnReplaceWord()
{
btnReplaceWord.setOnAction(actionEvent -> {
int indexOfWordToReplace = returnList.indexOf(tfCurrentWordBeingChecked.getText());
returnList.set(indexOfWordToReplace, tfReplacementWord.getText());
taWords.setText(String.join(" ", returnList));
btnCheckSpelling.fire();
});
}
public void setupListView()
{
lvReplacementWords.setItems(listViewData);
lvReplacementWords.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
tfReplacementWord.setText(newSelection);
});
}
private void loadWord()
{
if (wordList.size() > 0) {
tfCurrentWordBeingChecked.setText(wordList.get(0));
wordList.remove(0);
showPotentialCorrectSpellings();
}
}
private void showPotentialCorrectSpellings()
{
List<String> potentialCorrentSpellings = handleLevenshteinDistance.getPotentialCorretSpellings(tfCurrentWordBeingChecked.getText().trim());
listViewData.setAll(potentialCorrentSpellings);
}
}
CustomWord Class
/**
*
* #author blj0011
*/
public class CustomWord
{
private int distance;
private String word;
public CustomWord(int distance, String word)
{
this.distance = distance;
this.word = word;
}
public String getWord()
{
return word;
}
public void setWord(String word)
{
this.word = word;
}
public int getDistance()
{
return distance;
}
public void setDistance(int distance)
{
this.distance = distance;
}
#Override
public String toString()
{
return "CustomWord{" + "distance=" + distance + ", word=" + word + '}';
}
}
HandleLevenshteinDistance Class
/**
*
* #author blj0011
*/
public class HandleLevenshteinDistance
{
private List<String> dictionary = new ArrayList<>();
public HandleLevenshteinDistance()
{
try {
//Load DictionaryFrom file
//See if the dictionary file exists. If it don't download it from Github.
File file = new File("alpha.txt");
if (!file.exists()) {
FileUtils.copyURLToFile(
new URL("https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt"),
new File("alpha.txt"),
5000,
5000);
}
//Load file content to a List of Strings
dictionary = FileUtils.readLines(file, Charset.forName("UTF8"));
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public List<String> getPotentialCorretSpellings(String misspelledWord)
{
LevenshteinDistance levenshteinDistance = new LevenshteinDistance();
List<CustomWord> customWords = new ArrayList();
dictionary.stream().forEach((wordInDictionary) -> {
int distance = levenshteinDistance.apply(misspelledWord, wordInDictionary);
if (distance <= 2) {
customWords.add(new CustomWord(distance, wordInDictionary));
}
});
Collections.sort(customWords, (CustomWord o1, CustomWord o2) -> o1.getDistance() - o2.getDistance());
List<String> returnList = new ArrayList();
customWords.forEach((item) -> {
System.out.println(item.getDistance() + " - " + item.getWord());
returnList.add(item.getWord());
});
return returnList;
}
}
You just needed to go a little further out into the Dictionary
We are sure you were getting a lot of suggested words from the Dictionary?
We tested your code and sometimes it found 3000 or more possible matches WOW
So here is the BIG improvement. It still needs a lot of testing we used this line for our tests with 100% favorable results.
Tske Charriage to hommaker and hommake as hommaer
Our fear is if the speller really butchers the word this improvement might solve that degree of misspelling
We are sure you know that if the first letter is wrong this will not work
Like zenophobe for xenophobe
Here is the BIG improvement tada
cs.stream().filter(s -> s.startsWith(strSF)
|| s.startsWith(nF, 0)
&& s.length() > 1 && s.length() <= W+3 // <== HERE
&& s.endsWith(nE)
&& s.startsWith(nF)
&& s.contains(nM))
.forEach(list :: add);
You can send the check to my address 55 48 196 195
This question is a possible duplicate: Search suggestion in strings
I think you should be using something similar to Levenshtein Distance or Jaro Winkler Distance. If you can use Apache's Commons. I would suggest using Apache Commons Lang. It has an implementation of Levenshtein Distance. The example demos this implementation. If you set the distance to (distance <= 2), you will potentially get more results.
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
/**
*
* #author blj0011
*/
public class Main
{
public static void main(String[] args)
{
try {
System.out.println("Hello World!");
File file = new File("alpha.txt");
if (!file.exists()) {
FileUtils.copyURLToFile(
new URL("https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt"),
new File("alpha.txt"),
5000,
5000);
}
List<String> lines = FileUtils.readLines(file, Charset.forName("UTF8"));
//lines.forEach(System.out::println);
lines.stream().forEach(line -> {
int distance = StringUtils.getLevenshteinDistance(line, "zorilta");
//System.out.println(line + ": " + distance);
if (distance <= 1) {
System.out.println("Did you mean: " + line);
}
});
}
catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output distance <= 1
Building JavaTestingGround 1.0
------------------------------------------------------------------------
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
Hello World!
Did you mean: zorilla
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.329 s
Finished at: 2019-11-01T11:02:48-05:00
Final Memory: 7M/30M
Distance <= 2
Hello World!
Did you mean: corita
Did you mean: gorilla
Did you mean: zoril
Did you mean: zorilla
Did you mean: zorillas
Did you mean: zorille
Did you mean: zorillo
Did you mean: zorils
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.501 s
Finished at: 2019-11-01T14:03:33-05:00
Final Memory: 7M/34M
See the possible duplicate for more details about Levenshtein Distance.

how to sort data from a custom class

Ok so i made a car race script in java . It has two classes. The Car class and TheRace class.
The Car class just has stuff about the car like the distance the car has traveled, and in TheRace, I have two arrays for the drivers (driverArray) and sponsors (sponsors). I made a Car class array so each driver have different speeds and distance traveled.
Anyway, as you can see I made a boolean called winner, and a while loop that will keep going until the winner is true. The drivers distance becomes more and more in a while loop until myDistance is equal to or greater than 100.
In the code you can see that, if(carList[i].myDistance() >= 100){ winner = true;}, So then i display the Winner.
I have been trying to make it so it shows all the people who eventually cross the finish line 100 , and display them in the corrector order they finished. Like sorting an array or something. How i can show what place everyone got. How do i do this?
TheRace class,
package NASCAR;
import java.util.Arrays;
import java.util.Random;
public class TheRace {
// variables
public static String[] driverArray = {"steave smith", "Cheese farlin","Bob Joe","Josh Svioda", "Andrew Kralovec", "Ricky Bobby","Ashey GirslCanDriveTo","Kelsey IAgree","Joe ThisIsAManSport","Jess TheHellItIs","Jesus Defualt","Jason seglad","Andrew Smith","Andrew Johnson","Andrew Kosevsky","Andrew Anderson","Andrew Andrew", "Kate Andrew","Blondey Gold","Golden Blonde","Im Twenty" };
public static String[] sponsors = {"CocaCola","Pepsi","CoorsLight","GOD"} ;
public int[] currentDistance = new int[20];
public static void main(String[] args) {
Car[] carList = new Car[20] ;
Random rand = new Random();
for(int i =0 ; i < carList.length;i++){
carList[i] = new Car(driverArray[rand.nextInt(20)], sponsors[rand.nextInt(4)]) ;
} //end for
int lapCounter = 0 ;
boolean winner = false;
while(!winner){
for(int i = 0; i < carList.length; i++){
carList[i].changeDistance();
if(lapCounter % 6 == 0){
carList[i].speedChange();
} // end if change speed
System.out.println(carList[i].trackProgress());
if(carList[i].myDistance() >= 100){
winner = true;
System.out.println("_____ THE WINNER OF THE RACE IS: "+carList[i].myName()+" For team: "+carList[i].myTeam());
break ;
}
}// end for
lapCounter++;
System.out.println("---------------------------------");
} // end while
}// end main
}
Car class,
package NASCAR;
import java.util.Random;
public class Car {
//variables
private float totalOdMiles ;
private float speedPerHour ;
private String driverName ;
private String sponsorName ;
private Random rand = new Random();
public Car(String driverName, String sponsorName){
this.driverName = driverName ;
this.sponsorName = sponsorName ;
this.totalOdMiles = 0;
this.speedPerHour = rand.nextInt( 60);
}
public String myName(){
this.driverName = driverName;
return driverName ;
}
public String myTeam(){
this.sponsorName = sponsorName;
return sponsorName ;
}
public float myDistance(){ //reprot distance
return totalOdMiles;
}
public void speedChange(){ //ChangeSpeed()
this.speedPerHour = rand.nextInt(60);
}
public void changeDistance(){ //UpdateProgress()
float milesPerSecond = this.speedPerHour / 3600;
this.totalOdMiles+=milesPerSecond;
}
public String trackProgress(){ //ToString()
return this.driverName +" driving the "+ this.sponsorName+" car is going "+ this.totalOdMiles +"MPS "+this.totalOdMiles;
}
}
Ideally you should avoid the problem of having to sort two arrays simultaneously by adding the currentDistance field to the Car class. Then you can sort the carList using currentDistance.
For example, using java 8 you can get the first 3 places with:
Arrays.stream(carList)
.sorted((c1, c2) -> c2.currentDistance - c1.currentDistance)
.map(c -> c.getName())
.limit(3);
Hava a look at this custom Comparator,
put this code after your while loop,
Collections.sort(Arrays.asList(carList), new Comparator<Car>() {
#Override
public int compare(Car o1, Car o2) {
return Float.compare(o2.myDistance(), o1.myDistance());
}
});
to print the sorted names along with their rank,
for (Car s : carList){
System.out.println(s.myDistance() + " " + s.myName());
}
Output:
THE WINNER OF THE RACE IS: Andrew Johnson For team: CocaCola
100.004135 Andrew Johnson
99.623375 Jesus Defualt
99.23477 Andrew Smith
99.20563 Andrew Andrew
98.94183 Jesus Defualt
98.87631 Blondey Gold
98.86331 Jesus Defualt
98.64405 steave smith
98.54269 Jason seglad
98.24685 Bob Joe
98.23995 Andrew Kosevsky
98.06155 Ricky Bobby
97.81364 Jess TheHellItIs
97.77215 Blondey Gold
97.72567 Ashey GirslCanDriveTo
97.57001 Ashey GirslCanDriveTo
97.54619 Cheese farlin
97.29426 Andrew Kralovec
96.68102 Andrew Kosevsky
96.018654 Ashey GirslCanDriveTo
to list the first 5 places, use this instead,
for (int i=0; i<5; i++){
System.out.println(carList[i].myDistance() + " " + carList[i].myName() + ", -- Rank: " + (i+1));
}
This could be done more easily if you are using Java 8,
Arrays.stream(carList)
.sorted((a, b) -> Float.compare(b.myDistance(), a.myDistance()))
.map(c -> c.myDistance() + " " + c.myName())
.forEachOrdered(System.out::println);
This will get you the ranks of all the drivers in descending order along with their respective speed.
I propose an easy solution based on what I think you're asking.
Simply create a new array, carPlace[] (as an example) and add carList[i] to that array as soon as they finish.
That way 1st place will be carPlace[0], 2nd place carPlace[1] etc.
Once all cars are placed, then you can break out of the while loop as before.
You may not want to have your loop break as soon as a winner is found though - as this method requires all cars being added to the array.
If this is not what you are asking please specify ...
Happy coding!
your car class could imlpement the Comparable interface :
public class Car implements Comparable<Car>
#Override
public int compareTo(Car o) {
return this.totalOdMiles < o.totalOdMiles ? 0 : 1;
}
and the you can sort your array at the end of your while:
Arrays.sort(carList);
this should somehow work i guess :)

Issue with NullPointerException

I am continuing to get this error. Now I have gotten it for my SortSearchUtil. I've tried to do some debugging but can fix the issue. The error reads:
----jGRASP exec: java PostOffice
Exception in thread "main" java.lang.NullPointerException
at SortSearchUtil.selectionSort(SortSearchUtil.java:106)
at PostOffice.sortLetters(PostOffice.java:73)
at PostOffice.main(PostOffice.java:15)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
line 106 of selection Sort is:
if (array[indexSmallest].compareTo(array[curPos]) > 0)
I don't know what could be wrong with my method. It's a standard method that was given to me by my instructor. I've tried to debug my program but I'm pretty stuck. Here is the method that the error is originating from, selectionSort:
public static void selectionSort(Comparable[] array)
{
int curPos, indexSmallest, start;
Comparable temp;
for (start = 0; start < array.length - 1; start++)
{
indexSmallest = start;
for (curPos = start + 1; curPos < array.length; curPos++)
if (array[indexSmallest].compareTo(array[curPos]) > 0)
{
indexSmallest = curPos;
}
// end for
temp = array[start];
array[start] = array[indexSmallest];
array[indexSmallest] = temp;
} // end for
}
The sort method is at the bottom which calls SortSearchUtil.selectionSort of this Post Office Method:
import java.util.*;
import java.io.*;
public class PostOffice
{
private final int max = 1000;
private Letter [] ltrAra = new Letter[max];
private int count;
public static void main(String [] args)
{
PostOffice postOffice = new PostOffice();
postOffice.readLetters("letters.in");
postOffice.sortLetters();
postOffice.printLetters();
}
public PostOffice()
{
Letter [] Letters = ltrAra;
this.count = 0;
}
public void readLetters(String filename)
{
int count = 0;
int iWork = 0;
Scanner fin = new Scanner(filename);
String toName, toStreet, toCity, toState, toZip;
String fromName, fromStreet, fromCity, fromState, fromZip, temp;
double weight;
String sWork;
fin = FileUtil.openInputFile(filename);
if (fin != null)
{
while (fin.hasNext())
{
toName = fin.nextLine();
toStreet = fin.nextLine();
sWork = fin.nextLine();
iWork = sWork.indexOf(",");
toCity = sWork.substring(0, iWork);
iWork = iWork + 2;
toState = sWork.substring(iWork, iWork + 2);
iWork = iWork + 3;
toZip = sWork.substring(iWork);
fromName = fin.nextLine();
fromStreet = fin.nextLine();
sWork = fin.nextLine();
iWork = sWork.indexOf(",");
fromCity = sWork.substring(0, iWork);
iWork = iWork + 2;
fromState = sWork.substring(iWork, iWork + 2);
iWork = iWork + 3;
fromZip = sWork.substring(iWork);
sWork = fin.nextLine();
weight = Double.parseDouble(sWork);
ltrAra[count] = new Letter(toName, toStreet, toCity, toState, toZip, fromName, fromStreet, fromCity, fromState, fromZip, weight);
count++;
}
fin.close();
}
}
public void sortLetters()
{
SortSearchUtil.selectionSort(ltrAra);
}
public void printLetters()
{
for (Letter ltr : ltrAra)
{
System.out.println(ltr);
System.out.println();
}
}
}
My file looks like this "letters.in":
Stu Steiner
123 Slacker Lane
Slackerville, IL 09035
Tom Capaul
999 Computer Nerd Court
Dweebsville, NC 28804-1359
0.50
Tom Capaul
999 Computer Nerd Court
Dweebsville, NC 28804-1359
Chris Peters
123 Some St.
Anytown, CA 92111-0389
1.55
Obviously you get a NPE because:
You initialize ltrAra as array of 1000 items, but you read in less than 1000 items within method readLetters(). So at the end of this array some null references remain un-initialized (remember array-creation does itself not set the single items to any objects). Therefore following sorting-method gets some null-references => NPE.
Suggested solution:
You should use an ArrayList instead of an array because that will automatically prevent you from accessing too much items due to internal range check.
In addition to the above answer that Meno has well stated, you need to understand when you get a Null pointer Exception.
your error-line : if (array[indexSmallest].compareTo(array[curPos]) > 0)
If we get NPE in this line, it is obvious that array[indexSmallest] is null
And when you invoke an action on null, you get NPE. Hope this helps you to debug, down the line.
Also, One of the main reasons when we choose ArrayList over Arrays is when we do not know the length of the array.
One more suggestion, you can create an ArrayList and then convert to Arrays if you want to stick with Arrays
To convert ArrayList of any class into array, Convert T to the respective class. For eg: if you want String array, convert T to 'String'
List<T> list = new ArrayList<T>();
T [] students = list.toArray(new T[list.size()]);

parsing string in java

I have some problem in parsing one String as
String str="0|$5th std~~Pramod Deore|^97.0|^970.0|^1.02|^871.0600000000001|^S|^98.94|^5996.9400000000005|^12|^166|^|$7th std~~Vishal Chaudhary|^20.0|^220.0|^111.0|^-2000.0|^|^2220.0|^0.0|^110|^22222~Yogesh Gadage|^100.0|^3000.0|^10.0|^2000.0|^|^1000.0|^0.0|^16|^03~12|^111.0|^134532.0|^11.0|^133311.0|^B|^1221.0|^0.0|^45|^12~Chetan Patil|^200000.22|^2066002.2726|^-0.1500000549999395|^2096002.3166|^H|^-30000.044|^0.0|^20|^FEF-D~Sandeep Deshmukh|^-1.0|^-10.0|^0.0|^0.0|^|^0.0|^123.0|^29|^JPPWR~Yogita Gade|^25.0|^250.0|^100.25|^-2256.25|^X|^2506.25|^0.0|^30|^302|^|$";
Here in String I have 2 main records seperated by "~~"supppose 1. 5th std and 2. 7th std. Then in second record(i.e 7th std) there are 6 records seperated by "~". Now I want to parse this response and store values of each individual records.
let take one record from 2nd one.
Sandeep Deshmukh|^-1.0|^-10.0|^0.0|^0.0|^|^0.0|^123.0|^29|^JPPWR
In short What I want is- I want to know say -"Sandeep Deshmukh" is from 7th Std. and 1.0 is his grade, 10.0 is his 2nd grade ......and JPPWR is his city short name
Then I must know it is from 2nd main record (i.e 7 th std) and also store all values of this record which is separated by "|^". How to do this. I had tried following code.
import java.util.ArrayList;
class ParseTest
{
String str="0|$5th std~~Pramod Deore|^97.0|^970.0|^1.02|^871.0600000000001|^S|^98.94|^5996.9400000000005|^12|^166|^|$7th std~~Vishal Chaudhary|^20.0|^220.0|^111.0|^-2000.0|^|^2220.0|^0.0|^110|^22222~Yogesh Gadage|^100.0|^3000.0|^10.0|^2000.0|^|^1000.0|^0.0|^16|^03~12|^111.0|^134532.0|^11.0|^133311.0|^B|^1221.0|^0.0|^45|^12~Chetan Patil|^200000.22|^2066002.2726|^-0.1500000549999395|^2096002.3166|^H|^-30000.044|^0.0|^20|^FEF-D~Sandeep Deshmukh|^-1.0|^-10.0|^0.0|^0.0|^|^0.0|^123.0|^29|^JPPWR~Yogita Gade|^25.0|^250.0|^100.25|^-2256.25|^X|^2506.25|^0.0|^30|^302|^|$";
public static void main(String[] args)
{
ParseTest pt = new ParseTest();
pt.parse();
}
public void parse()
{
System.out.println (str);
ArrayList<String> stockrows = parseResponse(str,"|$");
for (int i=1;i<stockrows.size();i++)
{
System.out.println("iiii"+i+":::"+stockrows.get(i));
//parse with ~~
ArrayList<String> stockrows1 = parseResponse(str,"~~");
for (int j=0;j<stockrows1.size();j++)
{
System.out.println("jjjj"+j+"::::"+stockrows1.get(j));
//parse with ~
ArrayList<String> stockrows2 = parseResponse(str,"~");
for (int k=0;k<stockrows2.size();k++)
{
System.out.println("kkkkkk"+k+"::::"+stockrows2.get(k));
}
}
}
}
public static ArrayList<String> parseResponse(String input, String delimeter) {
ArrayList<String> parsed_strings = new ArrayList<String>();
while (true) {
int i = input.indexOf(delimeter);
if (i >= 0) {
String s = input.substring(0, i);
parsed_strings.add(s.trim());
input = input.substring(i + delimeter.length(), input.length());
} else {
break;
}
}
if (parsed_strings.size() < 1) {
parsed_strings.add(input);
}
return parsed_strings;
}
}
Any help will be apprecited. Thanks in advance
String str="0|$5th std~~Pramod Deore|^97.0|^970.0|^1.02|^871.0600000000001|^S|^98.94|^5996.9400000000005|^12|^166|^|$7th std~~Vishal Chaudhary|^20.0|^220.0|^111.0|^-2000.0|^|^2220.0|^0.0|^110|^22222~Yogesh Gadage|^100.0|^3000.0|^10.0|^2000.0|^|^1000.0|^0.0|^16|^03~12|^111.0|^134532.0|^11.0|^133311.0|^B|^1221.0|^0.0|^45|^12~Chetan Patil|^200000.22|^2066002.2726|^-0.1500000549999395|^2096002.3166|^H|^-30000.044|^0.0|^20|^FEF-D~Sandeep Deshmukh|^-1.0|^-10.0|^0.0|^0.0|^|^0.0|^123.0|^29|^JPPWR~Yogita Gade|^25.0|^250.0|^100.25|^-2256.25|^X|^2506.25|^0.0|^30|^302|^|$";
String a[] = str.split("~~|~");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}

Categories

Resources