Beginner - Java 2D Array - java

I've created the following:
import java.util.*;
public class morse5 {
public static void main(String [] args)
{
//Declare Variables
String [][] myIndexAlphaMorse = {{"a", ".-"}, {"b", "-..."}, {"c", "-.-."}, {"d", "-.."}, {"e", "."}, {"f", "..-."}, {"g", "--."}, {"h", "...."}, {"i", ".."}, {"j", ".---"}, {"k", "-.-"}, {"l", ".-.."}, {"m", "--"}, {"n", "-."}, {"o", "---"}, {"p", ".--."}, {"q", "--.-"}, {"r", ".-."}, {"s", "..."}, {"t", "-"}, {"u", "..-"}, {"v", "...-"}, {"w", ".--"}, {"x", "-..-"}, {"y", "-.--"}, {"z", "--.."}, {"1", ".----"}, {"2", "..---"}, {"3", "...--"}, {"4", "....-"}, {"5", "....."}, {"6", "-...."}, {"7", "--..."}, {"8", "---.."}, {"9", "----."}, {"0", "-----"}, {" ", "|"}};
//Test
System.out.println(Arrays.deepToString(myIndexAlphaMorse));
System.out.println(myIndexAlphaMorse[8][0]);
}
What I would like to know is how to get the value of the corresponding position based on user input. I'm learning, so I just want the piece on how to get, as an example, .- back when "a" is entered.

Simply iterate over you array and compare the 0th element at each position with the character you are looking for.
String input = "v";
String result= "";
for(int i = 0; i < myIndexAlphaMorse.length; i++){
if(myIndexAlphaMorse[i][0].equals(input)){
result = myIndexAlphaMorse[i][1];
break;
}
}
System.out.println("morse for " + input + " = " + result);
But as the other answer says you should use a map that whould fit perfect for this task.

You should consider using a Map instead of a two dimensional array for this problem:
Map<String, String> myIndexAlphaMap = new HashMap<>();
myIndexAlphaMap.put("a", ".-");
myIndexAlphaMap.put("b", "-...");
// etc.
// given user input of "a" you can access via
myIndexAlphaMap.get("a");

Or a map of string arrays
Map<String, String[]> myIndexAlphaMap = new HashMap<String, String[]>();
myIndexAlphaMap.put("a", new String {".","-"});
myIndexAlphaMap.put("b", new String {"-",".","."});
// given user input of "a" you can access via
myIndexAlphaMap.get("a")[0];

You can also use Hash tables, since they've already given sample above of HashMap/Map:
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("a", ".-");
table.put("b", "-...");
It is also synchronized and thread safe unlike HashMaps, albeit is a smidgen slower for bigger data sets.

First of all you have to read the letter as the String object. Then you can just iterate through your array and when we find what we are looking for - just print it and break the loop:
Scanner scanner = new Scanner(new InputStreamReader(System.in));
String letter = scanner.next();
for (int i=0; i<myIndexAlphaMorse.length; i++)
if (myIndexAlphaMorse[i][0].equals(letter)){
System.out.println(myIndexAlphaMorse[i][1]);
break;
}

Related

Transferring data from double array to HashMap

Creating a double array (one row for states, and one for capitols), I am trying to use 'map.put' in a for loop to save the arrays 'key(states)' and 'value(capitols)' to the HashMap. When using a key from user input after assigning a new HashMap (hMap = getInfo();, My output returns "null". Im not quite sure what it is im doing wrong, but I have a feeling I made an error in the for loop.
public class HashMapProgram {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
//Assign contents of map in getInfo to hMap
HashMap<String, String> hMap = getInfo();
//Prompting user to input a state (key)
System.out.print("Enter a state, or \"done\" when finished: ");
String state = input.next();
if(hMap.get(state) != "done")
System.out.println("The capital is "+ hMap.get(state));
}
public static HashMap<String, String> getInfo(){
//HashMap to save contents in
HashMap<String, String> map = new HashMap<>();
String x[][] = {
{"Alabama","Alaska","Arizona" ,"Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia",
"Hawaii" ,"Idaho" ,"Illinois" ,"Indiana" ,"Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland",
"Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey",
"New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington","West Virginia","Wisconsin","Wyoming"},
{"Montgomery","Juneau","Phoenix","Little Rock","Sacramento","Denver","Hartford","Dover","Tallahassee","Atlanta",
"Honolulu","Boise","Springfield","Indianapolis","Des Moines","Topeka","Frankfort","Baton Rouge","Augusta", "Annapolis",
"Boston","Lansing","St. Paul","Jackson","Jefferson City","Helena","Lincoln","Carson City","Concord","Trenton",
"Santa Fe","Albany","Raleigh","Bismarck","Columbus","Oklahoma City","Salem","Harrisburg","Providence","Columbia",
"Pierre","Nashville","Austin","Salt Lake City","Montpelier","Richmond","Olympia","Charleston","Madison","Cheyenne"}
};
//Saving contents in 'map'
for(int i = 0; i < x.length; i++) {
map.put(x[0][i], x[1][i]);
}
return map;
}
}
There are a few errors:
1) In your for-loop, change i < x.length; to i < x[0].length;, otherwise you're running the loop just 2 times.
2) Don't compare strings using !=. Use equals() instead. See this for more details.
3) You don't have a loop to ask for user input repeatedly. Change your code in main() to:
Scanner input = new Scanner(System.in);
HashMap<String, String> hMap = getInfo();
String state = "";
do {
System.out.print("Enter a state, or \"done\" when finished: ");
state = input.next();
System.out.println("The capital is " + hMap.get(state));
} while (!state.equals("done"));
4) Work with interface, not class. So change
HashMap<String, String> hMap = getInfo();
to
Map<String, String> hMap = getInfo();
and also update the method signature to return Map<String, String>.
5) Since Java 9, you can directly create a map like this:
Map<String, String> m = Map.of(
"Alabama", "Montgomery",
"Alaska", "Juneau",
"Arizona", "Phoenix"
//and so on...
);

Input a name and a role and get an output of that role with the names

I need to do this for school. Its supposed to be a JAVA project.
So for example, if we give an input:
thomas teacher
charlie student
abe janitor
jenny teacher
The output will be:
teachers,thomas,jenny
students,charlie,
janitor,abe.
I am just a beginner so, so far I have this code:
`Scanner in = new Scanner(System.in);
String line = in.nextLine();
String[] words = line.split(" ");
//TreeMap treemap = new TreeMap();
ArrayList<String> admin = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true){
Boolean s = input.nextLine().equals("Done");
//treemap.put(line, "admin");
if(words[1].contentEquals("admin")){
admin.add(words[0]);
}
else if(s == true){
break;
}
}
System.out.println("admins," + "," + admin);`
I was originally using a treemap but I don't know how to make it work so I thought of using an ArrayList and eliminating the brackets at the end.
EDIT:
So I now have the code:
HashMap<String, String> teacher = new HashMap<String, String>();
HashMap<String, String> student = new HashMap<String, String>();
HashMap<String, String> janitor = new HashMap<String, String>();
System.out.println("Enter a name followed by a role.");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Scanner name = new Scanner(System.in);
String r = name.nextLine();
while(true){
if(line.equals(r + " " + "teacher")){
teacher.put(r, "teacher");
}
}
I'll give you the hint because you should do it yourself.
Use a HashMap<String, List<String>> map and insert your inputs like below:
if(map.containsKey(words[1]))
{
List<String> list = map.get(words[1]);
list.add(words[0]);
map.put(words[1],list);
}
else
{
map.put(words[1],Arrays.asList(words[0]))
}
This way you will get list of names corresponding to each types(student/teacher) etc.
After that iterate over the map and print the list.
I think for a small amount of occupations it's reasonable to accomplish this using just array lists. I think the part you are having trouble with is the input structure so I'll help you out with an example of how to do that part and let you handle the filtering on your own:
private List<String> teachers = new ArrayList<>();
private List<String> students = new ArrayList<>();
private List<String> janitors = new ArrayList<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//Do whatever printing you have to do down here
}
private void putInArray(String name, String occupation) {
//filter and add to the correct list in here
}
If you wanted to implement this using a hashmap the input method would be the same, but instead of putting names into 3 pre-made occupation arraylists you create arraylists and put them inside a hashmap as you go:
private HashMap<String, List<String>> peopleHashMap = new HashMap<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//You can get all the keys that you created like this
List<String> keys = new ArrayList<>(peopleHashMap.keySet());
}
private void putInArray(String name, String occupation) {
if(peopleHashMap.containsKey(occupation)){
//If the key (occupation in this case) is already in the hashmap, that means that we previously
//made a list for that occupation, so we can just the name to that list
//We pull out a reference to the list
List<String> listOfNames = peopleHashMap.get(occupation);
//And then put the new name into that list
listOfNames.add(name);
}else{
//If the key isn't in the hashmap, then we need to make a new
//list for this occupation we haven't seen yet
List<String> listOfNames = new ArrayList<>();
//We then put the name into the new list we made
listOfNames.add(name);
//And then we put that new list with the into the hashmap with the occupation as the key
peopleHashMap.put(occupation, listOfNames);
}
}

How to print array values using a nested for loop to a CSV file?

I tried to go with a simple fix to my issue for printing the array to the .csv file and replacing certain characters, however I noticed later that I am not supposed to use any spaces before or after the commas in my output.
I can't use replace or else all of the header labels will have zero spaces either, so I need help with getting the values directly from my nested for loops.
import java.io.*;
import java.util.Arrays;
public class HW01 {
public static void main(String args[]) throws IOException {
// Create a 1D array to hold header labels
String headerLabels[] =
{"COURSE ID", "TEAM ID", "STUDENT FIRST NAME",
"STUDENT LAST NAME", "STUDENT ID", "ASSIGNMENT ID",
"DATE SUBMITTED", "TIME SUBMITTED", "SUBMITTED BY"
};
// Create a 2D array to hold header values
String headerValues[][] =
{
{"CMPS280-02", "Invokers01", "James", "Brown", "w0479045", "H01", "8/25/2017", "1:14PM", "James Brown"},
{"CMPS280-01", "Winners03", "Jacob", "Harley", "w0389342", "H03", "8/23/2017", "7:24PM", "Jacob Harley"},
{"SE101-02", "CodeIt00", "Keith", "Dillinger", "w0782345", "S04", "8/25/2017", "1:23AM", "Keith Dillinger"}
};
// Create an int to hold number of students
int students = headerValues.length;
// Array loop to create student .csv files
for (int i = 0; i < headerValues.length; i++){
for (int j = 0; j < students; j++){
// Create new .csv file and store in SUBMIT folder
String path = "SUBMIT/"+headerValues[i][0]+"_"+headerValues[i][5]+"_"+headerValues[i][1]+"_"+headerValues[i][4]+".csv";
File file = new File(path);
PrintWriter writer = new PrintWriter(file);
// Print headerLabels and headerValues for each student into .csv files
writer.println(Arrays.toString(headerLabels).replace("[", "").replace("]", "").replace(" , " , ","));
writer.println(Arrays.toString(headerValues[i]).replace("[", "").replace("]", "").replace(" , ", ","));
writer.close();
}
}
}
}
The nested loop isn't exactly the problem. The order in which you've tried to write the contents is. You only want 1 file for all the students, I assume, not i*j files. One for each student.
For example,
// Create student .csv files and store in SUBMIT folder
String path = "SUBMIT/students.csv";
try (PrintWriter writer = new PrintWriter(new File(path))) {
// Print header row
writer.println(String.join(",", headerLabels));
// Print all data rows
for (String[] studentData : headerValues){
writer.println(String.join(",", studentData);
}
}

Java How do I sort a 2D string array entirely

Hi guys I've searched the site about 2D array sorting in java and they all involved only one column. I want to know how I can sort a 2D array alphabetically in each column. I've tried using comparators but it only sorts one column.
I have to output my word bank in alphabetical or reverse alphabetical (depending on user's choice) by each column and output a table.
String word[][] ={
{"The", "ball", "the", "book"},
{"It", "dog", "a/an", "efficiently"},
{"A/An", "has", "some", "dog"},
{"Laura", "ant", "rolled", "cat"},
{"William", "cat", "ran", "apple"},
{"Alex", "ate", "big", "pear"},
{"Chris", "smelled", "small", "slowly"},
{"Daniel", "planted", "jumped", "truck"},
{"Joshua", "washed", "rotten", "awkward"},
{"Rachel", "bear", "juicy", "shirt"},
{"Jimmy", "boiled", "roared", "plant"},
{"Emily", "liked", "vibrant", "away"},
{"Erin", "touched", "swam", "chair"},
{"Michael", "hippo", "long", "bicep"},
{"Steven", "grabbed", "short", "phone"},
{"Andrew", "kept", "massive", "quickly"},
};
So the example output will be:
A/An "\t" ant "\t" a/an "\t" apple
Andrew "\t" ate "\t" juicy "\t" away
Alex "\t" ball "\t" jumped "\t" book
Thanks in advance!
You need to reorder your data by columns, and sort the columns. For example:
String word[][] ={
{"The", "ball", "the", "book"},
{"It", "dog", "a/an", "efficiently"},
{"A/An", "has", "some", "dog"},
{"Laura", "ant", "rolled", "cat"},
{"William", "cat", "ran", "apple"},
{"Alex", "ate", "big", "pear"},
{"Chris", "smelled", "small", "slowly"},
{"Daniel", "planted", "jumped", "truck"},
{"Joshua", "washed", "rotten", "awkward"},
{"Rachel", "bear", "juicy", "shirt"},
{"Jimmy", "boiled", "roared", "plant"},
{"Emily", "liked", "vibrant", "away"},
{"Erin", "touched", "swam", "chair"},
{"Michael", "hippo", "long", "bicep"},
{"Steven", "grabbed", "short", "phone"},
{"Andrew", "kept", "massive", "quickly"},
};
// generate the list of columns
List<List<String>> cols=new ArrayList<>();
for (String[] row:word){
for (int a=0;a<row.length;a++){
// create columns when needed
while(cols.size()<a+1){
cols.add(new ArrayList<String>());
}
List<String> col=cols.get(a);
col.add(row[a]);
}
}
// rewrite sorted words in word array
int colIdx=0;
for (List<String> col:cols){
// sort column
Collections.sort(col);
for (int a=0;a<col.size();a++){
word[a][colIdx]=col.get(a);
}
colIdx++;
}
// print
for (String[] row:word){
String sep="";
for (String w:row){
System.out.print(sep);
sep="\t";
System.out.print(w);
}
System.out.println();
}

incompatible type of double array and properties string.split()

public static void main(String[] args)
{
String input="jack=susan,kathy,bryan;david=stephen,jack;murphy=bruce,simon,mary";
String[][] family = new String[50][50];
//assign family and children to data by ;
StringTokenizer p = new StringTokenizer (input,";");
int no_of_family = input.replaceAll("[^;]","").length();
no_of_family++;
System.out.println("family= "+no_of_family);
String[] data = new String[no_of_family];
int i=0;
while(p.hasMoreTokens())
{
data[i] = p.nextToken();
i++;
}
for (int j=0;j<no_of_family;j++)
{
family[j][0] = data[j].split("=")[0];
//assign child to data by commas
StringTokenizer v = new StringTokenizer (data[j],",");
int no_of_child = data[j].replaceAll("[^,]","").length();
no_of_child++;
System.out.println("data from input = "+data[j]);
for (int k=1;k<=no_of_child;k++)
{
family[j][k]= data[j].split("=")[1].split(",");
System.out.println(family[j][k]);
}
}
}
i have a list of family in input string and i seperate into a family and i wanna do it in double array family[i][j].
my goal is:
family[0][0]=1st father's name
family[0][1]=1st child name
family[0][2]=2nd child name and so on...
family[0][0]=jack
family[0][1]=susan
family[0][2]=kathy
family[0][3]=bryan
family[1][0]=david
family[1][1]=stephen
family[1][2]=jack
family[2][0]=murphy
family[2][1]=bruce
family[2][2]=simon
family[2][3]=mary
but i got the error as title: in compatible types
found:java.lang.String[]
required:java.lang.String
family[j][k]= data[j].split("=")[1].split(",");
what can i do?i need help
nyone know how to use StringTokenizer for this input?
Trying to understand why you can't just use split for your nested operation as well.
For example, something like this should work just fine
for (int j=0;j<no_of_family;j++)
{
String[] familySplit = data[j].split("=");
family[j][0] = familySplit[0];
String[] childrenSplit = familySplit[1].split(",");
for (int k=0;k<childrenSplit.length;k++)
{
family[j][k+1]= childrenSplit[k];
}
}
You are trying to assign an array of strings to a string. Maybe this will make it more clear?
String[] array = data.split("=")[1].split(",");
Now, if you want the first element of that array you can then do:
family[j][k] = array[0];
I always avoid to use arrays directly. They are hard to manipulate versus dynamic list. I implemented the solution using a Map of parent to a list of childrens Map<String, List<String>> (read Map<Parent, List<Children>>).
public static void main(String[] args) {
String input = "jack=susan,kathy,bryan;david=stephen,jack;murphy=bruce,simon,mary";
Map<String, List<String>> parents = new Hashtable<String, List<String>>();
for ( String family : input.split(";")) {
final String parent = family.split("=")[0];
final String allChildrens = family.split("=")[1];
List<String> childrens = new Vector<String>();
for (String children : allChildrens.split(",")) {
childrens.add(children);
}
parents.put(parent, childrens);
}
System.out.println(parents);
}
The output is this:
{jack=[susan, kathy, bryan], murphy=[bruce, simon, mary], david=[stephen, jack]}
With this method you can directory access to a parent using the map:
System.out.println(parents.get("jack"));
and this output:
[susan, kathy, bryan]

Categories

Resources