Way to transfer the data in one array to two arrays? - java

https://i.stack.imgur.com/Daxvo.png
So this is my assignment. I was able to split the input using the split() method, which created an array, splitArray. But the problem is, I don't know how to transfer the contents of the splitArray to the phoneNumberVec and nameVec array.
splitArray[] data:
Joe
123-5432
Linda
983-4123
Frank
867-5309
Is there a way to put the names into one array and the numbers in another?
I hope I was clear on my question, I'm new to this whole thing! Thank you!

This is pretty simple. I think it's more comfortable to use Scanner instead of string split:
public static void main(String[] args) {
String contactList = "3 Joe 123-5432 Linda 983-41-23 Frank 867-5309";
String contactName = "Frank";
System.out.println(getPhoneNumber(contactList, contactName));
}
public static String getPhoneNumber(String contactList, String contactName) {
try (Scanner scan = new Scanner(contactList)) {
int N = scan.nextInt();
String[] nameVec = new String[N];
String[] phoneNumberVec = new String[N];
for (int i = 0; i < N; i++) {
nameVec[i] = scan.next();
phoneNumberVec[i] = scan.next();
}
return getPhoneNumber(nameVec, phoneNumberVec, contactName, N);
}
}
public static String getPhoneNumber(String[] nameVec, String[] phoneNumberVec, String contactName, int arraySize) {
for (int i = 0; i < arraySize; i++)
if (nameVec[i].equals(contactName))
return phoneNumberVec[i];
return "<not found>";
}

Related

String Sorter Returing Exit Code 0 instead of the Strings

I am trying to make a string sorter that takes user input and puts it into alphabetical order. My code looks like this:
public class StringSorter {
public static void main(String[] argv) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
System.out.println("How many strings do you want to sort?");
int numStrings = Integer.parseInt(stdin.readLine());
System.out.println("Input Strings Here:");
String[] stringsToSort = new String[numStrings];
for (int i = 0; i < numStrings; i++) {
String s = stdin.readLine();
stringsToSort[i] = s;
}
int comparison = (stringsToSort[0].compareToIgnoreCase(stringsToSort[1]));
if (stringsToSort[0].compareToIgnoreCase(stringsToSort[1]) < 0) {
System.out.println("Alphabetical Order: " + Integer.toString(comparison));
}
}
}
How do I make it print the strings instead of "Exit Code 0"?
I forgot to add that I cannot use java.util.Arrays or java.util.Vector for this assignment
Right now you are printing the result of a comparison and not the string and you're only sorting the two first strings.
You call Array.sort() first and then you print the array. Replace your comparison and print with
Arrays.sort(stringsToSort);
for (String string : stringsToSort) {
System.out.println(string);
}
The code is going to print 1, if the first String is alphabetically smaller than the second String otherwise it will do nothing and return 0 exit code.
If you intend to do is print the array, you should iterate using a for loop on the elements of the array and print the element.
For sorting the array, you could use any of the sorting algos. Selection sort is the simplest to understand. Following is a link for sorting a String array.
http://web.cs.iastate.edu/~smkautz/cs227f12/examples/week11/SelectionSortExamples.java
You can use a custom sorting like this for your one,
public class A {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in), 1);
System.out.println("How many strings do you want to sort?");
int numStrings = Integer.parseInt(stdin.readLine());
System.out.println("Input Strings Here:");
String[] stringsToSort = new String[numStrings];
for (int i = 0; i < numStrings; i++) {
String s = stdin.readLine();
stringsToSort[i] = s;
}
Arrays.sort(stringsToSort, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
for (int i = 0; i < stringsToSort.length; i++) {
System.out.println(stringsToSort[i]);
}
}
}

Trying to find min value of two array lists inside a loop

I feel like this shouldn't be a hard fix, but I've been stumped for awhile. Here's the chunk that I'm having issues with.
public static double bestConnectionPrice(ArrayList<String> flightList, String city1, String city2) {
ArrayList<String> firstPlane = new ArrayList<String>();
ArrayList<String> secondPlane = new ArrayList<String>();
double best = 10000;
firstPlane = flightsFrom(flightList,city1);
secondPlane = flightsTo(flightList,city2);
for(int i=0; i<firstPlane.size(); i++) {
for(int j=0;j<secondPlane.size();j++){
if(canConnect(firstPlane.get(i), secondPlane.get(j))==true){
double price = Double.parseDouble(getPrice(firstPlane.get(i))) + Double.parseDouble(getPrice(secondPlane.get(j)));
if (price<best) {
best=price;
}
}
else
best = -1;
}
}
return best;
}
It's supposed to find the lowest combined cost of flightsFrom and flightTo. However, it always takes whatever the last price happens to be. Is there any way to set the best variable to whatever it is the first time through the loop and then have it stay as that unless something is smaller than it. Right now it's resetting every time the loops is restarted to I'm not sure how I can compare if something is smaller than it. (I hope that makes sense).
Also here is my main method where I'm trying to call it, as well as the other methods that I'm calling just in case.
public static void main(String[] args) throws FileNotFoundException {
Scanner stdin = new Scanner(System.in);
ArrayList<String> test = new ArrayList<String>();
test.add("Portland#Orlando#200.00");
test.add("Portland#Orlando#100.00");
test.add("Portland#Orlando#300.00");
test.add("Orlando#Boston#100.00");
test.add("Orlando#Boston#400.00");
test.add("Orlando#Boston#200.00");
double connection = bestConnectionPrice(test,"Portland","Boston");
if (connection<0)
System.out.println("Sorry, there are no flights between those cities");
else
System.out.println("The chepeast price is $"+ connection);
}
public static ArrayList<String> flightsFrom(ArrayList<String> flightList, String city) {
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<flightList.size(); i++){
String city1 = getOriginationCity(flightList.get(i));
if (city1.equals(city)) {
list.add(flightList.get(i));
}
}
return list;
}
public static ArrayList<String> flightsTo(ArrayList<String> flightList, String city) {
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<flightList.size(); i++){
String city1 = getDestinationCity(flightList.get(i));
if (city1.equals(city)) {
list.add(flightList.get(i));
}
}
return list;
}
public static String getPrice(String price) { //Takes flight description, which is a string, as a parameter and returns price of flight
String[] sArray = price.split("#", -1);
String newPrice = "";
for (int i = 0; i<1; i++)
newPrice = sArray[2];
return newPrice;
public static boolean canConnect(String flight1, String flight2) {
String Destination = getDestinationCity(flight1);
String Origination = getOriginationCity(flight2);
if (Destination.equals(Origination)) {
return true;
}
else
return false;
public static String getOriginationCity(String city) {
String[] sArray = city.split("#", -1);
String start = "";
for (int i = 0; i<1; i++)
start = sArray[0];
return start;
}
public static String getDestinationCity(String city) {
String[] sArray = city.split("#", -1);
String end = "";
for (int i = 0; i<1; i++)
end = sArray[1];
return end;
}
Thanks in advance for any advice you might have!
Things would be easier if you had a class that represented your string-as-an-object, but nevertheless you are reinventing the wheel:
Make a List of every combination of 1st and 2nd fights
Sort the list based on their combined price using Collections.sort()
The first element in the List is then your result

Input from the console in java

I know this is a basic question but I have been trying hard to find Which method I can use if I have to take 2 {123,456} as the input from console where 2 is the number of inputs to the array and {123,456} are inputs to the array. Should I be using Regex for this since it has { symbols or can it be done by scanner alone??
You can read the array part as String and then strip the curly braces using substring. Convert the String to int and store into an array.
import java.util.Scanner;
public class ReadArray {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int count = read.nextInt();
String arrayLine = read.next();
int array[] = new int[count];
String elements[] = arrayLine.split(",");
elements[0] = elements[0].substring(1);
elements[count-1] = elements[count-1].substring(0, elements[count-1].length()-1);
for (int i=0; i<count; i++) {
array[i] = Integer.parseInt(elements[i]);
}
for (int i : array) {
System.out.println(i);
}
}
}
Input :
2 {123,456}
Output :
123
456
Assuming you have read the input as a string, you can do the following:
String[] inputs = input.split(" ");
int arrayLength = Integer.parseInt(inputs[0]);
String inputStringData = inputs[1].substring(1, inputs[1].length());
String[] arrayElements = inputStringData.split(",");
int[] array = new int[arrayLength];
for(int i=0; i<array.length; i++) {
array[i] = Integer.parseInt(arrayElements[i]);
}

Unable to reverse a String after converting it to String Array

I am trying to convert a String to a String Array using the split method. When I try to individually reverse elements of the array using the reverse method, the reverse method doesn't even show up in Eclipse Code Suggestions. Explicitly using reverse, spurts out an error saying The method reverse() is undefined for the type String.
Please help!
public class Split {
public static void main(String args[]){
String temp;
String names="Apple Banana Cabbage Daffodil";
String[] words = names.split(" ");
for (int i = 0; i < words.length; i++) {
temp = words[i].reverse();
}
}
The compiler message is clear: reverse is not a method of String.
Try:
String reverse = new StringBuilder(words[i]).reverse().toString();
There is no method reverse for type String but you could do it yourself like:
public static void main(String args[]){
String temp;
String names="Apple Banana Cabbage Daffodil";
String[] words = names.split(" ");
String[] reverseWords = new String[words.length];
int counter = words.length - 1;
for (int i = 0; i < words.length; i++) {
reverseWords[counter] = new String(words[i]);
counter--;
}
words = reverseWords;
for(String i : words)
{
System.out.print(" " + i);
}
}
There is no reverse method defined for the String type. You can use Collections#reverse on a List which reverses its elements:
String[] words = names.split(" ");
List<String> wordList = Arrays.asList(words);
Collections.reverse(wordList);
It's because String doesn't have method reverse, you can use StringBuilder instead.
Like:
public static void main(String[] args) {
String temp;
String names = "Apple Banana Cabbage Daffodil";
String[] words = names.split(" ");
for (int i = 0; i < words.length; i++) {
temp = new StringBuilder(words[i]).reverse().toString();
}
}

Separating an address line into House Number, Street name, and Apartment in Java or COBOL

I am currently trying to figure out the best way to take an address line and separate it out into three fields for a file, house number, street name, and apartment number. Thankfully, the city, state, and zip are already in columns so all I have to parse out is just the three things listed above, but even that is proving difficult. My initial hope was to do this in COBOL using SQL, but I dont think I am able to use the PATINDEX example someone else had listed on a separate question thread, I kept getting -440 SQL code. My second thought was to do this in Java using the strings as arrays and checking the arrays for numbers, then letters, then a compare for "Apt" or something to that effect. I have this so far to try to test out what I'm ultimately trying to do, but I am getting out of bounds exception for the array.
class AddressTest{
public static void main (String[] arguments){
String adr1 = "100 village rest court";
String adr2 = "1000 Arbor lane Apt. 21-D";
String[] HouseNbr = new String[9];
String[] Street = new String[20];
String[] Apt = new String[5];
for(int i = 0; i < adr1.length();i++){
String[] forloop = new String[] {adr1};
if (forloop[i].substring(0,1).matches("[0-9]")){
if(forloop[i+1].substring(0,1).matches("[0-9]")){
HouseNbr[i] = forloop[i];
}
else if(forloop[i+1].substring(0,1).matches(" ")){
}
else if(forloop[i].substring(0,1).matches(" ")){
}
else{
Street[i] = forloop[i];
}
}
}
for(int j = 0; j < HouseNbr.length; j++){
System.out.println(HouseNbr[j]);
}
for(int k = 0; k < Street.length; k++){
System.out.println(Street[k]);
}
}
}
Any other thoughts would be extremly helpful.
I would consider removing the unnecessary arrays and use a StringTokenizer...
public static void main(String[] args) {
String number;
String address;
String aptNumber;
String str = "This is String , split by StringTokenizer";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by space ------");
while (st.hasMoreElements()) {
String s = System.out.println(st.nextElement());
if (StringUtils.isNumeric(s) {
number = s;
continue;
}
if(s.indexOf("Apt")) {
aptNumber = s.substring(s.indexOf("Apt"),s.length-1);
continue;
}
}
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
If you leverage the freely available U.S. Postal Service zip code finder (https://tools.usps.com/go/ZipLookupAction!input.action), you can get back an address in standardized format. The valid options on that format are documented by the USPS and will make it easier to write a very complicated regex, or a number of simple regexes, to read the standard form.
I am still working on it, but for any in the future who may need to do this:
import java.util.Arrays;
import java.util.StringTokenizer;
import org.apache.commons.lang3.*;
class AddressTest{
public static void main (String[] arguments){
String adr1 = "100 village rest court";
//String adr2 = "1000 Arbor lane Apt. 21-D";
String reader = new String();
String holder = new String();
StringTokenizer a1 = new StringTokenizer(adr1);
String[] HouseNbr = new String[9];
String[] StreetName = new String[20];
String[] Apartment = new String[5];
int counter = 0;
while(a1.hasMoreElements()){
reader = a1.nextElement().toString();
System.out.println("Reader: " + reader);
if(StringUtils.isNumeric(reader)){
String[] HNBR = reader.split("");
for(int i = 1; i <= reader.length();i++){
System.out.println("HNBR:_" + HNBR[i]);
HouseNbr[i-1] = HNBR[i];
}
}
else if(StringUtils.startsWith(reader, "Apt.")){
holder = a1.nextElement().toString();
String[] ANBR = holder.split("");
for(int j = holder.length(); j >= 0;j--){
Apartment[j] = ANBR[j];
}
}
else{
String STR[] = reader.split("");
for(int k = 1; k <= reader.length();k++){
if(counter == StreetName.length){
break;
}
else{
StreetName[counter] = STR[k];
if(counter < StreetName.length){
counter++;
}
}
}
if((counter < StreetName.length) && a1.hasMoreElements()){
StreetName[counter] = " ";
counter++;
}
}
}
System.out.println(Arrays.toString(HouseNbr) + " " + Arrays.toString(StreetName)
+ " " + Arrays.toString(Apartment));
}
}

Categories