How do I print a 2d array? - java

My array is:
String[][] name = new String[15][2];
int rowNumber = 0;
My add button is:
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
I do not know what to put in my list button (lists the first name and last name) into my TextArea called outPut.
The Whole Code:
`
public class StudentGradesView extends FrameView {
String[][] name = new String[15][2];
double[][] testMark = new double[15][4];
int rowNumber = 0;
private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
rowNumber ++;
}
private void btnListMouseClicked(java.awt.event.MouseEvent evt) {
String outputStr = "";
for(int i=0; i < rowNumber; i++) {
outputStr += name[rowNumber][0] + " " + name[rowNumber][1] + "\n";
}outPut.setText(outputStr);
}
}`

Okay, I think I get what you want now.
First we take the inputs...
name[numberOfInputs][0] = firstName.getText();
name[numberOfInputs][1] = lastName.getText();
numberOfInputs += 1;
Now you want to output this to a textarea...
String outputStr = "";
for(int i=0; i < numberOfInputs; i++) {
outputStr += name[i][0] + " " + name[i][1] + "\n";
}
Then set your output textarea
outPut.setText(outputStr);
You are getting nulls because you are specifying a static array size but you (probably) are not filling up the array with test cases up to that amount. So you are printing elements of the array that are simply not populated.
Edit: for comments.

String st = "";
for (int i = 0; i < 15; i++)
st += name[i][0] + " " + name[i][1] + "\n";
outPut.setText(value);
This loops over the array and creates a string containing all the full names, separated by a line break.
This then sets the text using outPut.setText(value);

for(String[] s1d : s2d)
for(String s : s1d)
System.out.println(s);
A simple way using for() construct

The easiest way to print any array to any depth is to use Arrays.deepToString():
System.out.println(Arrays.deepToString(array));

try this:
import java.util.Arrays;
.
.
.
String[][] a = { { "john" },
{ "jones" }
};
System.out.println(Arrays.deepToString(a)); //whole string array
System.out.println(Arrays.deepToString(a[0])); //john
System.out.println(Arrays.deepToString(a[1])); //jones

Related

Getting names from text file shifts names 1 place to the left (in array)

I was trying to solve problem 22 of Euler Project. Description of what I'm trying to solve is here:
https://projecteuler.net/problem=22
Where's the problem?: I've got the names from the text file, put them on one string,
edited the string so that the names are separated by one space.
After getting those names on an array of Strings, I sort them. After finishing the program and getting the result wrong, I started testing different parts of the program and notice that the name "COLIN", which by eulerproject page is said to be the 938th, is 937th on my array. I can't seem to get why is it happening and how to fix this. Help would be much appreciated.
Here is the code:
package Project022;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class NameScore {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public NameScore(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
names = new File("Project022\\names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
String filtered = content.get(0).replaceAll("\",\"", " ");
//then remove first and last (")
filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
if (filtered.charAt(i) != ' '){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println(sortedNames[937]);
System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
NameScore name = new NameScore();
name.calculate();
System.out.println(name);
}
}
What I've ruled out as a problem:
the setScore() method which gives a score for every name, because I tested it with examples by hand and by program and got same results.
the calculate() method, since what it does is gets the score for each name and adds to the total sum.
This works for me.
Path p = Paths.get("p022_names.txt");
try {
List<String> lines = Files.readAllLines(p); // throws java.io.IOException
System.out.println(lines.size()); // Only one line in file.
// Remove all " (double quotes) characters.
String tmp = lines.get(0).replaceAll("\"", "");
String[] names = tmp.split(",");
System.out.println(names.length);
Arrays.sort(names);
// Test against example given in problem description.
System.out.println(names[937]); // Should be COLIN
char[] lett = names[937].toCharArray();
int sigma = 0;
for (int k = 0; k < lett.length; k++) {
sigma += lett[k] - 'A' + 1; // Since only uppercase letters in file.
}
int score = sigma * (937 + 1);
System.out.println(score); // Should be 49714
// Now obtain answer, i.e. the total of all the name scores in the file.
int total = 0;
for (int i = 0; i < names.length; i++) {
char[] letters = names[i].toCharArray();
int sum = 0;
for (int j = 0; j < letters.length; j++) {
sum += letters[j] - 'A' + 1;
}
total += sum * (i + 1);
}
System.out.println(total);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
Output obtained when running above code is as follows.
1
5163
COLIN
49714
871198282
I didn't want to make too many changes to your code, so just removed your replacement of "," and instead just removed all ". Then I added ALONSO in the end after the loop.
I figure if we're all in consensus about the total score of all the names, then we're doing it right :)
It prints:
-- Where's ALONSO ?
sortedNames[145] = ALONA
sortedNames[146] = ALONSO
sortedNames[147] = ALONZO
-- Where's COLIN ?
sortedNames[936] = COLETTE
sortedNames[937] = COLIN
sortedNames[938] = COLLEEN
-- Where's MARY ?
sortedNames[3361] = MARX
sortedNames[3362] = MARY
sortedNames[3363] = MARYA
-- sortedNames.length = 5163
the score of all names is: 871198282
I also called it Project022:
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
//public class NameScore {
public class Project022 {
private long scoreSum;
private LinkedList<String> allNames;
private String[] sortedNames;
private int[] nameScores;
public Project022(){
scoreSum = 0;
allNames = new LinkedList<>();
getNames();
}
private void getNames(){
List<String> content = null;
File names;
// read "names.txt" file and put all the names in one line(not effective when line
// length surpasses String maximum character range(2^31 - 1) but is good enough for us
// for now)
try {
// names = new File("Project022\\names.txt");
names = new File("resource\\p022_names.txt");
content = Files.readAllLines(Paths.get(names.getPath()), StandardCharsets.US_ASCII);
} catch (Exception e){
System.out.println("something went wrong while getting the file");
}
assert content != null;
//replace (",") with a space ( )
// String filtered = content.get(0).replaceAll("\",\"", " ");
String filtered = content.get(0).replaceAll("\"", "");
// //then remove first and last (")
// filtered = filtered.substring(1, filtered.length() - 1);
//declare "tempName" as a helper string
StringBuilder tempName = new StringBuilder();
//get every name and put it on the LinkedList
for (int i = 0; i < filtered.length(); i++) {
// if (filtered.charAt(i) != ' '){
if (filtered.charAt(i) != ','){
tempName.append(filtered.charAt(i));
} else {
allNames.add(tempName.toString().trim());
tempName = new StringBuilder();
}
}
allNames.add(tempName.toString().trim()); // added to include ALONSO
//now we use an pre defined array since it is faster.
sortedNames = new String[allNames.size()];
for (int i = 0; i < sortedNames.length; i++) {
sortedNames[i] = allNames.get(i);
}
//make the new array worthy of its name
Arrays.sort(sortedNames);
System.out.println("\n -- Where's ALONSO ?");
for (int i = 145; i < 148; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's COLIN ?");
for (int i = 936; i < 939; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- Where's MARY ?");
for (int i = 3361; i < 3364; i++) {
// sortedNames[0] = AARON
System.out.println("sortedNames[" + i + "] = " + sortedNames[i]);
}
System.out.println("\n -- sortedNames.length = " + sortedNames.length + "\n");
// System.out.println(Arrays.asList(sortedNames) + "\n" + sortedNames.length);
}
public void calculate(){
//we set the score for each name
nameScores = new int[sortedNames.length];
//
for (int i = 0; i < nameScores.length; i++) {
setScore(sortedNames[i], i + 1);
}
for (int i = 0; i < nameScores.length; i++) {
scoreSum += nameScores[i];
}
}
private void setScore(String name, int n) {
int sc = 0;
for (int i = 0; i < name.length(); i++) {
sc += (int)name.toUpperCase().charAt(i) - 'A' + 1;
}
sc *= n;
nameScores[n-1] = sc;
}
#Override
public String toString(){ return "the score of all names is: " + scoreSum; }
public static void main(String[] args) {
Project022 name = new Project022();
name.calculate();
System.out.println(name);
}
}

I want to print a formatted array in java

I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342
Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.
You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}
If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}
replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.

Method to do compare and change single characters in a string

I need to do a method to check two string for example bod and bot or crab and rab. The method needs to print out what the user must do in order to make them equal. For example in bod and bot it will print "replace,2,d in the string". I used this code which seems to work.
if(a.length()==b.length()){
int i;
for(i=0; i<=a.length(); i++){
if(a.charAt(i)!=b.charAt(i)){
return "replace,"+ i + "," + b.charAt(i);
}
}
}
But I am having troubles if the two string are not equal in size. I use this but it doesn't work because one of the strings is bigger.
int aS = a.length();
int bS = b.length();
if(bS - aS == 1){
int i;
for(i=0; i<=b.length(); i++){
if(b.charAt(i)!=a.charAt(i)){
return "remove," + i;
}
}
}
Can you guys give me a suggestion what method I can use to check which is the extra letter or vice versa a letter I can add and then return a string saying either to remove a character or add an extra one. Thank you
Maybe something like this?
public ArrayList<String> createConversionList(String primary, String secondary){
//Determine which string is shorter.
String shorter;
String longer;
boolean primaryIsShorter = false;
if (primary.length() >= secondary.length()){
longer = primary;
shorter = secondary;
} else{
longer = secondary;
shorter = primary;
primaryIsShorter = true;
}
//Fills an array with all the character positions that differ between the
//two strings, using the shorter string as the base.
int[] posOfCharsToChange = new int[shorter.length()];
for(int i = 0; i < shorter.length(); i++){
if(shorter.charAt(i) != longer.charAt(i)){
posOfCharsToChange[i] = i;
} else{
posOfCharsToChange[i] = -1;
}
}
//Adds to an ArrayList all of the "Replace" strings.
ArrayList<String> conversionList = new ArrayList();
for(int pos: posOfCharsToChange){
if(pos != -1){
String s = "Replace " + secondary.charAt(pos) + " with " + primary.charAt(pos) + ". \n";
conversionList.add(s);
}
}
//Depending on which string was bigger, either adds "Add" or "Remove"
//strings to the ArrayList. If the strings were the same size, does
//nothing.
if(primary.length() != secondary.length()){
if(primaryIsShorter){
for(int i = primary.length(); i < secondary.length(); i++){
String s = "Remove " + secondary.charAt(i) + ". \n";
conversionList.add(s);
}
}
else{
for(int i = secondary.length(); i < primary.length(); i++){
String s = "Add " + primary.charAt(i) + ". \n";
conversionList.add(s);
}
}
}
return conversionList;
}
My Approach works as follows
1) We take the smaller string and put all its contents in an arraylist
2) We take the bigger string and put its contents in the arraylist only if its not present in the arraylist
3) The last character in the arraylist must be removed from the bigger string to make them equal
Ex 1:
a = rab
b = crab
1) arraylist = rab -> contents of a added
2) arraylist = rabc -> only unique content of b is added
Ex 2:
a = crab
b = rab
1) arraylist = rab
2) arraylist = rabc
similarly if the positions are in the middle or not at start ,
ex : a = racb
b = rab
1) arraylist = rab
2) arraylist = rabc
public class Replace {
public static void main(String args[]) {
int p = 0, j = 0;
String a = "rab";
String b = "crab";
if (b.length() < a.length()) {
ArrayList al = new ArrayList();
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String a");
} else {
ArrayList al = new ArrayList();
for (j = 0; j < a.length(); j++) {
if (!al.contains(a.charAt(j))) {
al.add(a.charAt(j));
}
}
for (j = 0; j < b.length(); j++) {
if (!al.contains(b.charAt(j))) {
al.add(b.charAt(j));
}
}
System.out.println("Remove " + al.get(al.size() - 1)
+ " from String b");
}
}
}
Note - The program only works under your given contraints that strings only differ in one character and the ordering of both the strings is not different if we remove or add that charcter.

Reading in information into multiple arrays

The purpose of this program is to take information from a file about a music collection and turn it into three arrays.
>4
>141 Pure Heroine:Lorde
>171 Lights Out:Ingrid Michaelson
>270 Unorthodox Jukebox :Bruno Mars
>190 Head Or Heart:Christina Perri
In the file, the 4 stands for how long the arrays will be, the numbers are one array, the album titles another, and the artist names are the final array. The arrays for the titles and artist names are separated by the colon. While I can create the array for the numbers, what is giving me trouble is how to create the separate arrays for name and titles. I understand that I have to convert it into a sting and use the colon as a delimiter but I'm unsure as to how.
import java.util.*;
import java.io.*;
public class tunes {
public static void main(String[] args) throws FileNotFoundException {
int size; //Determines the size of the arrays
Scanner input = new Scanner(new File("music.txt"));
size = input.nextInt();
int[] time = new int[size];
for (int i = 0; i < time.length; i++) { // Creates an array for the numbers
time[i] = input.nextInt();
input.nextLine();
}
String[] artist = new String[size];
for (int i = 0; i <artist.length; i++) {
while (input.hasNextLine()){
}
}
System.out.println();
System.out.println("TOTAL TIME\t\t\t\t" + calcTotalTime(time));
System.out.println();
System.out.println();
System.out.println("LONGEST TRACK");
System.out.println("-------------");
System.out.println();
System.out.println();
System.out.println("SHORTEST TRACK");
System.out.println("--------------");
}
public static void printTable(int[] time, String[] artist, String[] title) {
System.out.println("TITLE\t\t\t" + "ARTIST\t\t\t " + "TIME");
System.out.println("-----\t\t\t" + "------\t\t\t " + "----");
for (int i = 0; i < time.length; i++) {
System.out.println(title[i] + "\t" + artist[i] + "\t" + time[i]);
}
}
public static int calcTotalTime(int[] time) {
int sum = 0;
for (int i = 0; i < time.length; i++) {
sum = sum + time[i];
}
return sum;
}
public static int findLongest(int[] time) {
int longest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] > time[longest]) {
longest = i;
}
}
return longest;
}
public static int findShortest(int[] time) {
int shortest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] < time[shortest]) {
shortest = i;
}
}
return shortest;
}
}
An example of how the output would look like would be
>Pure Heroine Lorde 141
>Lights Out Ingrid Michaelson 171
>Unorthodox Jukebox Bruno Mars 270
>Head or Heart Christina Perri 190
You can use String.split(":") on your text to split the artist/title Strings into String[] arrays.
For instance:
System.out.println(Arrays.toString("Head Or Heart:Christina Perri".split(":")));
Output
[Head Or Heart, Christina Perri]
Use the String split() method to save the pieces into a new array. The split() method takes a regular expression - see this question about how to use it. The colon is not a special character in a RegExp and therefore does not need to be escaped.
Allocate all the arrays first after reading the length of the arrays, then parse each line in one go using split to tokenize the artist-title part of the line.
size = input.nextInt();
int[] time = new int[size];
String[] artist = new String[size];
String[] title = new String[size];
for (int i = 0; i < time.length; i++) {
time[i] = input.nextInt();
String[] parts = input.next().split( ":" );
artist[i] = parts[0];
title[i] = parts[1];
}

using a method to print an array in java

From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
You need to call the method and print the result. Also use the array iA in your method.
System.out.println(display());
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i. During your loop, you should be adding the space as well as the value at the current array position.
Your method display() is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display

Categories