I am posting this question related to how to write values one below the other without using System.out.println(). I believe generally when we want to print out values we can use arrays or lists etc. It would go something like this, for example:
public class Main {
public static void main(String[]args){
int[] myList = new int[10] ;
for(int i = 0 ; i < myList.length ; i++){
myList[i] = i ;
System.out.println(myList[i] + "\n");
}
}
}
But I want to know how to print values in a box like this:
1 2 3 4
5 6 7 8
Thank you,
It is not completely clear what you want to achieve. If your purpose is to display data on standard out (console) I don't see any reason not to use System.out.println(), .print() or .printf().
Warning, long answer with questionable relevance
To print your values in two rows can be done in many different ways. Here is one option:
private static void printNums2() {
int rowLength = 4;
for (int i = 1; i < 9; i++) {
System.out.print(i + ((i % rowLength == 0) ? " \n" : " "));
}
System.out.println();
}
Prints the current number, i, and then checks if i has reached the end of a row with modulus. If so, prints a new line character. (Loop starts at 1 and goes to 8 to match the numbers in your output.)
I noticed in your example output there are varying number of spaces as well. Here is a version of the above which achieves this as well:
private static void printNums2b() {
int rowLength = 4;
for (int i = 1; i < 9; i++) {
System.out.printf("%-" + (i % rowLength + 2) + "d" + ((i % rowLength == 0) ? " \n" : ""), i);
}
System.out.println();
}
In short, it uses printf() to format the output and sets the padding on the number to modulus of the position (to account for rows) + 1 (because 0 doesn't work).
One interpretation of your question is that you don't want to print too often. There is no reason we have to print every number by itself. We can accumulate the output and then print it all at once.
Here is a solution using a StringBuilder (standard Java, no extra libraries needed):
private static void printNums3() {
int rowLength = 4;
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 9; i++) {
sb.append(i).append(' ');
if ((i % rowLength == 0)) {
sb.append('\n');
}
}
System.out.println(sb.toString());
}
Puts all the numbers in the StringBuilder, adds a newline at the end after every 4th number and then prints the entire thing at the end.
And again, with varying spaces:
private static void printNums3b() {
int rowLength = 4;
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 9; i++) {
sb.append(String.format("%-" + (i % rowLength + 2) + "d", i));
if ((i % rowLength == 0)) {
sb.append('\n');
}
}
System.out.println(sb.toString());
}
I don't think there is any particular benefit to using arrays. But then again, there are many ways to achieve this output. Since we don't know more about what you really want to achieve, if your array serves some other purpose (I removed the array because it's not needed for the printing) or what type of data you want to print other than numbers, I can't really give more ideas.
Related
Following this question, I want to now code "6 choose 2" times "4 choose 2." By that I mean, lets say I have 6 characters "A B C D E F." The first time I choose any two characters to delete. The 2nd time I want to choose 2 different letters to delete and then I append the results of these two trials. Hence, I will receive 90("6 choose 2" times "4 choose 2") eight character strings. The characters in the pattern are from the same pattern {1,2,3,4,5, 6}. All the characters are unique and no repetition.
Here is what I have so far.
public String[] genDelPatterns(String design){
char[] data = design.toCharArray();
String[] deletionPatterns = new String[15];
int x = 0;
StringBuilder sb = new StringBuilder("");
int index = 0;
for(int i = 0; i < (6-1); i++){
for(int j = i+1; j < 6; j++){
for(int k= 0; k < 6; k++){
if((k != j) && (k != i))
sb.append(String.valueOf(data[k]));
}
deletionPatterns[x++] = sb.toString();
sb = new StringBuilder("");
}
}
return deletionPatterns;
}
public String[] gen8String(String[] pattern1, String[] pattern2){
String[] combinedPatterns = new String[225];
int k = 0;
for(int i = 0; i < 15; i++)
{
for(int j = 0; j < 15; j++)
combinedPatterns[k++] = pattern1[i] + pattern2[j];
}
return combinedPatterns;
}
I will be calling the methods like this:
gen8String(genDelPatterns("143256"), genDelPatterns("254316"));
Currently, I am generating all the possible 8 letter strings. But I want to only generate the 8 character strings according to the aforementioned specifications. I am really stuck on how I can elegantly do this multiplication. The only way I can think of is to make another method that does "4 choose 2" and then combine the 2 string arrays. But this seems very roundabout.
EDIT: An example of an 8 character string would be something like "14322516", given the inputs I have already entered when calling gen8String, (143256,254316). Note that the first 4 characters are derived from 143256 with the 5 and 6 deleted. But since I deleted 5 and 6 in the first trail, I am no longer allowed to delete the same things in the 2nd pattern. Hence, I deleted the 3 and 4 from the 2nd pattern.
you have a chain of methods , each one called a variation itself.
For so, my advice is to use a recursive method!
to achieve your goal you have to have a little experience with this solution.
A simple example of a method that exploits the recursion:
public static long factorial(int n) {
if (n == 1) return 1;
return n * factorial(n-1);
}
I can also suggest you to pass objects (constructed to perfection) for the method parameter, if is too complex to pass simple variables
This is the heart of this solution in my opinion.
While what you tried to do is definitely working, it seems you are looking for other way to implement it. Here is the skeleton of what I would do given the small constrains.
// Very pseudo code
// FOR(x,y,z) := for(int x=y; x<z;x++)
string removeCharacter(string s, int banA, int banB){
string ret = "";
FOR(i,1,7){
if(i != banA && i != banB){
ret += s[i];
}
}
return ret;
}
List<string> Generate(s1,s2){
List<string> ret = new List<string>();
FOR(i,1,7) FOR(j,i+1,7) FOR(m,1,7) FOR(n,m+1,7){
if(m != i && m != j && n != i && n != j){
string firstHalf = removeCharacter(s1,i,j);
string secondHalf = removeCharacter(s2,m,n);
ret.Add(firstHalf + secondHalf);
}
}
return ret;
}
This should generate all possible 8-characters string.
Here is the solution I came up with. Doesn't really take "mathematical" approach, I guess. But it does the job.
//generating a subset of 90 eight character strings (unique deletion patterns)
public static String[] gen8String(String[] pattern1, String[] pattern2){
String[] combinedSubset = new String[90]; //emty array for the subset of 90 strings
String combinedString = ""; //string holder for each combined string
int index = 0; //used for combinedSubset array
int present = 0; //used to check if all 6 characters are present
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
combinedString = pattern1[i] + pattern2[j]; //combine both 4 letter strings into 8 char length string
char[] parsedString = combinedString.toCharArray(); //parse into array
//check if all 6 characters are present
for(int k = 1; k <= 6; k++)
{
if(new String(parsedString).contains(k+"")) {
present++;
}
else
break;
//if all 6 are present, then add it to combined subset
if(present == 6)
combinedSubset[index++] = combinedString;
}
present = 0;
}
}
return combinedSubset;
}
I'm creating a java project called magicsquare and I've searched online on how to do it. Now, I'm trying to understand how the 2nd loop works, I know that it prints and align the magic square, but I don't know the details. I already know the first one. I would really appreciate if someone explains to me the 2nd loop. Thanks!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
Well, first the obvious. The part about < 10 and < 100: if a number is between 0 and 9, it's only going to print out one digit. If it's between 10 and 99, it's going to print out two. And if it's between 100 and 999, it'll print out using three digits. (It seems as if this code is written to assume it will only encounter numbers between 0 and 999. Generally speaking, it's best to ensure that somehow rather than just hope.)
So, with the if statements and their extra spaces, a "5" will print out as " 5" (note the two leading spaces for a total of three characters). 25 will print out as " 25" (again, three characters) and 125 as "125" (three digits again). Since all of the numbers print out using three characters, everything will line up neatly in columns.
What confuses me is that you're iterating over c first, then r. This seems to say that you're printing out the first column on a single row on the screen, then the second column as a second row, and the third column as a third row. I.e. the whole thing has been rotated on a diagonal. But maybe that's just a naming issue.
I am trying to format the output from what I have written to display a list of primes (Eratosthenes) to a certain number results per line. Do they need to placed into an Array to accomplish this? I have not come across a way to implement their division besides .split("");, which would render a single line for each and the Oracle site's System.out.format(); argument index to specify length. Yet, these require the characters to be known. I am printing it with the following, which of course creates an infinite line.
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
System.out.print(count + ", ");
}
}
Is there a way to simply call System.out.print("\n"); with an if(...>[10] condition when System.out.print() has run for instance 10 times? Perhaps I am overlooking something, relatively new to Java. Thanks in advance for any advice or input.
By using a tracker variable, you can keep track of how many items have been displayed already so you know when to insert a new line. In this case, I chose 10 items. The exact limit is flexible to your needs.
...
int num = 0;
//loop
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
if (num == 10) { System.out.print("\n"); num = 0; }//alternatively, System.out.println();
System.out.print(count + ",");
num++;
}
}
...
You can just simply create some int value e.g.
int i = 1;
...and increment it's value everytime Sysout is running.
Something like this:
int i = 1;
for (int count = 2; count <= limit; count++) {
if (!match[count]) {
if (i%10 == 0)
System.out.print(count+ "\n");
else
System.out.print(count + ", ");
i++;
}
}
Try this:
int idx=1;
int itemsOnEachLine=10;
for(int count = 2; count <= limit; count++)
{
if(!match[count])
{
System.out.print(count+(idx%itemsOnEachLine==0?"\n":","));
idx++;
}
}
you go increasing a counter (idx) along with every write, every 10 increments (idx modulus 10 == 0), you will be printing a new line character, else, a "," character.
My problem requires me to create a list of all 20 amino acids permutations based on a user imputed chain length. For example, I currently have code that works if the user wants a 3 chain length. This is 20^3 possibilities. So I have 3 nested for loops that run through all possibilities, then a counter that outputs the number of permutations to make sure the answer is correct. How could I code this method so it output permutations based on user input?
protected void getPermutations(int chainlength) {
int counter = 0;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
for (int k = 0; k < 20; k++) {
System.out.println(AcidArray[i].getTcode() + "-"
+ AcidArray[j].getTcode() + "-"
+ AcidArray[k].getTcode());
counter++;
}
}
}
System.out.println("chain length = " + chainlength);
System.out.println(counter + " permutations");
}
Thanks
Recursion is your friend in this situation
protected String getPermutations(int chainlength) {
int counter = 0;
if(chainlength > 0) { // so that the counter is not 1
counter = getSubPermutations("", chainlength));
}
System.out.println("chain length = " + chainlength);
System.out.println(counter + " permutations");
}
private int getSubPermutations(String prefix, int chainlength){
if(chainlength == 0){ //The bottom of the stack, print out the combination
System.out.println(prefix.substring(0,prefix.length-1)); //remove the final '-'
return 1;
} else {
int counter = 0
for(int i = 0; i < 20; i++) {
//Add this level T code to the string and pass it on
counter += getSubPermutations(prefix + AcidArray[i].getTcode() + "-", chainlength-1);
}
return counter;
}
}
What this will do is make a tree of calls. If chainlength is one then it will call getSubPermutations with 1. This will run through the for loop calling getSubPermutations again with the String for the first value and a chainlength of 0. In this case the string will only have one T code in it. Each inner call will hit the first if statement so it will print out the string containing one T code and return 1. All these will be added up so the counter returned to getPermutations will be 20. By this stage all the permutations will have been printed out.
As chain length increases getSubPermuations is called recursively. With a chainlength of 2 it will call getSubPermutations 20 times with a chain length of 1, passing in the string of the T code. Each of these will call getSubPermutations with a chainlength of 0, with a string containing two T codes. This will then print out the full string and return 1. These return values will get added up to 20 as in the previous example but now when they are returned to the next level they are added up to return a final 400 to getPermutations and 400 Strings will have been printed.
I am pretty new to Java and I have a little problem with formatting a String. I have add "\n" for a new line after every 18th char and I have to split these new lines into array indexes, 13 lines for each index.
My code so far:
String[] strings = str.split("\n");
String result;
for (int i = 1; i < strings.length; i++) {
i++;
if ((i % 13) == 0) {
result += strings[i];
} else {
result += strings[i] + "\n";
}
}
It doesn't work as it should, I tested a bit around bit I don't know how to do this, could someone help me please?
You're incrementing i twice in each loop - once in the increment expression of the for statement, and once inside the loop itself. This means i is always even, so i % 13 is probably not 0 when you expect it to be. In addition, the first index of an array is 0, so you would currently ignore the first element. As a more minor point, I would advise using a StringBuilder instead of appending Strings:
String[] strings = str.split("\n");
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < strings.length; i++) {
String s = strings[i];
if ((i % 13) == 0) {
resultBuilder.append(s);
} else {
resultBuilder.append(s).append("\n");
}
}
String result = resultBuilder.toString();