public class Main {
public static void main(String[] args) {
String a = new String("Wow");
String b = a;
String c = new String("WoW");
String d = new String("WoW");
boolean b1 = a == b;
boolean b2 = d.equals(b + "!");
boolean b3 = !c.equals(a);
if (b1 && b2 && b3) {
System.out.println("Success!");
}
}
}
For the above code, when can boolean b2 = d.equals(b + "!"); be true. Pease help me with the changes to be made to Strings a, b, c or d(I should only change the first section of the code)
By initializing, String d = b + "!"; could print success. Worked for me.
Related
Is it possible to import excel as a guava table object where the excel sheet contains more than 3 columns?
Getting confused on this as most code samples talk about only 3 columns in sheet as seen in below link too
https://www.geeksforgeeks.org/table-guava-java/
You misinterpret the Table<R,C,V>. This are not three columns but Rrow, Column and Value.
A Excel table would be a Table<String, String, Object> where row keys are R1, R2, R3, .. and the column keys are C1, C2, C3, ... The objects are the cell values.
When we get each cell content as String, then a Excel table would be:
Table<String, String, String> excelTable = HashBasedTable.create();
and a cell content would be put there like:
excelTable.put("R" + r, "C" + c, value);
Given an Excel sheet like:
The following code gets all it's content to a Guava Table.
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.util.Map;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
class ReadExcelToGuavaTable {
public static void main(String[] args) throws Exception {
Table<String, String, String> excelTable = HashBasedTable.create();
Workbook workbook = WorkbookFactory.create(new FileInputStream("Excel.xlsx"));
DataFormatter dataFormatter = new DataFormatter(java.util.Locale.US);
FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
Sheet sheet = workbook.getSheetAt(0);
int r = 1;
int c = 1;
for (Row row : sheet) {
r = row.getRowNum() + 1;
for (Cell cell : row) {
c = cell.getColumnIndex() + 1;
String value = dataFormatter.formatCellValue(cell, formulaEvaluator);
//System.out.println("R" + r + "C" + c + " = " + value);
excelTable.put("R" + r, "C" + c, value);
}
}
// get Map corresponding to row 1 in Excel
Map<String, String> rowMap = excelTable.row("R1");
System.out.println("List of row 1 content : ");
for (Map.Entry<String, String> row : rowMap.entrySet()) {
System.out.println("Column : " + row.getKey() + ", Value : " + row.getValue());
}
// get a Map corresponding to column 4 in Excel
Map<String, String> columnMap = excelTable.column("C4");
System.out.println("List of column 4 content : ");
for (Map.Entry<String, String> column : columnMap.entrySet()) {
System.out.println("Row : " + column.getKey() + ", Value : " + column.getValue());
}
// get single cell content R5C5
System.out.println("Single cell content R5C5 :");
System.out.println("R5C5 : " + excelTable.get("R5", "C5"));
// get all rows and columns
Map<String,Map<String,String>> allMap = excelTable.rowMap();
System.out.println("List of whole table : ");
for (Map.Entry<String, Map<String, String>> row : allMap.entrySet()) {
Map<String, String> colMap = row.getValue();
for (Map.Entry<String, String> column : colMap.entrySet()) {
System.out.println(row.getKey() + column.getKey() + " = " + column.getValue());
}
}
workbook.close();
}
}
I have the three methods that take the longest and then my run() method; the rest of the code takes a negligible amount of time. I'm just confused as to why it would run instantly in Eclipse but not be able to do the same when I run it from a .jar file.
It is around 120x slower when run from the .jar file. Is it my code or is there something else going on here?
public void modifyCell(String input, int rowNum, int column, Workbook wb) throws IOException {
Sheet sheet = wb.getSheet("Sheet1");
Row row = sheet.getRow(rowNum);
Cell cell = row.getCell(column);
cell = row.createCell(column);
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
cell.setCellStyle(cellStyle);
cell.setCellValue(input);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
cell = row.getCell(column+1);
evaluator.evaluateFormulaCell(cell);
row = sheet.getRow(3);
cell = row.getCell(getFinalFormula(site));
evaluator.evaluateFormulaCell(cell);
evaluateTopFormulas(wb);
FileOutputStream fileOut = new FileOutputStream(workbook);
wb.write(fileOut);
fileOut.close();
}
public void evaluateTopFormulas(Workbook wb){
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
Sheet sheet = wb.getSheet("Sheet1");
Row row = sheet.getRow(1);
Cell cell = row.getCell(6);
evaluator.evaluateFormulaCell(cell);
row = sheet.getRow(2);
cell = row.getCell(6);
evaluator.evaluateFormulaCell(cell);
}
public int getRow(Workbook wb, int column){ // i also think this part is very poorly written
but I don't know how to go about it differently.
All I want is to get the next blank cell in a column after the 4th cell.
long startTime = System.nanoTime();
Sheet sheet1 = wb.getSheetAt(0);
int i = 4;
Row startRow = sheet1.getRow(i);
Cell cell = startRow.getCell(column);
Row row;
try {
while (!(cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK)){
row = sheet1.getRow(i++);
cell = row.getCell(column);
}
} catch (Exception e){
}
if (i == 4){
return i;
}
long estimatedTime = System.nanoTime() - startTime;
System.out.println(estimatedTime + " getRow");
return i-1;
}
public void run(){
try {
System.out.println("Adding to Invoice");
Workbook wb = openWorkbook();
int column = getColumn(site);
int row = getRow(wb, column);
modifyCell(input, row, column, wb);
System.out.println(input + " was added to " + workbook);
} catch (InvalidFormatException | IOException e) {
System.out.println(e);
}
}
I am using the Java jxl api v2.6.16 to generate Excel Spread Sheet. Like the above title puts it, how do get an address of a Cell or More specifically Writable cell that I am writing to if all I have is the cell's column and row? Or do I have to write an algorithm which can generate that?
Thanks in advance.
You can use this code. Hope this help. You can use it in this way:
cellAddress(cell.getRow() + 1, cell.getColumn()) if cell is defined like Cell cell = someCell;
private String cellAddress(Integer rowNumber, Integer colNumber){
return "$"+columnName(colNumber)+"$"+rowNumber;
}
private String columName(Integer colNumber) {
Base columns = new Base(colNumber,26);
columns.transform();
return columns.getResult();
}
class Base {
String[] colNames = "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".split(",");
String equalTo;
int position;
int number;
int base;
int[] digits;
int[] auxiliar;
public Base(int n, int b) {
position = 0;
equalTo = "";
base = b;
number = n;
digits = new int[1];
}
public void transform() {
if (number < base) {
digits[position] = number;
size();
} else {
digits[position] = number % base;
size();
position++;
number = number / base;
transform();
}
}
public String getResult() {
for (int j = digits.length - 2; j >= 0; j--) {
equalTo += colNames[j>0?digits[j]-1:digits[j]];
}
return equalTo;
}
private void size() {
auxiliar = digits;
digits = new int[auxiliar.length + 1];
System.arraycopy(auxiliar, 0, digits, 0, auxiliar.length);
}
}
the Address is made up of the Column and Row.
In A1 Notation it is written like: Range("A1") where the column 1 is rtepresented by the letter "A" and the row is 1
In R1C1 Notation it would be written like this: R1C1 where the column is 1 and the row is 1
They would be used like this:
Cells(1,1).font.bold=true ' row 1, column 1
range("A1").font.bold=true
to get the address from a Reference, retrieve the Address property of the Cells or Range object as below:
sAddress=cells(1,1).address
which would return A$1$
and in JXL, String rangeAddress = range.getAddress();
You can get the column by it's alpha index by using one of the methods below. he simple method just casts an integer to a ASCII character. The second method allows the use of a custom alphabet.
Simple Method
public class LookupUtil {
public static String cellAddress(int row, int col) {
return String.format("$%s$%d", columnName(col), row);
}
public static String columnName(int index) {
int div = index + 1;
StringBuffer result = new StringBuffer();
int mod = 0;
while (div > 0) {
mod = (div - 1) % 26;
result.insert(0, (char) (65 + mod));
div = (int) ((div - mod) / 26);
}
return result.toString();
}
}
Advanced Method
public class LookupUtil {
private static final char[] ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static String cellAddress(int row, int col) {
return String.format("$%s$%d", columnName(col, ALPHA), row);
}
public static String columnName(int index, char[] alphabet) {
int div = index + 1;
StringBuffer result = new StringBuffer();
int mod = 0;
while (div > 0) {
mod = (div - 1) % alphabet.length;
result.insert(0, alphabet[mod]);
div = (int) ((div - mod) / alphabet.length);
}
return result.toString();
}
}
public int MainOperationSimplifeid(char operatoru)
{
if (beforeoperation == 2)
{
a2 = Convert.ToInt32(textBox1.Text);
textBox1.Text = "";
result = a1 operatoru a2;
// textBox1.Text = Convert.ToString(result);
a1 = 0;
a2 = 0;
}
beforeoperation++;
return result;
}
a1, a2 - represents two numbers in the program and result is the answer for the >operation peformed
i am thinking of using one single character or some other like argument that reduce all my operators used else where in the program
but i cant get the +, * as replace to a char between two integers. :(
Can you guys please help which inbult function or argument can replace all my operator to a single variable , so that i can pass that as my argument.
Thanks for going through my question :)
This sort of thing can be done with delegates. The built in delegate type Func<T1, T2, T3> represents code that accepts two parameters and returns a result.
public int MainOperationSimplifeid(Func<int, int, int> operatoru)
{
if (beforeoperation == 2)
{
a2 = Convert.ToInt32(textBox1.Text);
textBox1.Text = "";
result = operatoru(a1, a2);
// textBox1.Text = Convert.ToString(result);
a1 = 0;
a2 = 0;
}
beforeoperation++;
return result;
}
Then you can call the method with a lambda:
var addResult = MakeOperationSimplifeid((x, y) => x + y);
var multResult = MakeOperationSimplifeid((x, y) => x * y);
I think you can't make that, because the compiler needs the operator to compile the program. So, as I can see, the solution could be a enum, Something Like this:
Enum Operator {
Addition, Substraction, Multiplication, Division
};
public double MainOperationSimplified(Operator operatoru)
{
if (beforeoperation == 2)
{
a2 = Convert.ToInt32(textBox1.Text);
textBox1.Text = "";
switch (operatoru) {
case Addition:
result = a1 + a2;
break;
case Substraction:
result = a1 - a2;
break;
case Multiplication:
result = a1 * a2;
break;
case Division:
result = a1 / a2;
break;
default:
result = 0;
break;
}
a1 = 0;
a2 = 0;
}
beforeoperation++;
return result;
}
I have an object whose class has a getter method , and this getter method returns a Date value. I want to show this value in a Label in the format DD/MM/YYYY.
How to achieve that with LWUIT ?
Thank you very much indeed
You can use this code to convert date to string format and pass the this string value to label.
public static String dateToString (long date)
{
Calendar c = Calendar.getInstance();
c.setTime(new Date(date));
int y = c.get(Calendar.YEAR);
int m = c.get(Calendar.MONTH) + 1;
int d = c.get(Calendar.DATE);
String t = (d<10? "0": "")+d+"/"+(m<10? "0": "")+m+"/"+(y<10? "0": "")+y;
return t;
}
To thank you here is a code of mine which formats a number :
public static String formatNombre(int trivialNombre, String separateur)
{
String pNombre, sNombreLeads, sNombre, argNombre, resultat;
int leadingBits;
int nbBit;
pNombre = String.valueOf(trivialNombre);
if (pNombre.length() > 3)
{
leadingBits = (pNombre.length())%3;
if (leadingBits != 0)
sNombreLeads = pNombre.substring(0, leadingBits).concat(separateur);
else
sNombreLeads = "";
nbBit = 0;
sNombre = "";
argNombre = pNombre.substring(leadingBits);
for (int i=0;i<argNombre.length();i++)
{
sNombre = sNombre.concat(String.valueOf(argNombre.charAt(i)));
nbBit++;
if (nbBit%3 == 0)
sNombre = sNombre.concat(separateur);
}
sNombre = sNombre.substring(0, sNombre.length() - 1);
resultat = sNombreLeads.concat(sNombre);
return resultat;
}
else
return pNombre;
}