JAVA 2D Array Loop Print Formatting [0][0], [1][1], etc - java

I am having trouble getting my 2D array to print side by side values taking the first array row value index 0 and matching it to the 2nd row array index 0 and continuing on in a vertical list. As it stands, my code compiles and just prints the entire arrays in a horizontal fashion on two lines. Basically, I would like the end result to be formatted like this:
Admin | Password1
Vale.Vicky | BruceIsTheBat!
Lane.Lois | FlyMeToTheMoon1234
Kent.Clark | PhoneBoothsSmell
Wayne.Bruce | ThisBat4You99
...and so on.
public class PasswordArrays { // start of class
public static void main(String[] args) { // Start of main
// TODO Auto-generated method stub
String [][] idArray = {
{"Admin", "Vale.Vicky", "Lane.Lois", "Kent.Clark", "Wayne.Bruce", "Parker.Peter", "Rogers.Steve", "Luther.Lex", "Osborn.Harry","Prince.Diana", "Linda Zoel"},
{"Password1", "BruceIsTheBat!", "FlyMeToTheMoon1234", "PhoneBoothsSmell","ThisBat4You99", "webSlinger","ShieldEnthusiast", "HairClub4Men", "GoblinGoober", "WonderWonderWho?", "WhoIsLindaZoel?"}
};
printArray(idArray);
} //End of main
public static void printArray(String a [][]) { //start of printArray method
for (int row=0; row < a.length ; row++) { // start of row for loop
for (int column = 0; column < a [row].length; column++) { //start of column for loop
System.out.print(a[row][column] + " ");
} // End of column for loop
System.out.println();
} // End of row for loop
} // End of printArray method
} //End of class
I know there's got to be an answer already for this somewhere but I have been unsuccessful in finding it. Any help is greatly appreciated.

A 2D array could be iterated in two ways:
Row wise
Column wise
As per your expected result, what you would want to do is iterate column wise rather than row wise. Here's a solution:
public static void printArray(String a [][]) {
for(int col=0; col < a[0].length; col++) {
for (int row = 0; row < a.length; row++) {
if (row!=a.length-1) {
System.out.print(a[row][col] + "|");
}
else {
System.out.print(a[row][col]);
}
}
System.out.println();
}
}
Helpful Link: Iterate through multi-dimensional array

you are traversing your 2D array incorrectly
you can try this for your array:
if(a.length > 0){
for(int i = 0; i < a[0].length; i++){
for(int j = 0;j < a.length; j++){
System.out.print(a[j][i]+" ");
}
System.out.println("");
}
}

Structure
Are you sure that you understood the structure of your 2d-array? You only have two rows but multiple columns (the array contains 2 arrays containing multiple elements each).
The structure is
idArray = { /* firstArray, secondArray */ }
idArray[0] = { /* Names */ }
idArray[1] = { /* Passwords */ }
Solution
You only need one iteration from int i = 0; to i < idArray[0].length. After that always pair the content of idArray[0][i] with idArray[1][i], that's all.
final int[][] idArray = ...
// Variant 1: Regular for-loop
for (int i = 0; i < idArray[0].length; i++) {
System.out.println(idArray[0][i] + " | " + idArray[1][i];
}
// Variant 2: Stream solution
IntStream.range(0, idArray[0].length) // IntStream
.map(i -> idArray[0][i] + " | " + idArray[1][i]) // Stream<String>
.forEach(System.out::println);
Note that idArray[0].length and idArray[1].length should of course be equal.
Notes
Probably you are better off using proper OOP, creating classes for each Account containing name and password fields and then using a List<Account> and toString for Account or something like that.
public class Account {
private final String mName;
private final String mPassword;
public Account(final String name, final String password) {
this.mName = name;
this.mPassword = password;
}
public String getName() {
return this.mName;
}
public String getPassword() {
return this.mPassword;
}
#Override
public String toString() {
return this.getName() + " | " + this.getPassword();
}
}
And then use it like
final List<Account> accounts = new ArrayList<>();
accounts.add(new Account("Admin", "Password1"));
...
// Variant 1: Enhanced for-loop 'foreach'
for (final Account account : accounts) {
System.out.println(account);
}
// Variant 2: The same using streams
accounts.forEach(System.out::println);
// Variant 3: Using Lists 'toString'
System.out.println(accounts);

Related

Java Insertion Sorting with ArrayLists of Strings

I have an assignment on sorting which requires me to sort a list of random words by putting letters that start with the same letter in a group/zones and sorting that group alphabetically. My code sorts the words but my problem is that some of the words have changed. For example instead of having an output as
angela
APPLE
Apple
apple
Baboon
Ball
Cat
cat
PINK
Pink
Steve
I would have an output of :
apple
apple
apple
apple
Ball
Ball
cat
cat
Pink
PINK
Steve
As you can see, some of the words have been changed and in some cases, words with a capital letter are turned into lower cases like "cat" and I can't seem to find where my mistake is.
This is my sorting code; my driver class just takes in the list of random words :
import java.util.ArrayList;
import java.util.Collections;
public class ZoneSort
{
ArrayList[] arrayOfZones;
ArrayList<String> words;
public ZoneSort(ArrayList<String> words)
{
arrayOfZones = new ArrayList [ 26 ];
for(int index = 0; index < 26;index++)
arrayOfZones [ index ] = new ArrayList();
this.words = words;
putWordsIntoZones();
}
private void putWordsIntoZones()
{
for(String word: words)
{
int index = Character.toLowerCase(word.charAt(0)) - 97;
ArrayList<String> zoneAtIndex = arrayOfZones[index];
zoneAtIndex.add(word);
}
}
public void sortTheArrayOfZones()
{
for(ArrayList<String> zone : arrayOfZones )
{
sortZone(zone);
}
}
private void sortZone(ArrayList<String> zone)
{
for(int i = 1; i < zone.size(); i++)
{
String key = zone.get(i);
int j = i-1;
while(j>=0 && key.compareTo(zone.get(j)) > 0)
{
String x = zone.get(j+1);
zone.set(j, x);
j--;
}
String x = zone.get(j+1);
x = key;
}
}
public void printArrayOfZones()
{
System.out.println("The sorted words are");
for(ArrayList<String> zone:arrayOfZones)
{
for(String word: zone)
{
System.out.println(word);
}
}
}
Reading your code and viewing your results, it seems that your code overwrites the values instead of swapping them. To fix this you need to take a look at the function sort.
I have modified your code so that instead of overwriting, you swap the two elements :
private void sortZone(ArrayList<String> zone){
for(int i = 1; i < zone.size(); i++){
String key = zone.get(i);
int j = i-1;
while(j>=0 && key.compareTo(zone.get(j)) > 0){
String x = zone.get(j+1);
zone.set(j+1,zone.get(j)); // line added
zone.set(j, x);
j--;
}
String x = zone.get(j+1);
x = key;
}
}
I hope this fixed your problem.
If I compare your sortZone implementation with a reference insertion sort implementation such as https://www.baeldung.com/java-insertion-sort
I see the following differences - see inline comments
for(int i = 1; i < zone.size(); i++)
{
String key = zone.get(i);
int j = i-1;
// The sort order is reversed.
// You've used "key > zone[j]" when it should be "key < zone[j]"
while(j>=0 && key.compareTo(zone.get(j)) < 0)
{
// This is copying items backwards, towards the beginning of the array.
// String x = zone.get(j+1);
// zone.set(j, x);
// It should be copying items forwards, towards the end, to make room for "key"
// Like this:
String x = zone.get(j);
zone.set(j+1, x);
j--;
}
// You should be setting zone[j+1] = "key" - this does not do it:
// String x = zone.get(j+1);
// x = key;
// This is how you set a value in a list:
zone.set(j+1, key);
}

Remove duplicates in 2d array

I want to remove duplicate row in a 2d array . i tried the below code .but it is not working . please help me .
Input :
1,ram,mech
1,ram,mech
2,gopi,csc
2.gopi,civil
output should be :
1,ram,mech
2,gopi,csc
2.gopi,civil
Code :
package employee_dup;
import java.util.*;
public class Employee_dup {
public static void main(String[] args)
{
boolean Switch = true;
System.out.println("Name ID Dept ");
String[][] employee_t = {{"1","ram","Mech"},{"1","siva","Mech"},{"1","gopi","Mech"},{"4","jenkat","Mech"},{"5","linda","Mech"},{"1","velu","Mech"}};
int g = employee_t[0].length;
String[][] array2 = new String[10][g];
int rows = employee_t.length;
Arrays.sort(employee_t, new sort(0));
for(int i=0;i<employee_t.length;i++){
for(int j=0;j<employee_t[0].length;j++){
System.out.print(employee_t[i][j]+" ");
}
System.out.println();
}
List<String[]> l = new ArrayList<String[]>(Arrays.asList(employee_t));
for(int k = 0 ;k < employee_t.length-1;k++)
{
if(employee_t[k][0] == employee_t[k+1][0])
{
System.out.println("same value is present");
l.remove(1);
array2 = l.toArray(new String[][]{});
}
}
System.out.println("Name ID Dept ");
for(int i=0;i<array2.length;i++){
for(int j=0;j<array2[0].length;j++){
System.out.print(array2[i][j]+" ");
}
System.out.println();
}
}
}
class sort implements Comparator {
int j;
sort(int columnToSort) {
this.j = columnToSort;
}
//overriding compare method
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[j].compareTo(row2[j]);
}
}
First I sorted the array based on column one ,then tried to remove duplicates by checking the first column elements and seconds column elements but it is not removing the required column but remove other columns.
You may give this solution a try:
public static void main(String[] args) {
String[][] employee_t = {
{"1","ram","Mech"},
{"1","ram","Mech"},
{"1","siva","Mech"},
{"1","siva","Mech"},
{"1","gopi","Mech"},
{"1","gopi","Mech"} };
System.out.println("ID Name Dept");
Arrays.stream(employee_t)
.map(Arrays::asList)
.distinct()
.forEach(row -> System.out.printf("%-3s%-7s%s\n", row.get(0), row.get(1), row.get(2)));
}
Output
ID Name Dept
1 ram Mech
1 siva Mech
1 gopi Mech
How it works: comparing arrays does rely on instance equality and not on comparing contained elements by equals. Hence converting each row of your 2D array into a List will enable you to compare lists, which takes equals of the elements contained into account.
The Java Stream API does provide a method distinct which relies on equals and will remove all duplicates for you.
Based on your code. Maybe it is not the BEST solution but it works.
public static void main(String[] args) {
System.out.println("Name ID Dept ");
// I added duplicated rows
String[][] inputArray = {
{ "1", "ram", "Mech" },
{ "1", "siva", "Mech" },
{ "1", "gopi", "Mech" },
{ "1", "gopi", "Mech" },
{ "4", "jenkat", "Mech" },
{ "5", "linda", "Mech" },
{ "1", "velu", "Mech" },
{ "1", "velu", "Mech" }
};
// I will add all rows in a Set as it doesn't store duplicate values
Set<String> solutionSet = new LinkedHashSet<String>();
// I get all rows, create a string and insert into Set
for (int i = 0 ; i < inputArray.length ; i++) {
String input = inputArray[i][0]+","+inputArray[i][1]+","+inputArray[i][2];
solutionSet.add(input);
}
// You know the final size of the output array
String[][] outputArray = new String[solutionSet.size()][3];
// I get the results without duplicated values and reconvert it to your format
int position = 0;
for(String solution : solutionSet) {
String[] solutionArray = solution.split(",");
outputArray[position][0] = solutionArray[0];
outputArray[position][1] = solutionArray[1];
outputArray[position][2] = solutionArray[2];
position++;
}
System.out.println("Name ID Dept ");
for (int i = 0; i < outputArray.length; i++) {
for (int j = 0; j < outputArray[0].length; j++) {
System.out.print(outputArray[i][j] + " ");
}
System.out.println();
}
}
I have posted what I think is a readable and easy to maintain solution.
I decided to use distinct from Stream which is part of Java 8
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream. - https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--
Main.class
class Main {
public static void main(String[] args)
{
//Create a list of Employee objects
List<Employee> employeeList = new ArrayList<Employee>();
Employee e1 = new Employee(1, "ram", "mech");
Employee e2 = new Employee(1, "ram", "mech");
Employee e3 = new Employee(2, "gopi", "csc");
Employee e4 = new Employee(2, "gopi", "civil");
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
System.out.println("Before removing duplicates");
employeeList.stream().forEach(System.out::println);
//This is where all the magic happens.
employeeList = employeeList.stream().distinct().collect(Collectors.toList());
System.out.println("\nAfter removing duplicates");
employeeList.stream().forEach(System.out::println);
}
}
Output:
Before removing duplicates
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=2, valB=gopi, valC=csc]
Employee [valA=2, valB=gopi, valC=civil]
After removing duplicates
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=2, valB=gopi, valC=csc]
Employee [valA=2, valB=gopi, valC=civil]
Employee.class
//This is just a regular POJO class.
class Employee {
int valA;
String valB, valC;
public Employee(int valA, String valB, String valC){
this.valA = valA;
this.valB = valB;
this.valC = valC;
}
public Employee(Employee e) {
this.valA = e.valA;
this.valB = e.valB;
this.valC = e.valC;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + valA;
result = prime * result + ((valB == null) ? 0 : valB.hashCode());
result = prime * result + ((valC == null) ? 0 : valC.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof Employee && ((Employee)obj).hashCode() == this.hashCode()){
return true;
}
return false;
}
#Override
public String toString() {
return "Employee [valA=" + valA + ", valB=" + valB + ", valC=" + valC + "]";
}
}
Pre Java - 8 solution. May not be the best way. But a quick solution which works..
String[][] records = {
{"1","ram","Mech"},
{"1","ram","Mech"},
{"1","gopi","csc"},
{"1","gopi","civil"} };
List<String[]> distinctRecordsList = new ArrayList<String[]>();
for(String[] record : records){
if(distinctRecordsList.size()>0){
boolean sameValue = false;
for(String[] distinctRecord : distinctRecordsList){
int distinctRecordFields = distinctRecord.length;
if(record.length==distinctRecordFields){
for(int k=0;k<distinctRecordFields;k++){
sameValue = record[k].equalsIgnoreCase(distinctRecord[k]);
if(!sameValue)
break;
}
}else
throw new Exception("Can't compare the records");
}
if(!sameValue)
distinctRecordsList.add(record);
}else if(distinctRecordsList.size()==0)
distinctRecordsList.add(record);
}
Object[] distRecObjects = distinctRecordsList.toArray();
String[][] distinctRecordsArray = new String[distRecObjects.length][];
int i=0;
for(Object distRecObject : distRecObjects){
distinctRecordsArray[i] = (String[]) distRecObject;
i++;
}
Contrary to some other answers I will try to explain what went wrong in your own code and how to fix it within your code (I agree very much with kkflf that an Employee class would be a huge benefit: it’s more object-oriented and it will help structure the code and give better overview of it).
The issues I see in your code are:
You are not removing the correct element when you detect a duplicate, but always the element at index 1 (the second element since indices count from 0). This isn’t trivial, though, because indices shift as you remove elements. The trick is to iterate backward so only indices that you are finished with shift when you remove an element.
You are using == to compare the first element of the subarrays you are comparing. If you wanted to compare just the first element, you should use equals() for comparison. However, I believe you want to compare the entire row so 2,gopi,csc and 2.gopi,civil are recognized as different and both preserved. Arrays.equals() can do the job.
You need to create array2 only after the loop. As your code stands, if no duplicates are detected, arrays2 is never created.
So your loop becomes:
for (int k = employee_t.length - 1; k >= 1; k--)
{
if (Arrays.equals(employee_t[k], employee_t[k - 1]))
{
System.out.println("same value is present");
l.remove(k);
}
}
array2 = l.toArray(new String[][]{});
This gives you the output you asked for.
Further tips:
Your comparator only compares one field in the inner arrays, which is not enough to guarantee that identical rows come right after each other in the sorted array. You should compare all elements, and also require that the inner arrays have the same length.
Use generics: class Sort extends Comparator<String[]>, and you won’t need the casts in compare()
According to Java naming conventions it should be class EmployeeDup, boolean doSwitch (since switch is a reserved word) and class Sort.
You are not using the variables Switch and rows; delete them.
I have wrote a solution for me. This may not be the best but it works.
public static String[][] removeDuplicate(String[][] matrix) {
String[][] newMatrix = new String[matrix.length][matrix[0].length];
int newMatrixRow = 1;
for (int i = 0; i < matrix[0].length; i++)
newMatrix[0][i] = matrix[0][i];
for (int j = 1; j < matrix.length; j++) {
List<Boolean> list = new ArrayList<>();
for (int i = 0; newMatrix[i][0] != null; i++) {
boolean same = true;
for (int col = 2; col < matrix[j].length; col++) {
if (!newMatrix[i][col].equals(matrix[j][col])) {
same = false;
break;
}
}
list.add(same);
}
if (!list.contains(true)) {
for (int i = 0; i < matrix[j].length; i++) {
newMatrix[newMatrixRow][i] = matrix[j][i];
}
newMatrixRow++;
}
}
int i;
for(i = 0; newMatrix[i][0] != null; i++);
String finalMatrix[][] = new String[i][newMatrix[0].length];
for (i = 0; i < finalMatrix.length; i++) {
for (int j = 0; j < finalMatrix[i].length; j++)
finalMatrix[i][j] = newMatrix[i][j];
}
return finalMatrix;
}
This method will return a matrix without any duplicate rows.

Label distinct values for Arraylist<String> with identifier

I have a simple problem. I have an ArrayList (of type String) with 100'000 Names. I want to create another ArrayList (of type Integer) which also has 100'000 Elements and assignes each Element of the String ArrayList an ID-Number. Equal Names should have equal ID Numbers assigned. VERY BASIC EXAMPLE:
i have: (hans, max, hans, hans, frank)
i want: ( 1 , 2 , 1 , 1 , 3 )
I implemented a Solution which works, but is very slow (for my big dataset of 100'000 Names). I wonder someone can find a better/faster way of doing this. Thanks everyone for any tipps!
public static void main(String[] args) {
// initialize arraylists
ArrayList<String> Names = new ArrayList<String>();
ArrayList<Integer> Id = new ArrayList<Integer>();
// sample data // I want the integer Arraylist to have values:
Names.add("Hans"); // 1
Names.add("Max"); // 2
Names.add("Hans"); // 1
Names.add("Hans"); // 1
Names.add("Frank"); // 3
// my solution (works, but is slow and confusing)
int N = Names.size();
int ID_Count = 0;
for (int i=0; i<N; i++) {
boolean match_found = false;
String curr_Name = Names.get(i);
for (int check=0; check<i; check++) {
if (curr_Name.equals(Names.get(check))) {
Id.add(Id.get(check));
match_found = true;
break;
}
}
if (match_found==false) {
ID_Count++;
Id.add(ID_Count);
}
}
// show result
for (int i=0; i<N; i++) {
System.out.println(Id.get(i) + " " + Names.get(i));
}
}
This is a faster way of doing it:
public static void main(String[] args) {
// initialize arraylists
ArrayList<String> Names = new ArrayList<String>();
Map<String,Integer> map = new HashMap<>();
// sample data // I want the integer Arraylist to have values:
Names.add("Hans"); // 1
Names.add("Max"); // 2
Names.add("Hans"); // 1
Names.add("Hans"); // 1
Names.add("Frank"); // 3
int N = Names.size();
int id = 0;
for (int i = 0; i < N; i++) {
String name = Names.get(i);
if (map.get(name) == null) {
map.put(name,++id);
}
}
// show result
for (int i=0; i<N; i++) {
String name = Names.get(i);
System.out.println(map.get(name) + " " +name);
}
}
If I understand your question correctly, you ought to use a HashMap, as it will be a lot faster/easier than working with two arrays. I would do it like this:
Map<String,Integer> map = new HashMap<>();
This way you will be able to do map.put("name", int id), and it won't allow duplicate keys (key is the "name" in your case) so you will automatically have only one key/value pair for names that are the same.

How do I check strings in a 2D array column?

I have a 2D array with a list of names and numbers. Column 1 contains all the names of people. How do I edit my function to take user input and check to see if the input matches or if the input is partially found inside one of the names in one of the string in the array?
Example:
Daniel Zen, 12, 3
Niel Diam, 15, 5
Arthur Ziel, 16, 99
My function currently takes the first column, the names, but how do I look threw each if they are matching? and how do I determine their row value.
Wanted output: (User input "IeL")
Daniel Zen is row 0
Niel... is row 1
Arth... is row 2
What I have so far takes the input, converts it to lower-case.
public static void print_player_info(String[][] data, String player)
{
String name = player.toLowerCase();
for(int i = 0; i<data[0].length; i++)
{
String namecolumn = data[i][0];
String rownames = data[0][i];
if(name.indexOf(namecolumn)!= -1)//i dont think this is correct
{
// what would need to go here
}
}
}
Something similar would do for you.. I have not tested this, have a check and let us know.
public static void print_player_info(String[][] data, String player) {
String name = player.toLowerCase();
for (int i = 0; i < data.length; i++) {
String temp = Arrays.toString(data[i]);
if(temp.toLowerCase().contains(player)){
System.out.println(player + " - " + i);
}
}
}
public static void print_player_info(String[][] data, String player) {
int i = 0;
for (String[] dd : data) {
for (String d : dd) {
if (d.toLowerCase().contains(player.toLowerCase())) {
System.out.println(d + " is row " + i);
}
}i++; }}

Disappearing Arraylist Values

I am writing a Java program that will take a sentence (or phrase) and translate it into a group of objects that the computer can easily read. I wanted to make a simple word separating program, and then extend it later on.
My code is like this:
package Literary;
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone){
ArrayList<String> temptwo = new ArrayList();
ArrayList<Character> tempthree = new ArrayList();
for (int tempfour = 0; tempfour == tempone.length() - 1; tempfour++){
if (tempone.charAt(tempfour) != ' '){
tempthree.add(tempone.charAt(tempfour));
} else {
temptwo.add(getStringRepresentation(tempthree));
tempthree.clear();
}
}
String[] tempfive = new String[temptwo.size()];
for (int tempfour = 0; tempfour == tempfive.length - 1; tempfour++){
tempfive[tempfour] = temptwo.get(tempfour);
}
return tempfive;
}
/** Courtesy of Vineet Reynolds on StackExchange.
*
* "You can iterate through the list and create the string."
*
* #param list
* #return
*/
public static String getStringRepresentation(ArrayList<Character> list){
StringBuilder builder = new StringBuilder(list.size());
for(int i = 0; i == list.size() + 1; i++)
{
builder.append(list.get(i).charValue());
}
return builder.toString();
}
}
It's supposed to receive a string as an input, and return a list of strings that have been separated by spaces.
But when I run my main class:
import Literary.WordParser;
public class Start {
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i == tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i]);
}
}
}
The console tells me nothing except run: and BUILD SUCCESSFUL (total time: 1 second).
I'm using Netbeans 8 and Java 1.7 if that helps.
Looks like the problem's here:
for (int i = 1; i == tempstring.length; i++) {
This for loop will run at most once: if tempstring is exactly one String long, it should print out the word.
However, since your test sentence has 8 words, nothing will ever print out (provided WordParser works correctly).
You probably want to change this line to: (note the < between i and tempstring.length.)
for (int i = 1; i < tempstring.length; i++) {
so that it will loop through all the items in tempstring.
You had multiple issues in your code:
1) for loops were not properly made, they would never execute. Use either !=, > or < instead of ==.
2) you don't need a method getWords() nor getStringRepresentation(). Method like that are already implemented in Java.
So the final code should be this:
public class WordParser {
public static String[] getWords(String tempone) {
return tempone.split(" ");
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Output:
Word 1 : There
Word 2 : was
Word 3 : once
Word 4 : a
Word 5 : sword
Word 6 : in
Word 7 : the
Word 8 : stone
I've also fixed your code that runs the same as above, if you are interested:
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone) {
ArrayList<String> sarr = new ArrayList<String>();
ArrayList<Character> tempthree = new ArrayList<Character>();
String[] ansarr;
if(tempone.charAt(tempone.length()-1) != ' ')
tempone += " "; //Add white space to the end to catch the last word
for (int i = 0; i < tempone.length(); i++) {
if (tempone.charAt(i) != ' ') {
tempthree.add(tempone.charAt(i));
} else {
sarr.add(tempthree.toString());
tempthree.clear();
}
}
ansarr = new String[sarr.size()];
for (int i = 0; i < ansarr.length; i++) {
ansarr[i] = sarr.get(i);
}
return ansarr;
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Enjoy! :)
I think you should use String.split(" ") which seems to do the same thing
Change your main method as follows,
and it will work
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i <= tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i - 1]);
}
}
For the WordParser you could use,
public class WordParser
{
public static String[] getWords(String tempone)
{
return tempone.split(" ");
}
}
First of, I would recommend using the split method to break up a sentence
it is defined as:
public String[] split(String regex, int limit)
and you can simply call
String s1=new String("Random words in a sentence");
String[] words=s1.split(" ");
in order to break the string up into words and you will now have a String
array of five elements where each element consists of a word
In Respect to your question, you are not using the conditional statement correctly
You want to iterate over the elements of the String array WHILE the position
is less than stringname.length, not only if it the position equals the stringname.length
Therefore, you must make the following changes in these parts of your code
For Example:
for (int i = 1; i == tempstring.length; i++)
should have its line changed to
for (int i = 1; i < tempstring.length; i++)
and this problem also occurs in various places in your WordParser.java file
It is useful to remember also that you may often want to start at index 0 instead
of index 1, as java has its' first indice as 0.

Categories