Creating an object class with elements of varying but set length - java

I want to create an object (Wine) that contains a set of data where each data element is a different size (year, region, maker, variety, etc.). I want to be able to print these out in a tabular format using the set length of each element. I've searched and tried lots of ways but can't find the answer.
my class definition looks like this:
public class Wine {
char[] year;
char[] area; // Wine area
char[] brand; // Wine brand
char type; // R or W or F
char[] variety;
char bin;
int numbottles;
I can read data in from a txt file but the elements are shortened to the text content plus a space so the tabulation is lost.
I've tried this in my main section without success:
wine.year = rightpad(tokens[0].toCharArray(), 5) ;
wine.area = rightpad(tokens[1].toCharArray(), 9);
....
static char[] rightpad(char[] text, int leng) {
for(int i = text.length - 1; i < leng; i++){
text = (new String(text) + ' ').toCharArray();
}
return text;
}
Any suggestions would be greatly appreciated.
Chris A

You can use String.format
String.format("%-8s", "test") // "test "
You set the length of the String and use a negative value to add the space to the right (without the minus, to the left)
Complete information about the format are available in Formatter - Format String Syntax

Use org.apache.commons.lang.StringUtils Apache Commons Lang
StringUtils.leftPad("text", 7) // return " text"

Here is my parse routine which reads through the String line and pulls out each Object element then adds them to the Object at the end:
static List<Wine> parseLine(String line, List<Wine> wineInfo) {
String year = null;
String area = null;
String brand = null;
String type = null;
String variety = null;
String bin = null;
String numbottles = null;
String drinkyear = null;
String cost = null;
Wine wine = new Wine(year, area, brand, type, variety, bin,
numbottles, drinkyear, cost);
int length = line.length();
int j = 0;
char yr[] = new char[3];
for (int i = 0; i < 3; i++) {
yr[j] = line.charAt(i);
year = new String(yr);
j = j + 1;
}
char temp[] = new char[7];
j = 0;
for (int i = 3; i < 10; i++) {
temp[j] = line.charAt(i);
area = new String(temp);
j = j + 1;
}
char temp1[] = new char[12];
j = 0;
for (int i = 10; i < 22; i++) {
temp1[j] = line.charAt(i);
brand = new String(temp1);
j = j + 1;
}
char temp3[] = new char[2];
j = 0;
for (int i = 22; i < 24; i++) {
temp3[j] = line.charAt(i);
type = new String(temp3);
j = j + 1;
}
char temp2[] = new char[21];
j = 0;
for (int i = 24; i < 45; i++) {
temp2[j] = line.charAt(i);
variety = new String(temp2);
j = j + 1;
}
char tmp[] = new char[6];
j = 0;
for (int i = 45; i < 51; i++) {
tmp[j] = line.charAt(i);
bin = new String(tmp);
j = j + 1;
}
char temp4[] = new char[3];
j = 0;
for (int i = 51; i < 54; i++) {
temp4[j] = line.charAt(i);
numbottles = new String(temp4);
j = j + 1;
}
char temp5[] = new char[4];
j = 0;
for (int i = 54; i < 58; i++) {
temp5[j] = line.charAt(i);
drinkyear = new String(temp5);
j = j + 1;
}
char temp6[] = new char[7];
j = 0;
for (int i = 58; i < length; i++) {
temp6[j] = line.charAt(i);
cost = new String(temp6);
j = j + 1;
}
wine.setYear(year);
wine.setArea(area);
wine.setBrand(brand);
wine.setType(type);
wine.setVariety(variety);
wine.setBin(bin);
wine.setNumbottles(numbottles);
wine.setDrinkYear(drinkyear);
wine.setCost(cost);
wineInfo.add(new Wine(year, area, brand, type, variety, bin,
numbottles, drinkyear, cost));
return wineInfo;
}
}
I then used a collections Comparator method to sort:
List<Wine> wineByYear = new ArrayList<Wine>(wineInfo);
Collections.sort(wineByYear, Wine.YearComparator);

Related

efficient way to do nested for loop and add to list

Below I have written some code that works and prints the right result, but is there a much more efficient way to do this using nested for loops, instead of having 5 different for loops?
String A = "";
String B = "";
String C = "";
String D = "";
String E = "";
ArrayList<String> id = new ArrayList<String>();
int row = 5;
for (int i=0; i < row; i++) {
A = "id0"+i;
id.add(A);
}
for (int i=0; i < row; i++) {
B = "id1"+i;
id.add(B);
}
for (int i=0; i < row; i++) {
C = "id2"+i;
id.add(C);
}
for (int i=0; i < row; i++) {
D = "id3"+i;
id.add(D);
}
for (int i=0; i < row; i++) {
E = "id4"+i;
id.add(E);
}
return id;
result
[id00, id01, id02, id03, id04, id10, id11, id12, id13, id14, id20, id21, id22, id23, id24, id30, id31, id32, id33, id34, id40, id41, id42, id43, id44]
The following should produce the same output by using a nested loop
ArrayList<String> id = new ArrayList<>();
int row = 5;
for (int i = 0; i < row; i++) {
for (int j = 0; j < row; j++) {
id.add("id" + i + j);
}
}
return id;
Consider the following:
ArrayList<String> id = new ArrayList<String>();
int row=5;
for (int i=0; i < 5; i++) {
for (int j=0; j < row; j++) {
String temp = "id" + i + j;
id.add(temp);
}
}
This simplifies the code into 2 nested for loops, with a single string variable instead of 5. This also shouldn't change the time complexity of your solution since the outer loop is constant.

Matrix Multiplication Returing Array Index out of bound error

This is one first post here, Pardon me if my question doesn't meet required standards here.
I have written a piece of code which takes input for two matrix from two separate files and performs multiplication and output the data to a new file.
It gives perfect output for 2x3 or 3x3 matrix. If i give input of 4x4 matrix i get array index out of bound runtime exception. I don't understand the reason as i dynamically create index
I get an array index out of bound exception at line 40.
I get an error.
![Snipet][2]
List item
public class MM {
private BufferedReader br;
private int sum = 0;
private final static String matrixA="matrixA.txt";
private final static String matrixB="matrixB.txt";
public static void main(String[] args) {
new MM().MathMultiplicationValues(matrixA, matrixB);
}
private void MathMultiplicationValues(String mat1, String mat2) {
try {
br = new BufferedReader(new FileReader(mat1));
String line;
int mat1rows = 0, mat1cols = 0, mat2rows = 0, mat2cols = 0;
while ((line = br.readLine()) != null) {
mat1cols = line.split(" ").length + 1;
mat1rows++;
}
br.close(); // To close file
br = new BufferedReader(new FileReader(mat2)); // to read input from file.
while ((line = br.readLine()) != null) {
mat2cols = line.split(" ").length + 1;
mat2rows++;
}
int[][] mat1vals = new int[mat1rows ][mat1cols ];
int[][] mat2vals = new int[mat2rows ][mat2cols ];
br.close();
br = new BufferedReader(new FileReader(mat1));
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
br = new BufferedReader(new FileReader(mat2));
for (int i = 1; i < mat2rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat2cols; j++) {
mat2vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
br.close();
if ((mat1cols-1) == mat2rows) {
int[][] resltmat = new int[mat1rows + 1][mat2cols + 1];
for (int i = 1; i < mat1rows + 1; i++) { //Loop does matrix multiplication.
for (int j = 1; j < mat1cols; j++) {
for (int k = 0; k < mat2rows + 1; k++)
sum = sum + mat1vals[i][k] * mat2vals[k][j];
resltmat[i][j] = sum;
sum = 0;
}
}
final PrintWriter pw = new PrintWriter("Answer.txt"); //Creates a new file called Matrix Answer.
for (int i = 1; i < mat1rows + 1; i++)
{
for (int j = 1; j < mat2cols; j++) {
pw.print(resltmat[i][j] + " "); // Writes the output to file the file called MatrixAnswer
}
pw.println();
}
pw.close();
} else // If no of columns not equal to rows control passes to else block.
System.out.println("Multiplication of Matrix is not possible because columns are not equal to rows");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Might be because of this
for (int i = 1; i < mat1rows + 1; i++) {
line = br.readLine();
String[] colvals = line.split(" ");
for (int j = 1; j < mat1cols; j++) {
mat1vals[i][j] = Integer.parseInt(colvals[j - 1]);
}
}
i = mat1rows on the last iteration which is OOB. Change for (int i = 1; i < mat1rows + 1; i++) to for (int i = 1; i < mat1rows; i++)
As you used in the allocation, the dimension of the resulting matrix are mat1rows x mat2cols. Thus in the computation of resltmat[i][j] the index i has bound mat1rows (check) and the index j has the upper bound mat2cols (fail). Thus change the range of j from mat1cols to mat2cols.

How can I store substrings generated from a String into a String array?

The program I am writing is to generate every possible sub-string from a given string (including the word itself) and store these into a String array
This is my code:
String word = "WOMAN";
String[] res = new String[20];
String sub;
int i, j, k;
int len = word.length();
for(i = 0; i < len; i++)
{
for(j = 0; j <= len-i; j++)
{
sub = word.substring(i, i+j);
for(k = 0; k < res.length; k++)
res[k] = sub;
}
}
I get an error that says - error: incompatible types: String[] cannot be converted to String. What am I doing wrong?! I want to store each sub-string as an element in the res array.
public static String[] getSubStrings(String string){
List<String> result = new ArrayList<String>();
int i, c, length;
length = string.length();
for( c = 0 ; c < length ; c++ )
{
for( i = 1 ; i <= length - c ; i++ )
{
result.add(string.substring(c, c+i));
}
}
return result.toArray(new String[result.size()]);
}
i change little maybe for some help
String word = "WOMAN";
String[] res = new String[20];
String sub;
int i, j, k=0;
int len = word.length();
for(i = 0;i < len;i++)
{
for(j = 0;j <= len-i;j++,k++)
{
sub = word.substring(i, i+j);
//for(k = 0;k < res.length;k++)
res[k] = sub;
}
}
Try it this way
String word = "WOMAN";
String sub = "";
int len = word.length();
List list = new ArrayList();
for(int i = 0; i < len; i++)
{
for(int j = 1; j <=len-i; j++)
{
sub = word.substring(i, i+j);
list.add(sub);
}
}
System.out.println(list);
Try Using ArrayList in place of array . Array Size is fixed . So generated sub strings can sometimes over flow or some spaces remain empty if sub string size will be less than the array. Array list grows dynamically with the increasing size .
with Array list one simple solution would be :
public class GenerateStrings {
/**
* Generate substrings of a given string and add them in an arraylist.
*/
public static void main(String[] args) {
ArrayList<String> aList=new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter the string to split");
String string=sc.nextLine();
for(int i=0;i<string.length();i++){
for(int j=1;j<=string.length()-i;j++){
String subString=string.substring(i, i+j);
aList.add(subString);
}
}
System.out.println(aList);
}
}
I Hope it helps .
I simplified your code to this one. This might help.
String str = "WOMAN";
List<String> tempArr = new ArrayList<String>();
for (int i = 1; i < str.length(); i++) {
for (int j = i; j <= str.length(); j++) {
tempArr.add(str.substring(i - 1, j));
}
}
String[] res = tempArr.toArray(new String[tempArr.size()]);

How do I printout my 2 dimensional array?

Trying to build a data structure for a sudoku board, and I want to print it to the console for starters. I'm using a 2 dimensional array for represent each cell on a sudoku game and I'm having a really nooby problem printing it out.
public class Main {
public static void main(String[] args) {
int[][] puzzleBoard = {};
//Row 1
puzzleBoard[1][1] = 0;
puzzleBoard[2][1] = 0;
puzzleBoard[3][1] = 0;
puzzleBoard[4][1] = 0;
puzzleBoard[5][1] = 0;
puzzleBoard[6][1] = 0;
puzzleBoard[7][1] = 0;
puzzleBoard[8][1] = 0;
puzzleBoard[9][1] = 0;
//Row 2
puzzleBoard[1][2] = 0;
puzzleBoard[2][2] = 0;
puzzleBoard[3][2] = 0;
puzzleBoard[4][2] = 0;
puzzleBoard[5][2] = 0;
puzzleBoard[6][2] = 0;
puzzleBoard[7][2] = 0;
puzzleBoard[8][2] = 0;
puzzleBoard[9][2] = 0;
//Row 3
puzzleBoard[1][3] = 0;
puzzleBoard[2][3] = 0;
puzzleBoard[3][3] = 0;
puzzleBoard[4][3] = 0;
puzzleBoard[5][3] = 0;
puzzleBoard[6][3] = 0;
puzzleBoard[7][3] = 0;
puzzleBoard[8][3] = 0;
puzzleBoard[9][3] = 0;
//Row 4
puzzleBoard[1][4] = 0;
puzzleBoard[2][4] = 0;
puzzleBoard[3][4] = 0;
puzzleBoard[4][4] = 0;
puzzleBoard[5][4] = 0;
puzzleBoard[6][4] = 0;
puzzleBoard[7][4] = 0;
puzzleBoard[8][4] = 0;
puzzleBoard[9][4] = 0;
//Row 5
puzzleBoard[1][5] = 0;
puzzleBoard[2][5] = 0;
puzzleBoard[3][5] = 0;
puzzleBoard[4][5] = 0;
puzzleBoard[5][5] = 0;
puzzleBoard[6][5] = 0;
puzzleBoard[7][5] = 0;
puzzleBoard[8][5] = 0;
puzzleBoard[9][5] = 0;
//Row 6
puzzleBoard[1][6] = 0;
puzzleBoard[2][6] = 0;
puzzleBoard[3][6] = 0;
puzzleBoard[4][6] = 0;
puzzleBoard[5][6] = 0;
puzzleBoard[6][6] = 0;
puzzleBoard[7][6] = 0;
puzzleBoard[8][6] = 0;
puzzleBoard[9][6] = 0;
//Row 7
puzzleBoard[1][7] = 0;
puzzleBoard[2][7] = 0;
puzzleBoard[3][7] = 0;
puzzleBoard[4][7] = 0;
puzzleBoard[5][7] = 0;
puzzleBoard[6][7] = 0;
puzzleBoard[7][7] = 0;
puzzleBoard[8][7] = 0;
puzzleBoard[9][7] = 0;
//Row 8
puzzleBoard[1][8] = 0;
puzzleBoard[2][8] = 0;
puzzleBoard[3][8] = 0;
puzzleBoard[4][8] = 0;
puzzleBoard[5][8] = 0;
puzzleBoard[6][8] = 0;
puzzleBoard[7][8] = 0;
puzzleBoard[8][8] = 0;
puzzleBoard[9][8] = 0;
//Row 9
puzzleBoard[1][9] = 0;
puzzleBoard[2][9] = 0;
puzzleBoard[3][9] = 0;
puzzleBoard[4][9] = 0;
puzzleBoard[5][9] = 0;
puzzleBoard[6][9] = 0;
puzzleBoard[7][9] = 0;
puzzleBoard[8][9] = 0;
puzzleBoard[9][9] = 0;
int rows = 9;
int columns = 9;
int i, j;
for (i = 1; i < rows; i++){
for(j = 1; j < columns; j++){
System.out.print(puzzleBoard[i][j] + " ");
}
System.out.println( "" );
}
}
}
You didn't specify a size for your array.
int[][] puzzleBoard = {}; should be int[][] puzzleBoard = new int[10][10];
There is no need to initialize your array with a for loop or line by line if you're only filling it with 0.
Then arrays are 0 base indexed. So the first element will be at position [0][0] and the last one at position [9][9].
You could also remove your two variables rows and columns.
Finally, you should modify your for loop to start from 0.
for (i = 0; i < puzzleBoard.length; i++){
for(j = 0; j < puzzleBoard[i].length; j++){
System.out.print(puzzleBoard[i][j] + " ");
}
System.out.println( "" );
}
To learn more about arrays in Java, I advise you to read this.
You should initialize the array elements with a for loop as well!
Also, remember, Java arrays are zero based, so the topmost cell would be puzzleboard[0][0]!
You should also specify a size for your array - int[][] puzzleBoard = new int[10][10];
You should use java.util.Arrays.deepToString() to print 2D arrays:
Returns a string representation of the "deep contents" of the
specified array. If the array contains other arrays as elements, the
string representation contains their contents and so on. This method
is designed for converting multidimensional arrays to strings.
The string representation consists of a list of the array's elements,
enclosed in square brackets ("[]"). Adjacent elements are separated by
the characters ", " (a comma followed by a space). Elements are
converted to strings as by String.valueOf(Object), unless they are
themselves arrays.

Exception in thread main ArrayIndexOutOfBoundsException

Can someone maybe help me with the following error. Exception in thread main java.lang.arrayindexoutofboundsexception : 3 at RowTrans.encrypt(Rowtrans.java:33)
at RowTrans.main(Rowtrans.java :7)
In my program I want to get a text. Put it in a matrix with 5 columns and determine the rows according to the length of the text. Then i want to change the column and row position so that the row gets the columns position and the column the row. And when a row does not contain 5 values I want to add the character Z in the empty spaces. Can anyone assist me on this error please.
Here is my code
import java.util.Scanner;
public class ColTrans {
public static void main(String[] args)
{
String ori = "This is my horse";
String enc = encrypt(ori);
System.out.println(enc);
// String dec = decrypt(enc);
// System.out.println(dec);
}
static String encrypt(String text)
{
String result = "";
text = text.toUpperCase();
int length = text.length();
int rows = length / 5;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];
if ((length % 5) != 0)
rows = rows + 1;
int k = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < 5; j++)
{
if (k > length)
b[i][j] = 'Z';
else
{
d[k] = text.charAt(k);
b[i][j] = d[k];
}
k++;
}
for (int i = 0; i < 5; i++)
for (int j = 0; j < rows; j++)
{
c[i][j] = b[j][i];
result = result + c[i][j];
}
return result;
}
}
Here is the cause:
You are increamenting row variable by one, once you have defined the array.
Move following line before line char [][] b =new char[rows][5];
if ((length % 5) != 0)
rows = rows + 1;
There are 2 issues in your code. First move the mod part before the matrix instantiation :
if ((length % 5) != 0)
rows = rows + 1;
char [][] b =new char[rows][5];
[...]
Then change if ( k > length ) to if ( k >= length )
just change your code as following:
if ((length % 5) != 0)
rows = rows + 1;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];
According to your description:
text = text.toUpperCase();
char[] b = text.toCharArray();
char[][] c = new char[b.length][5];
int bLen = 0;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < 5; j++) {
if(bLen < b.length)
c[i][j] = b[bLen++];
else
c[i][j] = 'Z';
}
}
//change the column and row position
char[][]d = new char[c[0].length][c.length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
d[i][j] = c[j][i];
}
}
Output: TI EZZZZZZZZZZZZHSHZZZZZZZZZZZZZI OZZZZZZZZZZZZZSMRZZZZZZZZZZZZZ YSZZZZZZZZZZZZZ

Categories