This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 6 years ago.
String[] nodes = {"a", "b", "c"};
String[] a = {"ax", "ay"};
String[] b = {"bx", "by"};
String[] c = {"cx", "cy"};
for (String n: nodes){
for (String elem: /* n, it should be sequentially a, b, c */){
System.out.print(elem);
}
}
I want to use the variable name to call each string array.
What I want as the result is, ax ay bx by cx cy...
What should I do? or do I need to change its structure??
You need to declare nodes array in different way. You declared it as a string array, but you need to declare it as array of arrays. Check the code below:
String[] a = {"ax", "ay"};
String[] b = {"bx", "by"};
String[] c = {"cx", "cy"};
String[][] nodes = {a, b, c};
for (String[] n: nodes){
for (String elem: n){
System.out.print(elem);
}
}
Or use a Class (yay!):
class Node {
String name;
Node(String name) {
this.name = name;
}
String getX() {
return name + "x";
}
String getY() {
return name + "y";
}
}
Node[] nodes = new Node[] {new Node("a"), new Node("b"), new Node("c")};
for (Node node : nodes){
System.out.printf("%s %s ", node.getX(), node.getY());
}
Related
I need to create class that has a setter to assign values to an array, then in the main method take command line arguments and use the method to put that in an array. I have no clue how to do this. Any help would be appreciated.
import java.util.*;
public class Number{
private double [] number = new double[3];
private double value ;
private int i;
public double[] getNumber() {
return sweet;
}
public void printNumber() {
System.out.println("Array " + Arrays.toString(number));
}
public double getValue(int i) {
return this.i;
}
public void setMethod(int i, double value) {
this.value = value;
this.i = i;
}
public class Score {
public static void main (String [] args) {
Number score = new Number();
// code to get values from keyboard into the array
edit: Thank you for your help I managed to create the new array. Now I need to be able to change the array value. In my setMethod I am guessing I need to change it to something like this..,
public void setMethod(int i, double value { //
for ( i = 0; i < this.array.length; i ++){
this.array[this.i] =this. value;
}
this.mark = mark;
this.pos = pos;
}
If you look at main() method's list of arguments, you'll see String[] args - command line arguments are passed to the main() method as arguments. You can simply read them using a for loop:
String[] yourNewArray = new String[args.length]:
for(int i = 0; i< args.length; i++) {
yourNewArray[i] = args[i];
}
Now in yourNewArray you have stored command line arguments.
It is worth to mention that yourNewArray doesn't need to be an array containg Strings. Arguments passed as command line arguments can be parsed and used as, for example integers, doubles and other types of values.
Now, as you edited your question and have new thing to figure out, I will show you an example, how you could implement method to assign new array to an existing one and another method to change single value in this array:
import java.util.*;
// This is your class - there is String[] arr - you want to be able to change whole array or its single value:
class MyClass {
String[] arr;
// To change whole array:
public void setMethod(String[] array) {
this.arr = array;
}
// To change only one value in array:
public void changeSingleValue(int index, String value) {
arr[index] = value;
}
}
public class Test {
public static void main(String[] args) {
String[] arrayFromArgs = new String[args.length];
for(int i = 0; i < args.length; i++) {
arrayFromArgs[i] = args[i];
}
MyClass obj = new MyClass();
// In this method you assign array storing command line arguments to the array in MyClass:
obj.setMethod(arrayFromArgs);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is an example of assigning another array to obj.arr:
String[] anotherArray = { "A", "B", "C", "D"};
obj.setMethod(anotherArray);
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Here is another way to assign new values to obj.arr:
obj.setMethod(new String[]{"x", "y", "z"});
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
// Simple example how to change single value in obj.arr by passing the index where and value that needs to be changed:
obj.changeSingleValue(1, "Changed");
System.out.println("obj.arr: " + Arrays.toString(obj.arr));
}
}
And the output of the above program:
obj.arr: [] // in this array you will see values passed as the command line arguments
obj.arr: [A, B, C, D]
obj.arr: [x, y, z]
obj.arr: [x, Changed, z]
Try something like the following code to copy your array:
public static void main (String [] args) {
// code to get values from keyboard into the array
String[] myArgs = new String[args.length];
for (int i = 0; i < args.length; i++) {
myArgs[i] = args[i];
}
// ...
}
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);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I trying to replace the value in the arraylist of edge under the updateEdge() method.
At If statement, the value of the edge.a.name and edge.b.name matches my source and dest value but somehow it doesn't enter the IF condition.
What I found out is this, edge.a = Node#55f96302 and a.name = Node#55f96302.
What I know this when I print out the node address, both does not match.
private ArrayList<Node> nodes = new ArrayList<Node>();
private ArrayList<Edge> edges = new ArrayList<Edge>();
//add new node
public void addNode(String nodeName)
{
Node node = new Node(nodeName);
nodes.add(node);
}
//add edge
public void addEdge(String source, String dest, String weight)
{
Node a, b;
a = new Node(source);
b = new Node(dest);
Double w = Double.parseDouble(weight);
Edge edge = new Edge(a, b, w);
edges.add(edge);
}
//Check index of the node
public int indexOfNode(String name)
{
for (int i = 0; i < nodes.size(); i++)
{
if(nodes.get(i).name.equals(name))
{
return i;
}
}
return -1;
}
//update edge
public void updateEdge(String source, String dest, String weight)
{
Node a, b;
a = nodes.get(indexOfNode(source));
b = nodes.get(indexOfNode(dest));
Double w = Double.parseDouble(weight);
for(int i = 0; i < edges.size(); i++)
{
Edge edge = edges.get(i);
if(edge.a.name == a.name && edge.b.name == b.name)
{
edge.weight = w;
}
}
}
a String is an object, when you compare two objects in java by using the == operator, you compare their hashcode and class, hence the 'Node' and 55f96302.
An int or double (for instance) are primitive types and hence can be compared with the == operator. They actually have to, seeing as how they don't have any methods for comparison since they are not objects (Integer and Double are their class counterparts).
In order to compare two strings based on their character array values, you will need to use the .equals() method:
edge.a.name.equals(a.name)
I assume name is a string
replace if(edge.a.name == a.name && edge.b.name == b.name)
with if(edge.a.name.equals(a.name) && edge.b.name.equals(b.name))
This question already has answers here:
Cartesian product of an arbitrary number of sets
(11 answers)
Closed 8 years ago.
I have an array that contains 3 arrays, like this:
String[][] S = { {a,b,c} , {d,e}, {f,g,h} }
Now I want to create all arrays
R = {r1,r2,r3}
where r1 belongs to S1, r2 belongs to S2, r3 belongs to S3 (S1, S2, S3 are sub-array of S) and I want have the output like that:
R1 = {S[1][1], S[2][1], S[3][1]},
R2 = {S[1][1], S[2][1], S[3][2]},
R3 = {S[1][1], S[2][1], S[3][3]},
...,
R18 = {S[1][3], S[2][2], S[3][3]}
I can not use 3 for-iterators because the array S is dynamic.
Here is a solution using recursion.
private static void fillArray(List<String> prefix, String[][] s, List<String[]> allResults){
if(prefix.size() < s.length) {
String[] currentArray = s[prefix.size()];
for (String currentString : currentArray) {
LinkedList<String> copy = new LinkedList<>(prefix);
copy.add(currentString);
fillArray(copy,s,allResults);
}
} else {
allResults.add(prefix.toArray(new String[prefix.size()]));
}
}
To use it call:
String[][] S = { {"a","b","c"} , {"d","e"}, {"f","g","h"} };
List<String[]> allResults = new LinkedList<>();
fillArray(new LinkedList<String>(),S,allResults);
for (String[] result: allResults) {
System.out.println(Arrays.toString(result));
}
EDIT:
Here is a method for what you want:
private static void fillArray2(List<String> prefix, String[][] s, List<String[]> allResults){
if(prefix.size() < s.length) {
String[] currentArray = s[prefix.size()];
for(int i=0;i<currentArray.length;i++) {
LinkedList<String> copy = new LinkedList<>(prefix);
copy.add("S["+(prefix.size()+1)+"]["+(i+1)+"]");
fillArray2(copy,s,allResults);
}
} else {
allResults.add(prefix.toArray(new String[prefix.size()]));
}
}
I have an declared an ArrayList a = [1,2,3]. I created another ArrayLList b using the loop below:
for(int i = 0; i<a.size(); i++)
{
for(int j=i+1; j<a.size();j++)
{
b.add("{" + a.get(i)+ "," + a.get(j) + "}");
}
}
Now the ArrayList b will contain elements [{1,2},{1,3},{2,3}]. Now if I print the statement using System.out.println(b.get(0)), then the output will be {1,2}.
Now I want to to further explore the array such that I can extract 1 and 2 separately. How can I achieve this?
create class pair
class Pair{
String a
String b
....
///setters and getters
}
now let b will be List<Pair> so instead calling b.add("{" + a.get(i)+ "," + a.get(j) + "}"); you can do simple b.add(new Pair(a.get(i),a.get(j));
then you don't need to play with splitting string and stuff like that, you can easly access your values by doing ie b.get(0).getA() or b.get(0).get()
you can also override method to string in pair
public String toString() {
return "{" + a+ "," + b + "}";
}
so when you do System.out.println(a.get(0)) you will get exactly same output like before
***EDIT
if you want to have a groups of more than 2 elements as you say in comment
you can construct your class little bit different
class MyClass{
List<Integer> fields = new ArrayList<Integer>();
//two constructors
MyClass(int singleVal)
{
fields.add(singleVal);
}
MyClass(MyClass a, MyClass b)
{
fields.addAll(a.fields);
fields.addAll(b.fields);
}
//getters setters depends what you need
}
both of your list will be list of MyClass, when you populate list a, you create objects by using first constructor, when you want to add elements to your b list you can do b.add(new MyClass(a.(i),a.(j))) but you can also do b.add(new MyClass(a.(i),b.(j))) or b.add(new MyClass(b.(i),b.(j)))
I understand that your array b holds just strings. Use any String tokenizing mechanism to achieve this - either String.split or StringTokenizer
Hint : StringTokenizer performs better
You should decompose the presentation from logic.
In your loop you create a pair of element. So create a some type to represent it.
class Pair {
private int left;
private int right
Pair(int left, int right) {
this.left = left;
this.right = right;
}
public int getLeft() {
return this.left;
}
public int getRight() {
return this.right;
}
#Override
public void toString() {
return String.format("{%d , %d}",getLeft(),getRight());
}
}
List list = new ArrayList();
for(int i = 0; i<a.size(); i++)
{
for(int j=i+1; j<a.size();j++)
{
list.add(new Pair(i,j));
}
}
Then to access (extract) items
int l = list.get(0).getLeft();
int r = list.get(0).getRith();
If you want to display on console the result.
for(Pair p : list) {
System.out.println(p);
}
About output format
EDIT
AS the OP mentioned in the comment. He would like to have flexible data structure that allow him to store the data.
List<List<Integer> parent = new ArrayList<List<Integer>()
for(int i = 0; i<a.size(); i++)
{
List<Integer> child = new ArrayList<Integer>();
for(int j=i+1; j<a.size();j++)
{
child.add(a.get(i));
child.add(a.get(j));
}
parent.add(child);
}
String ele = b.get(0);
ele = ele.replace("{", "");
ele = ele.replace("}", "");
StringTokenizer tokens = new StringTokenizer(ele, ",");
while(tokens.hasMoreTokens()) {
int val = Integer.parseInt(tokens.nextToken());
}