Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there anyway I could return an array of strings from an array of pairs? I'm guessing it's something to do with hashmap since two values are involved. Any simple example with some explanation would help :)
As pointed out by #dasblinkenlight, if the input is (y,3),(t,2) and I want the output as "yPP","tP" where the string should have the length of the numerical value given. and so after taking the character, the rest of the length is to be filled by P.
Suppose I've got the static method,
public static Line[] get(Couple[] temp)
I need to complete it so that my main method would produce the following result:
get (new Couple[]{new Couple(āeā,4), new Couple(ānā,2)})
should return the array of Strings
{"ePPP", "nP"}
Hope this helps :)
class Pair{
public Pair(String st1,String st2){
string1=str;
string2=str;
}
private String string1;
private String string2;
// + getters and maybe setters for strings;
}
Later on create simple Pair[] and do whatever you want
With a Pair class implemented as
class Pair {
private final String s;
private final int i;
public Pair(String s, int i){
this.s = s;
this.i = i;
}
public String getS() {
return s;
}
public int getI() {
return i;
}
}
Initialize the Pair[] and invoke a converter method as
Pair[] pairArr = new Pair[2];
pairArr[0] = new Pair("Y", 3);
pairArr[1] = new Pair("T", 2);
System.out.println(Arrays.toString(convertPairsToStrArray(pairArr, "P")));
Output :
[YPP, TP]
Here's a sample converter implementation:
private static String[] convertPairsToStrArray(Pair[] pairArr, String padStr) {
String[] strArr = null;
if (pairArr != null) {
strArr = new String[pairArr.length];
for (int i = 0; i < pairArr.length; i++) {
String s = pairArr[i].getS();
StringBuilder sb = new StringBuilder();
if (s != null) {
sb.append(s);
int j = 0;
if ((j = pairArr[i].getI() - s.length()) > 0) {
while (j-- > 0) {
sb.append(padStr);
}
}
}
strArr[i] = sb.toString();
}
}
return strArr;
}
Like many things, the question contains the answer.
Create a class to hold the pairs. Add a method, to that class, to produce the desired output. Here is some code:
Pairzor.java:
public class Pairzor
{
private final static char FILL_CHARACTER = 'P';
private final char theChar;
private final int theCount;
public Pairzor(
final char newChar,
final int newCount)
{
theChar = newChar;
theCount = newCount;
}
public final String blammy()
{
StringBuilder buffer = new StringBuilder();
buffer.append(theChar);
for (int count = 1; count < theCount; ++count)
{
buffer.append(FILL_CHARACTER);
}
return buffer.toString();
}
}
Main.java
public class Main
{
/**
* #param args
*/
public static void main(String[] args)
{
Pairzor one = new Pairzor('y', 3);
Pairzor two = new Pairzor('t', 2);
System.out.println(one.blammy());
System.out.println(two.blammy());
}
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I want to have two constructors in one class but I can't. I know it is possible but I can't find my mistake.
public static class Matrix{
int [][] matrix;
int row;
int column;
String matrixName;
Matrix (String [] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int [row][column];
initialize(input);
}
Matrix (Matrix A, char ch) {
if (ch == 'T'){
column = A.row;
row = A.column;
}
else{
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
}
the second Matrix can't be defined as a constructor.
There is no problem with the second constructor. The problem is with the first line of the declaration which is public static class Matrix. Note that you can not use static modifier here. Only public, abstract and final are allowed.
After this correction, you can test your class as follows:
class Matrix {
int[][] matrix;
int row;
int column;
String matrixName;
Matrix(String[] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int[row][column];
// initialize(input);
System.out.println("First");
}
Matrix(Matrix A, char ch) {
if (ch == 'T') {
column = A.row;
row = A.column;
} else {
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
System.out.println("Second");
}
}
public class Main {
public static void main(String[] args) {
Matrix m1 = new Matrix(new String[] { "a", "b" }, "Hello");
Matrix m2 = new Matrix(m1, 'X');
}
}
Output:
First
Second
Is it nested class in another class? Because class can be static only when it is nested in another class like this:
public class Matrix {
public static class NestedClass {
int number;
String string;
public NestedClass(NestedClass A, String string) {
this.number = A.number;
this.string = string;
}
public NestedClass(NestedClass A) {
this.string = A.string;
}
}
}
Class Matrix cannot be static, only final or abstract.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
/* This program sorts out name in orders from
their first alphabetical orders .*/
package nameorder;
public class NameOrder {
public static void sayName(String a, String s, String d){
System.out.println("Name By Alphabetical Order: \n1."+a+"\n"+"2."+s+"\n3."+d+"\n");
}
public static void stringOrder(String a ,String s ,String d){
int i= a.compareTo(s) ;
int j= a.compareTo(d) ;
int k= d.compareTo(s) ;
int l= d.compareTo(a) ;
String first="";
String second="";
String third="";
if(i<0&&j<0){
first=a;
if(k>0&&l>0){
third = d;
second = s;
}else{
second = d;
third = s;
}
}else if(i>0&&j>0){
third=a;
if(k<0&&l<0){
first = d;
second = s;
}else{
second = s;
first = d;
}
}else{
second=a;
if(k<0&&l<0){
first = d;
third = s;
}else{
first = s;
third = d;
}
}
sayName(first,second,third);
}
public static void main(String[] args) {
String a ="C";
String s ="a";
String d ="h";
stringOrder(a.toUpperCase(),s.toUpperCase(),d.toUpperCase());
}
}
I'm just wondering if I'm doing this right or there is a better shorter version for this?
From just the perspective of "sorting three strings", you could just need to do three comparisons and lose all those temp variables.
public static void stringOrder(String a, String s, String d) {
String tmp;
if (a.compareTo(s) > 0) {
tmp = a;
a = s;
s = tmp;
}
if (a.compareTo(d) > 0) {
tmp = a;
a = d;
d = tmp;
}
if (s.compareTo(d) > 0) {
tmp = s;
s = d;
d = tmp;
}
sayName(a, s, d);
}
But from a maintainability perspective, just use the facilities built into Java to sort multiple strings at a time:
public static void stringOrder(String a, String s, String d) {
String [] arr = {a, s, d};
java.util.ArrayList<String> list = new ArrayList<String>(Arrays.asList(arr));
java.util.Collections.sort(list);
sayName(list.get(0), list.get(1), list.get(2));
}
I used Collections.List here so that your code is more dynamic, allowing for any
amount of strings to be ordered. With yours, you hard-coded that 3 strings would be entered. Here, you can enter as many strings as you'd like within the main function.
The Collections.Sort method will sort your list in the most efficient way. Whenever you can, use methods made by the guys at Java, as they've spent years optimizing these functions.
public static void main(String[] args){
// Create a collection to store the strings in
List<String> list = new ArrayList<String>();
// Add the strings to the Collection
list.add("C");
list.add("A");
list.add("H");
// Use the Collections library to sort the strings for you, by their
// defined ordering
Collections.sort(list);
// Print the ordered strings
System.out.println("Names By Alphabetical Order: ");
for(String string: list){
System.out.println(string);
}
}
I have string and i need to print all the combination of the string Char's
Example
For the string "123" the output is:
1,2,3,12,13,21,23,31,32,123,132,213,231,312,321
It must be without loops, only with recursion.
Thanks!
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
I think just giving you the full code would be a little to easy for you. This is the simple set up for the code that you would want. The recurse method is not completely finished, the return statement being one of the things that you will need to fix first. By answer the question, this way, I hope that I am still answering the question, but also still allowing you to fully learn and understand recursion on your one. By the way,
for the public static void main(String [] args) part
You would also put that in a separate class like so:
public class CharacterRecursion
{
private String str;
private int counter;
public CharacterRecursion()
{
str = "";
counter = 0;
}
public CharacterRecursion(String str1)
{
str = str1;
counter = 0;
}
public String recurse(String str)
{
if (counter == 15)
{
return ;
}
counter++;
// return (recurse(String str _________) _________) _________;
}
public String [] toString()
{
String [] arr = new String[14];
for (int i = 0; i < 14; i++)
{
arr[i] = this.recurse();
}
return arr;
}
public class CharacterRecursionClient
{
public static void main(String [] args)
{
CharacterRecursion recurse = new CharacterRecursion("123")
System.out.println(recurse.toString);
}
}
That would work just as well if you are required to have a client class. I hope that this help and cleared up at least a couple of things.
public static int arraysize=1;
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][]=new String[arraysize][3];
public static int a=0;
public void isiData(String kategori, String buku, String penulis){
this.buku[a][0]=kategori;
this.buku[a][1]=buku;
this.buku[a][2]=penulis;
arraysize++;
a++;
}
Hi guys I tried to increase my array length every time I call a method named "isiData", but it didn't work. I already checked the increment, but nothing wrong with it. Is there any way to increase its length every time I use the method? I want to make a simple way to input book, category, and its author using array.
You cannot increase the size of array.
There are 3 approaches to solve this problem:
Use ArrayList as suggested by others.
You can create another temp array of size one greater than the previous array and then copy the temp array to already created array.
You can use the copyOf(array, size) function of Arrays in Java
For example:
previousArray = Arrays.copyOf(previousArray , arraysize + 1);
arraysize += 1
Just try this Approach:
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
/**
*
* #author Maverick
*/
public class Buku {
public static int arraysize;
public String namabuku;
public String penulis;
public String Kategori;
public List<List<String>> bukuList = new ArrayList<List<String>>();
public static void main(String[] args) {
Buku n = new Buku();
for (int i = 0; i < 5; i++) {
n.isiData("ab" + i, "cd" + i, "ef" + i);
}
n.arraysize = n.bukuList.size();
for (int i = 0; i < n.bukuList.size(); i++) {
System.out.println(n.bukuList.get(i).toString());
}
}
public void isiData(String kategori, String buku, String penulis) {
bukuList.add(Arrays.asList(kategori, buku, penulis));
}
}
Output:
[ab0, cd0, ef0]
[ab1, cd1, ef1]
[ab2, cd2, ef2]
[ab3, cd3, ef3]
[ab4, cd4, ef4]
You have to call new array to change the size of an array. I assume this is an exercise to practice using an array, so I'm going to avoid the classes like Arrays and System in the isiData method. You should look at those classes though.
So something like this:
public class BukuTest
{
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][] = new String[ 0 ][ 3 ];
public void isiData( String kategori, String buku, String penulis )
{
String[][] temp = this.buku;
final int len = temp.length;
this.buku = new String[ len + 1 ][];
for( int i = 0; i < len; i++ )
this.buku[i] = temp[i];
this.buku[len] = new String[ 3 ];
this.buku[len][0] = kategori;
this.buku[len][1] = buku;
this.buku[len][2] = penulis;
// not needed
// arraysize++;
// a++;
}
public static void main(String[] args) {
BukuTest b = new BukuTest();
b.isiData( "test1", "test2", "test3" );
b.isiData( "test4", "test5", "test6" );
b.isiData( "test7", "test8", "test9" );
System.out.println(b);
}
#Override
public String toString()
{
return "BukuTest{" + "namabuku=" + namabuku + ", penulis=" + penulis +
", Kategori=" + Kategori + ", buku=" +
Arrays.deepToString(buku) + '}';
}
}
Using an ArrayList is definitely the way to go here as others have commented and displayed but, if you are absolutely bent on using a Two Dimensional String Array then this can be done with a custom method conveniently named redimPreserve() as I have shown below.
As #Jdman1699 had mentioned in his comment under your post, this is a very inefficient way of doing this sort of thing especially for larger arrays but since you asked, here is how it can be done:
// YOUR METHOD:
public int arraysize = 1;
public String[][] buku = new String[arraysize][3];
public void isiData(String kategori, String buka, String penulis){
// I have renamed the buku argument for this method to buka
// since you can not have a parameter variable named the
// same as a Class Global variable.
buku = redimPreserve(buku, arraysize, 3);
buku[arraysize-1][0] = kategori;
buku[arraysize-1][1] = buka;
buku[arraysize-1][2] = penulis;
arraysize++;
}
// THE redimPreserve() METHOD:
public static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
int newCol = 0;
if (newColSize.length != 0) { newCol = newColSize[0]; }
// The first row of your supplied 2D array will always establish
// the number of columns that will be contained within the entire
// scope of the array. Any column value passed to this method
// after the first row has been established is simply ignored.
if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
if (newCol == 0 && newRowSize <= 1) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Column dimension provided for 2D Array!\n");
}
if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
+ "No Row dimension provided for 2D Array!\n");
}
String[][] tmp = new String[newRowSize][newCol];
if (yourArray.length != 0) {
for(int i = 0; i < yourArray.length; i++) {
System.arraycopy(yourArray[i], 0, tmp[i], 0, yourArray[i].length);
}
}
return tmp;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am working on a homework about arrays and while loop in java.
The question is to create a method called public int getPopulation(String province) which returns the population of the province. If there is no such province, return a constant called NO_SUCH_PROVINCE, which is an int set to -1. But I cannot get what I want.
public class Country {
public static final int ON = 0;
public static final int QC = 1;
public static final int BC = 2;
public static final int AB = 3;
public static final int MB = 4;
public static final int NO_SUCH_PROVINCE = -1;
private String[] provinces;
private int[] population;
public Country() {
provinces = new String[5];
provinces[0] = "Ontario";
provinces[1] = "Quebec";
provinces[2] = "British Columbia";
provinces[3] = "Alberta";
provinces[4] = "Manitoba";
population = new int[5];
population[ON] = 12851821;
population[QC] = 7903001;
population[BC] = 4400057;
population[AB] = 3645257;
population[MB] = 1208268;
}
public int getPopulation(String province) {
int i = 0;
int temp = 0;
while(i < provinces.length) {
if(province == provinces[i]) {
temp = population[i];
}else {
temp = NO_SUCH_PROVINCE;
}
i++;
}
return temp;
}
There is an issue with your search algorithm. It keeps going after it finds the solution and then overwrites the correct value. This here, when it finds the value, immediately returns the value and leaves the method. If it cannot find any value, it then returns NO_SUCH_PROVINCE.
The other issue is that noted by Scary Wombat, which is that your code does not compare Strings correctly to find a match.
public int getPopulation(String province) {
for (int i = 0; i < provinces.length; i++) { // For objects, always use .equals()
if (province.equals(provinces[i])) { return population[i]; }
}
return NO_SUCH_PROVINCE;
}
Of course, this would be much simpler if one could simply use a HashMap<String, Integer> that stores all the data like a dictionary.