String [] board = new String [9];
String [] sequence = new String [8];
sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];
Say I was to make sequence[0]="XXO";
How could I take sequence[0] and change the the board points so that:
board[0]="X";
board[1]="X";
board[2]="O";
I am trying to run this for loop and I have to initialize the board array before the sequences part as I am printing it out to the screen and can't have the values be null.
for(int i = 0; i < 8; i++
{
if(sequence[i].equals("X"+"X"+" "))
{
sequence[i] = "XXO";
}
}
You can use String::split which return an array of String for example :
String[] board;//you could also to not initialize the array here
//because you will do that in split
String[] sequence = new String[8];
sequence[0] = "XXO";
board = sequence[0].split("");//split and initialize the board array
//print the values
System.out.println(board[0]);
System.out.println(board[1]);
System.out.println(board[2]);
Output
X
X
O
You generally shouldn't store the same data in different ways (the Don't Repeat Yourself principle), sometimes because it leads to a mess like this.
One correct way to do what you want is the following:
board[0] = String.valueOf(sequence[0].charAt(0));
board[1] = String.valueOf(sequence[0].charAt(1));
board[2] = String.valueOf(sequence[0].charAt(2));
As you want only one character as an element in your board array you can use character array instead of String array and then can use
char board[] = new char[9];
board = sequence[0].toCharArray();
Related
I have created an array under
public class program {
public static String[] tasks = new String[5];
}
Now I want to create a two dimensional String array with that existing String array (tasks) and a new String array (date) in order to have synchronized data.
How would one go about that in Java?
Can you explain more on the problem. This can be simply achieved using pojo. I couldn't comment so added it as ans.
You can covert array to list. Can this example is helpful. What is the use of Collections.synchronizedList() method? It doesn't seem to synchronize the list
OR
public String[][] arr = new String[5][2]; // not sure why you need static
for (int i = 0; i < 5; i++) { // you can take constant or array length
arr[i][0] = new Date().toString(); // or System milliseconds as string
arr[i][1] = tasks[0];
}
Like so
public static String[][] tasksWithDate = new String[task.length][2];
You can push your old data with a simple loop
for (int i = 0; i < task.length; i++) {
taskWithDate[i][0] = tasks[0];
}
If you access the new array you can access a specfific task via taskWithDate[i][0] and the date with taskWithDate[i][1]
First, a 2D array is an array of arrays.
So to create a two dimensional array, you do it like so:
String[][] tasks = new String[5][2];
This creates a 2D array with 5 rows and 2 columns.
To insert a record into the first row and first column, you do it like so:
tasks[0][0] = "My new string";
To loop through a 2D array, you will need 2 loops.
for (int row = 0; row < tasks.length; row++) {
for (int col = 0; col < tasks[row].length; col++) {
tasks[row][col] = "New string for index row " + row + " col " + col;
}
}
Below example will give you complete context.
Adding Tasks with some values
Creating Two Dimension array, where first index will present tasks value and 2nd index is Date.
Printing all values.
public static void method() {
String[] tasks = { "1", "2", "3", "4", "5" };//new String[5];
String[][] taskTwoDim = new String[tasks.length][2];
//Adding values to two dimension array, 0->tasks, 1->String Date
for (int i = 0; i < tasks.length; i++) {
taskTwoDim[i][0] = tasks[i];
taskTwoDim[i][1] = new Date().toString();
}
//Printing all values which is present on index-0, index-1
for (int a = 0; a < taskTwoDim.length; a++) {
System.out.println(taskTwoDim[a][0] + " " + taskTwoDim[a][1]);
}
}
If I understand your question right, you can create a 2d array from 2 one-dimensional arrays by simply doing this:
int[][] resultArray = {task, date};
If I understand your question correctly, it is better to create a new POJO class TaskDate.
public class program {
public static TaskDate[] tasks = new TaskDate[5];
}
class TaskDate {
private String task;
private String date;
// todo add a constructor, getters, and setters
}
I really need help with my program. I'm trying to make a cumulative grade calculator in java, using arrays and dialog boxes. For some reason, my arrays won't print out the input made by the user which is throwing off my calculations. How can I give it the correct value?
{
// First array - Length
int[] arNumber = null;
int number;
String str;
// Second array - Elements
int numbers;
int[] arNumbers = null;
int total = 0;
int gradeSum = 0;
String str2;
String message = "How many grades will you input in this class?";
str = JOptionPane.showInputDialog(message);
number = Integer.parseInt(str);
arNumber = new int[number];
for(int index = 0; index < arNumber.length; index++)
{
String message2 = "Insert your grade";
str2 = JOptionPane.showInputDialog(message2);
numbers = Integer.parseInt(str2);
arNumbers = new int[numbers];
}
for (int element : arNumbers)
{
// Print array onto console
System.out.println(element);
// Add all elements
gradeSum += element;
// Print grade onto console
System.out.println(gradeSum);
}
total = gradeSum / arNumber.length;
return total;
}```
It looks like you don't need to use two arrays. The line with arNumbers = new int[numbers]; means that arNumbers is getting reinitialized as a new array for every iteration of that loop. Try using arNumber[index] = numbers; to assign the user-entered value into the arNumber array and do away with arNumbers. Then loop over arNumber in the second loop.
Also note that total is declared as an int which will truncate your floating point value, which I'm guessing you don't want. Good luck!
My array is filled in the beginning with a string. Then the user can enter a new string. I want my array to shift to the right, like {a,x,x,x} should move the a to the right {x,a,x,x} so new entries can move up. When I run my code it puts the entered string in the first position of the array, but in the next step it doesn't move the entered string, but prints out an array only filled with the predefined string. Why doesn't it contain my entered string?
public static void main(String args[]) {
int i;
String n = new String("n");
Scanner sc = new Scanner(System.in);
String a;
String affe [] = new String [5];
Arrays.fill(affe, n);
a = sc.next();
affe[0] = a;
System.out.println(Arrays.toString(affe));
for(i = 0; i<affe.length-1; i++){
affe[i] = affe[i+1];
}
System.out.println(Arrays.toString(affe));
}
Try
Collections.rotate(Arrays.asList(affe), 1);
You're copying the wrong way around.
Change this line:
affe[i] = affe[i+1];
to
affe[i+1] = affe[i];
But you also need to change the order of the loop to go from back to front. Otherwise, each subsequent iteration brings the one value from the start forward to the end. So change the loop to:
for (int i = affe.length - 2; i >= 0; i--) {
affe[i+1] = affe[i];
}
How to separate following string by ' ' and store in two dimensional array in java
"('1494576','16268568','5150022241','Flour','Pillsbury','2 For $5.00','5','8/20/2016','80','Best All Purpose Unbleached Enriched','Demoulas/Market Basket','2','itemlink')"
I need data only in between ' ' in two dimensional array
like
temp[0][0]="1494576"
temp[0][1]="16268568"
As #Jesse Amano recommends, you could probably get away with using JSON. Here's another crude way of doing it:
String s = "('1494576','16268568','5150022241','Flour','Pillsbury','2 For $5.00','5','8/20/2016','80','Best All Purpose Unbleached Enriched','Demoulas/Market Basket','2','itemlink')";
String[][] temp = ...;
boolean inside = false;
boolean end = false;
int index = 0;
for(int i = 0; i < s.length(); i ++){
if(s.substring(i, i + 1).equals("'")){
inside = !inside; //determines if we are between ''
if(end) index ++;
end = !end; //determines if this is the closing '
}
else{
if(inside) temp[0][index] += s.substring(i, i +1);
}
}
String s = "('1494576','16268568','5150022241','Flour','Pillsbury','2 For $5.00','5','8/20/2016','80','Best All Purpose Unbleached Enriched','Demoulas/Market Basket','2','itemlink')"
s = s.substring(2,s.length()-2);
String[] str = s.split("','");
String[][] temp = new String[3][4];
int k = 0;
for(String[] a: temp){
for(String b: a){
b = str[k];
k++;
}
}
Since you have 13 elements, it's not possible to put it in rectangular 2D array. This one will hold only 12 of them. You may adjust your data or use jagged array to hold just 13.
i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);