Print ArrayList like Excel spreadsheet [duplicate] - java

This question already has answers here:
How to print a table of information in Java
(6 answers)
Closed 2 years ago.
Is there a way to print an ArrayList like a Excel spreadsheet ?
My code is this:
private static void printList() {
for (int i = 0; i < matrizCuadrada.size(); i++) {
System.out.print(fillWithSpaces(matrizCuadrada.get(i).getValor()));;
}
}
private static String fillWithSpaces(String cadena) {
int cantidadEspacios = 9 - cadena.length();
for (int i = 0; i < cantidadEspacios; i++) {
cadena += " ";
}
return cadena;
}

To print a one-dimensional data structure like ArrayList in two dimensions you are going to have to set a fixed line size. This is actually a very similar problem as loading pixels stored in linearly stacked memory to a two-dimensional image. Check the linked article for more details about this problem.
You need nested loops to achieve this behaviour, which you already have (fillWithSpaces() (containing a loop) is called from inside another loop). So, change fillWithSpaces() to something like this:
private static String fillWithSpaces(String cadena) {
String line = "";
for (int i = 0; i < cadena.length(); i++) {
line += cadena.charAt(i);
line += " ";
}
return line;
}
This code can also be simplified using a utility called StringJoiner to join strings and characters with a delimiter:
private static String fillWithSpaces(String cadena) {
StringJoiner joiner = new StringJoiner(" ");
for (int i = 0; i < cadena.length(); i++) {
joiner.add(cadena.charAt(i));
}
return joiner.toString();
}
Also, you need to jump to a new line at the end of the outer loop. This can be done by changing System.out.print() to System.out.println(), which will automatically output a new line.
Check this article by Daniel Shiffman for an extensive explanation of the same problem in a different context (under Pixels, pixels, and more pixels): https://processing.org/tutorials/pixels/

Related

Making java output a specific number of characters, depending on the input in the console

I need to write a program that let's the user write 3 words in the console, then the program reprints those 3 words (one in each line) but also fills out the remaining spaces in each line with dots (".") so the total number of characters in each lines becomes a total of 30 characters.
Example:
Input:
Hello
Me
Overflow
Output:
.........................Hello
............................Me
......................Overflow
This is the code that I currently have which generates an error. I have been given the code (at the bottom) as part of my assignment and need to write the repeatChar method to make it work.
The first thing I did was to add the following commands in the code, in order to save the 3 words into the array threeWord.
threeWord[1] = wordOne;
threeWord[2] = wordTwo;
threeWord[3] = wordThree;
Next, I had to write the method repeatChar, and I decided to use a for-loop to make it repeat dots for each individual line, but I'm having a hard time making it fit with the rest of the code. Any guidance would be much appreciated, thanks.
import java.util.*;
public class FillDots {
private static int LineLength = 30;
public static void main(String[] arg) {
String[] threeWord = new String [3]; // Defines 3 locations to place strings in the array "threeWord"
Scanner console = new Scanner(System.in);
System.out.println("Type in three words:");
String wordOne = console.next();
threeWord[1] = wordOne; // Saves first word to array "threeWord"
String wordTwo = console.next();
threeWord[2] = wordTwo; // Saves second word to array "threeWord"
String wordThree = console.next();
threeWord[3] = wordThree; // Saves third word to array "threeWord"
for(int i = 0; i < threeWord.length; i++) {
System.out.println(repeatChar('.', LineLength - threeWord[i].length()) + threeWord[i]);
}
}
public static String repeatChar(String LineLength) {
for(int j = 0; j < LineLength; j++) {
System.out.print(".");
}
}
}
Besides the index starts from 0, you need return the dots in the repeatChar method:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
You can use existing library for doing padding
for(String temp:threeWord)
system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") );
this might simplify your code

how to split an arraylist of String whenever a space is encountered in java?

I have an input like this in an ArrayList<String>:
cat eats mouse
mouse eats cheese
cheese is tasty
(blank lines should be ignored since I will be reading this input from a file)
and I want to convert it into a 2-d array of String which will have dimensions [no. of elements in ArrayList][3].
The no. 3 is fixed i.e. each sentence will have 3 words.
like this:
"cat" "eats" "mouse"
"mouse" "eats" "cheese"
"cheese" "is" "tasty"
here's what I have tried:
public static int processData(ArrayList<String> array)
{
String str[]=new String[array.size()];
array.toArray(str);
String str1[][]=new String[str.length][5];
for(int i=0;i<str.length;i++)
{
str1[i][]=str.split("\\s+"); //i want to do something like this, but this is showing errors.
}
return 0; //this is temporary, I will be modifying it
}
Tell me if I am not clear.
You are close. In Java, you can't put new elements at the end of an array by using empty brackets []. The following code does the thing. Note that number of elements in the second array is limited by 5. So, after the first 5 words, the rest of the line will be ignored. If the line is shorter, there will be nulls in the end of the array.
public static int processData(ArrayList<String> array) {
String[] str = new String[array.size()];
array.toArray(str);
String[][] str1 = new String[str.length][3];
for(int i=0; i < str.length; i++) {
String[] parts = str[i].split("\\s+");
for(int j = 0; j < parts.length || j < 3; j++) {
str1[i][j] = parts[j];
}
}
// do something next
}
A shorter, and slightelly more efficient version:
static int processData(ArrayList<String> array)
{
String str[][] = new String[array.size()][3];
for(int i = 0; i < str.length; ++i) {
str[i] = array.get(i).split("\\s+");
}
return 0;
}
There is no reasion for the first array called str in your code, since you cann access the Strings directly from the ArrayList.
Also you can don't have to copy the Strings, you can just put the arrays of Strings into the array of arrays, like in my code
Plus, if you have a fixed size of 3, and don't need to add any more to the arrays, why do you allocate space for 5 strings?
As you mentioned "arraylist" in Subject:
try{
BufferedReader br = new BufferedReader(new FileReader("filename"));
Arraylist<String[]> l = new ArrayList<String[]>();
String line;
while((line = br.readline) != null)
l.add(line.split("\\s+");
br.close();
}catch(Exception e){e.printStackTrace();}
Change your for loop to:
String str1[][] = new String[str.length][3];
for(int i = 0; i < str.length; i++) {
str1[i] = str[i].split("\\s+");
}
You don't need to have 5 elements if you know that you have only 3 words, do not waste your resources.
str is a String[], str[i] is a String, str[i].split() is a String[] and so is str1[i]. The types match.
Also, this way the code is clearer and easier to understand. I agree with Ongy to remove str if you do not need it, but I can't tell now because you said you are going to change this method later (at least the return value)
Bonus: Btw, the names array, str, str1 are not the best choice for that piece of code, it is really easy to be confused what is what. Try finding better name such as lines, linesArray, words or something like that

How to print a specific amount of strings such as "_"? [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 9 years ago.
I need to print a specific set of lines without manually typing them.
I want my output to be like this
"|Word_________|"
Is there a code which allows me to set my own amount of "_"?
One may use a format, which then padds (left or right) with spaces.
System.out.printf("|%-30s|%5s|%n", "Aa", "1");
System.out.printf("|%-30s|%5s|%n", "Bbbb", "222");
String s = String.format("|%-30s|%5s|%n", "Aa", "1").replace(' ', '_');
String fortyBlanks = String.format("%40s", "");
You can print a _ with:
System.out.print("_");
If you want more, do it multiple times (inefficient), or build up a string containing multiple and print it. You may want to look at StringBuilder.
No direct way. But with looping you can do
String s = "";
for (int i = 0; i < 10; i++) { // sample 10
s = s + "_";
}
System.out.println(s);
Still it is not a bestway to use + in looping. Best way is
StringBuilder b = new StringBuilder();
for (int i = 0; i < 10; i++) { //sample 10
b.append("_");
}
System.out.println(b.toString());
Use a for loop.
Here's the link to the java documnentation for a for loop: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
int amountOf_ = 10;
System.out.println("|" + StringUtils.rightPad("Word", amountOf_, "_") + "|");
}
}

Compare the index of 2 String arrays with different values Java

I have 2 parallel arrays: the first contains State Names, the second Capitals of the states.
I'm making a quiz that randomly generates a State then asks the user to enter the Capital of the state. Once the input is received I want to call a method to check if the index of the capital entered is the same as the index of the state it goes with.
ie: stateArray[0] = "New York" and capitalArray[0] = "Albany".
Check Answer Method
public static void checkAnswer(String[]stateArray, String capitalArray, String answer)
{
int index;
for (int i = 0; i < capitalArray.length; i++){
if(capitalArray[i].equalsIgnoreCase(answer)){
index = i;
}
}
if(capitalArray[index] == stateArray[index])
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
I know the second if statement is wrong. How can I compare the two arrays using the index where the users answer was found in the capitalArray?
boolean checkAnswer(String[] stateArray, String[] capitalArray, String displayedState, String answer) {
for (int i = 0; i < stateArray.length; i++) {
if (stateArray[i].equals(displayedState) && capitalArray[i].equals(answer)) {
return true;
}
}
return false;
}
Or something. The key is you need to pass in something to represent the state you displayed.
You need to keep track of the index that holds the State displayed to the user. For example, the way your code is written now gives the user the ability to get a right answer by giving a wrong answer. Take this example as explanation:
string[] stateArray = {"New York", "California"};
string[] capitalArray = {"Albany", "Sacramento"};
If you were to show "New York" as the question and the user happens to answer "Sacramento" your code would display correct.
You also need a case in which the answer does not match any of the capitals in the array. One way of doing this to implement in your code is to initiate the index to -1.
int index = -1;
Once you finish the for loop check if index is -1 and display "Your answers is not a valid State" or something along those lines.
Maybe use a HashMap, I am not completely familiar with Java it appears to be the similar to a Dictionary in Python. Dictionary object has great performance.
Since you know what state you asked about you should know its array index as well. As you see below both arrays are declared as class variables.
... class Quiz {
private String[] states = new String[50];
private String[] capitals = new String[50];
... method to fill both arrays with the correct data
public static void checkAnswer(int question, String answer)
{
if(capitalArray[question].equalsIgnoreCase(answer)){
{
System.out.println("correct");
}
else
{
System.out.println("incorrect");
}
}
}
It's better to have checkAnswer method's return type as Boolean, but I left it your way.
An alternate implementation in Java would be to use a Map instead of two arrays.
Map<String,String> stateCapitals = new HashMap<String,String>();
stateCaptitals.put("New York", "Albany");
then you can check the map with
public voic checkAnswer(String chosenState, String chosenCapital) {
if (stateCapitals.get(chosenState).equals(chosenCapital) {
System.out.println("you are correct!");
}
}
This does not do it with 2 parallel arrays, but it is a better implementation if your real concern is the type of data you mentioned, and not the arrays themselves.
Try this function it return array:-
public static String[] numSame (String[] list1, String[] list2)
{
int same = 0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
same++;
break;
}
}
}
String [] array=new String[same];
int p=0;
for (int i = 0; i <= list1.length-1; i++)
{
for(int j = 0; j <= list2.length-1; j++)
{
if (list1[i].equals(list2[j]))
{
array[p]= list1[i]+"";
System.out.println("array[p] => "+array[p]);
p++;
break;
}
}
}
return array;
}

Java String Array Mergesort

Hi all I wrote a mergesort program for a string array that reads in .txt files from the user. But what I want to do now is compare both files and print out the words in file one and not in file two for example apple is in file 1 but not file 2. I tried storing it in a string array again and then printing that out at the end but I just cant seem to implement it.
Here is what I have,
FileIO reader = new FileIO();
String words[] = reader.load("C:\\list1.txt");
String list[] = reader.load("C:\\list2.txt");
mergeSort(words);
mergeSort(list);
String x = null ;
for(int i = 0; i<words.length; i++)
{
for(int j = 0; j<list.length; j++)
{
if(!words[i].equals(list[j]))
{
x = words[i];
}
}
}
System.out.println(x);
Any help or suggestions would be appriciated!
If you want to check the words that are in the first array but do not exist in the second, you can do like this:
boolean notEqual = true;
for(int i = 0; i<words.length; i++)
{
for(int j = 0; j<list.length && notEqual; j++)
{
if(words[i].equals(list[j])) // If the word of file one exist
{ // file two we set notEqual to false
notEqual = false; // and we terminate the inner cycle
}
}
if(notEqual) // If the notEqual remained true
System.out.println(words[i]); // we print the the element of file one
// that do not exist in the second file
notEqual = true; // set variable to true to be used check
} // the other words of file one.
Basically, you take a word from the first file (string from the array) and check if there is a word in file two that is equal. If you find it, you set the control variable notEqual to false, thus getting out of the inner loop for and not print the word. Otherwise, if there is not any word on file two that match the word from file one, the control variable notEqual will be true. Hence, print the element outside the inner loop for.
You can replace the printing statement, for another one that store the unique word in an extra array, if you wish.
Another solution, although slower that the first one:
List <String> file1Words = Arrays.asList(words);
List <String> file2Words = Arrays.asList(list);
for(String s : file1Words)
if(!file2Words.contains(s))
System.out.println(s);
You convert your arrays to a List using the method Arrays.asList, and use the method contains to verify if the word of the first file is on the second file.
Why not just convert the Arrays to Sets? Then you can simply do
result = wordsSet.removeAll(listSet);
your result will contain all the words that do not exist in list2.txt
Also keep in mind that the set will remove duplicates ;)
you can also just go through the loop and add it when you reached list.length-1.
and if it matches you can break the whole stuff
FileIO reader = new FileIO();
String words[] = reader.load("C:\\list1.txt");
String list[] = reader.load("C:\\list2.txt");
mergeSort(words);
mergeSort(list);
//never ever null
String x = "" ;
for(int i = 0; i<words.length; i++)
{
for(int j = 0; j<list.length; j++)
{
if(words[i].equals(list[j]))
break;
if(j == list.length-1)
x += words[i] + " ";
}
}
System.out.println(x);
Here is a version (though it does not use sorting)
String[] file1 = {"word1", "word2", "word3", "word4"};
String[] file2 = {"word2", "word3"};
List<String> l1 = new ArrayList(Arrays.asList(file1));
List<String> l2 = Arrays.asList(file2);
l1.removeAll(l2);
System.out.println("Not in file2 " + l1);
it prints
Not in file2 [word1, word4]
This looks kind of close. What you're doing is for every string in words, you're comparing it to every word in list, so if you have even one string in list that's not in words, x is getting set.
What I'd suggest is changing if(!words[i].equals(list[j])) to if(words[i].equals(list[j])). So now you know that the string in words appears in list, so you don't need to display it. if you completely cycle through list without seeing the word, then you know you need to explain it. So something like this:
for(int i = 0; i<words.length; i++)
{
boolean wordFoundInList = false;
for(int j = 0; j<list.length; j++)
{
if(words[i].equals(list[j]))
{
wordFoundInList = true;
break;
}
}
if (!wordFoundInList) {
System.out.println(x);
}
}

Categories

Resources