alignment of table in array java [duplicate] - java

This question already has answers here:
Output in a table format in Java's System.out
(8 answers)
Closed 7 years ago.
My code is this:
// for loop for displaying multiple values
for (int index = 0; index < 5; index++) {
System.out.println("\t\t" + name[index] + "\t\t\t" + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " ");
}
This is the current output, but I want to display output with same spacing
Sales and Commission
======================================================
Salesperson Sales Amount Commission
-----------------------------------------------------
u ujuhygtfd $89000 $8900.0
uh uh $87000 $8700.0
t t $65000 $5200.0
f f $54000 $4320.0
u r $43000 $2580.0
Total: 9 Data entries
How can I display my data like this?
Sales and Commission
======================================================
Salesperson Sales Amount Commission
-----------------------------------------------------
u ujuhygtfd $89000 $8900.0
uh uh $87000 $8700.0
t t $65000 $5200.0
f f $54000 $4320.0
u r $43000 $2580.0
Total: 9 Data entries

As said in this answer (slightly modified):
Use System.out.format. You can set lengths of fields like this:
System.out.format("%32s%10d%16d", name[index], sales[index], comm[index]);
This pads name[index], sales[index], and comm[index] to 32, 10, and 16 characters,
respectively.
See the Javadocs for java.util.Formatter for more information on the
syntax (System.out.format uses a Formatter internally).

You could do something like
for (int index = 0; index < 5; index++) { // for loop for displaying multiple values
int numOfSpaces = 20 - name[index].length();
String spaces = "";
for (int i = 0; i<numOfSpaces; i++)
spaces += " ";
System.out.println("\t\t" + name[index] + spaces + "$" + sales[index] + "\t\t\t" + "$" + comm[index] + " ");
}
And change the arbitrary 20 to anything you want, eg. the longest string in names + 5.

Related

How do I sum string arrays in java

I am creating a simulated test that is ready to be graded. My main module request user input of 20 multiple choice answers (A,B,C,D). I am using a for loop to populate both arrays. I next have an If .equals statements that compares the two arrays for correct answer and in correct answer. `
My current out put is:
The correct answer to question 16 is: C
Your answer to question 16 is: C
Question 16 is correct
The correct answer to question 17 is: C
Your answer to question 17 is: A
Question 17 is incorrect
Next
I am attempting to simulate an out put of:
You passed the exam with a grade of 90%. Congratulations!
Number of correct answers: 18
Number of incorrect answers: 2
Here is the portion of code I am working on
int arraySize;
arraySize = 20;
// Declare and assign the variables to create the parallel array
int count;
// Access the contents of both arrays
for (count = 0; count <= arraySize - 1; count++) {
System.out.println();
// Message to diplay the Answerkey and testAnswer
System.out.println("The correct answer to question " + (count + 1) + " is: " + answerKeyArray[count]);
System.out.println("Your answer to question " + (count + 1) + " is: " + testAnswers[count]);
// Find the correct and incorrect answers
if (answerKeyArray[count].equals(testAnswers[count])) {
// Message to display the answer is correct
System.out.println("Question " + (count + 1) + " is correct ");
} else {
// Message to display the answer is incorrect
System.out.println("Question " + (count + 1) + " is incorrect ");
you can make a counter variable inside the for loop, which would make it a local variable, and it would be voided after it goes outside the for loop. Below is an example
for(int i = 0; i < arraySize; i++){
int correctCounter = 0;
int incorrectCounter = 0;
if(PretendThisIsAConditional){
counter++;
}
else{
incorrectCounter++;
System.out.println("Number of correct answers: " + correctCounter + "Number of incorrect answers: " + incorrectCounter);
}
If you have the number correct inside a string for whatever reason you can do
int numCorrect = Integer.parseInt(String);

How to print multiple variables from different methods?

I want to create a print statement that displays three values. 1) Counter variable which shows number of iterations. 2) Array recorder which records the values of the elements and 3) the value of these elements + 5.
There is a change method which takes all of the values in the array and adds 5 to them. I just can't understand how to print this value in line with the counter variable and Array Element counter. Is this possible to do?
int sam[] = {1,2,4,5,6,4,3,67};
change(sam);
for (int y:sam) {
for(int counter =0; counter<sam.length;counter++) {
//this is where I wish to print out the 3 elements
System.out.println(counter+ "\t\t" + sam[counter]+y);
}
}
public static void change(int x []) {
for(int counter=0; counter<x.length;counter++)
x[counter]+=5;
}
Everything is fine except that sam[counter] + y is evaluated as integer value because both arguments are integers. You need string concatenation instead:
System.out.println(counter + " " + sam[counter] + " " + y);
Or something like this (using formatter):
System.out.printf("counter = %d, sam[counter] = %d, y = %d\n", counter, sam[counter], y);
%d is a decimal argument, \n is a new line.
EDIT: Regarding your code. If you want to ouput the following row format for each element in the array
counter sam[counter] sam[counter] + 5
then just use
int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] + 5));
}
This will print values in needed format.
0 1 6
1 2 7
2 4 9
...
Or, if you want to change array, but be able to print old values, try this:
int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] += 5));
}
Here (sam[counter] += 5) will increment each elemnent by 5 and return the new value.
Get rid of this outer loop for (int y:sam)
This should work:
for(int counter =0; counter<sam.length;counter++) {
System.out.println(counter+ "\t\t" + sam[counter]+ "\t\t" + counter + sam[counter] + 5);
}
Your question was a little hard to interpret, but just drop the outer loop, and don’t “+y”
Scratch that. What do you think the change routine did for you? Did you want an array with the original value and another array with the changed value, and then have access to both of those arrays?

String with 1000 digits, find the biggest 5 digits without an array

I know my code can be simpler and more efficient... My code is supposed to grab the biggest set of 5 digits. It works, except it only is grabbing 3 digits, what would i need to modify to change that?
public class thousandDigits {
public static void main(String[] args) {
int greatest = 0;
String num = ("73167176531330624919225119674426574742355349194934"
+ "96983520312774506326239578318016984801869478851843"
+ "85861560789112949495459501737958331952853208805511"
+ "12540698747158523863050715693290963295227443043557"
+ "66896648950445244523161731856403098711121722383113"
+ "62229893423380308135336276614282806444486645238749"
+ "30358907296290491560440772390713810515859307960866"
+ "70172427121883998797908792274921901699720888093776"
+ "65727333001053367881220235421809751254540594752243"
+ "52584907711670556013604839586446706324415722155397"
+ "53697817977846174064955149290862569321978468622482"
+ "83972241375657056057490261407972968652414535100474"
+ "82166370484403199890008895243450658541227588666881"
+ "16427171479924442928230863465674813919123162824586"
+ "17866458359124566529476545682848912883142607690042"
+ "24219022671055626321111109370544217506941658960408"
+ "07198403850962455444362981230987879927244284909188"
+ "84580156166097919133875499200524063689912560717606"
+ "05886116467109405077541002256983155200055935729725"
+ "71636269561882670428252483600823257530420752963450");
for (int n = 0; n < num.length() - 5; n++) {
greatest = ((num.charAt(n)) + (num.charAt(n+1)) + (num.charAt(n+2)) + (num.charAt(n+3))
+ (num.charAt(n+4)));
if (greatest > n) {
n = greatest;
}
}
System.out.print(greatest);
}
}
OUTPUT:
357
I think you want to use String.substring(int, int) to iterate all possible 5 character substrings, and then you might use Math.max(int, int) to update greatest. Something like
int greatest = Integer.MIN_VALUE;
for (int i = 0; i < num.length() - 4; i++) {
// int value = Integer.parseInt(num.substring(i, i + 5));
int value = Integer.parseInt(String.valueOf(num.charAt(i))
+ num.charAt(1 + i) + num.charAt(2 + i) + num.charAt(3 + i)
+ num.charAt(4 + i));
greatest = Math.max(greatest, value);
}
System.out.println(greatest);
I get 99890.
I think you are trying to add 5 consecutive characters to get sum, and store starting index of highest sum.
But you should be using Character.getNumricValue(char) to convert (num.charAt(n)) to numeric value and then add.
greatest = Character.getNumericValue((num.charAt(n)) + Character.getNumericValue((num.charAt(n+1)) + Character.getNumericValue((num.charAt(n+2)) +
Character.getNumericValue((num.charAt(n+3)) +
Character.getNumericValue((num.charAt(n+4));
You need a valirable to store old value to compare and index
if(greatest > oldGreatest) {
index = n;
}
Then finally print using index out side loop:
System.out.print((num.charAt(index)) + (num.charAt(index+1) + (num.charAt(index +2)) + (num.charAt(index +3)) + (num.charAt(index +)));
Although #ElliottFrisch and #dave provides more elegant answer, I tried to modify from your original version and here is my code (I have tested it):
public class ThousandDigits {
public static void main(String[] args) {
int greatest = 0;
String num = ("73167176531330624919225119674426574742355349194934"
+ "96983520312774506326239578318016984801869478851843"
+ "85861560789112949495459501737958331952853208805511"
+ "12540698747158523863050715693290963295227443043557"
+ "66896648950445244523161731856403098711121722383113"
+ "62229893423380308135336276614282806444486645238749"
+ "30358907296290491560440772390713810515859307960866"
+ "70172427121883998797908792274921901699720888093776"
+ "65727333001053367881220235421809751254540594752243"
+ "52584907711670556013604839586446706324415722155397"
+ "53697817977846174064955149290862569321978468622482"
+ "83972241375657056057490261407972968652414535100474"
+ "82166370484403199890008895243450658541227588666881"
+ "16427171479924442928230863465674813919123162824586"
+ "17866458359124566529476545682848912883142607690042"
+ "24219022671055626321111109370544217506941658960408"
+ "07198403850962455444362981230987879927244284909188"
+ "84580156166097919133875499200524063689912560717606"
+ "05886116467109405077541002256983155200055935729725"
+ "71636269561882670428252483600823257530420752963450");
int max = -1;
for (int n = 0; n < num.length() - 4; n++) {
greatest = ((num.charAt(n) - '0') * 10000 + (num.charAt(n + 1) - '0') * 1000
+ (num.charAt(n + 2) - '0') * 100 + (num.charAt(n + 3) - '0') * 10 + (num.charAt(n + 4) - '0'));
if (max < greatest) {
max = greatest;
}
}
System.out.print(max);
}
}
I think you'll find it's not grabbing three digits, but rather the sum of the six characters you are pulling out is a 3-digit number.
If you're after the largest five digit number, you need to extract five digits (not six) as you do and assign them a weight. So the first digit must be multiplied by 10,000, the second by 1,000 and so on.
But there's more: you're are getting the character at an index within your string. This is not what you want as it is not the same as the numeric value of that character. For that you need:
num.charAt(n) - '0'
These changes should allow you to correct your algorithm as it stands.
A more efficient approach would be to extract 5-digit sub-strings and convert them to integers. The first one would be:
Integer.parseInt(num.subString(0, 5));
You can iterate to get each one to find the greatest.

How to improve the efficiency of the algorithm while using Iterator in java?

This is the question:
There are N boys and N girls. Only a boy and a girl can form a dancing pair (i.e. no same sex dancing pairs are allowed). The only other condition in making pairs is that their absolute difference in height should be less than or equal to K.
Find the maximum number of pairs that can be formed so that everyone has a unique partner.
I want to improve my algorithm to take less time..
first see the code:
//k is the maximum difference between pairs
int k = 5;
ArrayList<Integer> ArrBoys = new ArrayList<>(Arrays.asList(new Integer[]{28, 16, 22}));
ArrayList<Integer> ArrGirls = new ArrayList<>(Arrays.asList(new Integer[]{13, 10, 14}));
//sorting all arrays
Collections.sort(ArrBoys);
Collections.sort(ArrGirls);
System.out.println("After Sorting");
//printing arrays after sorting
for (Integer ArrBoy : ArrBoys) {
System.out.print(ArrBoy + " ");
}
System.out.println("");
for (Integer ArrGirl : ArrGirls) {
System.out.print(ArrGirl + " ");
}
System.out.println("");
//algorithm used to find the number of pairs
int count = 0;
for (Iterator<Integer> iteB = ArrBoys.iterator(); iteB.hasNext();) {
Integer ArrBoy = iteB.next();
for (Iterator<Integer> iteG = ArrGirls.iterator(); iteG.hasNext();) {
{
Integer ArrGirl = iteG.next();
int dif = (int) Math.abs(ArrBoy - ArrGirl);
if (dif <= k) {
System.out.println("we took " + ArrBoy + " from boys with "
+ ArrGirl + " from girls, thier dif < " + k);
ArrBoys.remove(ArrBoy);
ArrGirls.remove(ArrGirl);
iteB = ArrBoys.iterator();
count++;
break;
} else {
System.out.println("we try " + ArrBoy + " from boys with " + ArrGirl + " from grils but thier dif > " + (int) k);
//ArrGirls.remove(ArrGirl);
}
}
}
}
System.out.println("the number of pairs we can take is "+count);
the output of this code is:
As you see this algorithm inefficient since we don't need to start comparing the height from the first girl for the second boy, we should go to the girl which come after the previous girl we took as pair.
For example:
in the boy with 22 height, the algorithm must start comparing the boys'height with the girl with 14 height, because we already sort them, if the first boy (shorter) cant make a pair with the first girl so definitely the second boy (longer) cant also, we waste the time if we compare from the first girl.
We can solve this problem by two choices, either by making the iterator start with the girl after the previous boy has been stopped (i don't know how to do it with iterator), or by removing the girl from the arraylist once if it's not satisfy the condition and let the loop start with first girl (i tried this but it gives me an exception)
Solve it by these two ways if you can...
You have to add more conditions. Here it is, there are three options :
abs(dif) <= k : they can dance together
dif > k : even the current boy (the smallest) is too tall for her, no one can dance with her, exclude her
dif < -k : the first girl is far too tall for him, exclude him
Here is the code:
int count = 0;
int gLimit = 0;
for (int b = 0; b<ArrBoys.size();b++) {
if(gLimit == ArrGirls.size()) {
System.out.println("no more girl for boy " + ArrBoys.get(b));
}
for (int g = gLimit; g<ArrGirls.size();g++) {
{
int dif = ArrBoys.get(b) - ArrGirls.get(g);
if (Math.abs(dif) <= k) {
System.out.println("we took " + ArrBoys.get(b) + " from boys with "
+ ArrGirls.get(g) + " from girls, thier dif < " + k);
gLimit++;
count++;
break;
} else if (dif > k) {
System.out.println("we try " + ArrBoys.get(b) + " from boys with " + ArrGirls.get(g) + " from grils but thier dif > " + (int) k + ", girl too small, excluded");
gLimit++;
} else if (dif < -k) {
System.out.println("we try " + ArrBoys.get(b) + " from boys with " + ArrGirls.get(g) + " from grils but thier dif > " + (int) k + ", boy too small, excluded");
break;
}
}
}
}
I used get index for more maniability on lists content
Here is the ouput
After Sorting
16 22 28
10 13 14
we try 16 from boys with 10 from grils but thier dif > 5, girl too small, excluded
we took 16 from boys with 13 from girls, thier dif < 5
we try 22 from boys with 14 from grils but thier dif > 5, girl too small, excluded
no more girl for boy 28
the number of pairs we can take is 1

Ignore certain values from a file in Java

My content data in Notepad is 1 to 25. How can I display the data that is marked in red below. The other values can be ignored.
change
int i = sc.nextInt();
System.out.println(i + " ");
to
int i = sc.nextInt();
if(i%10 <= 5) {
System.out.println(i + " ");
}
Idea is that i%10 will give the unit digit of a number. So if it is <= 5 print that number.

Categories