How to use printf to print out in a certain format - java

How do I use the command printf to print my output the same way in the attached output file?
this is my code currently:
else if (args[0].equals("fib")) {
for (int i = 0; i < (Integer.parseInt(args[1]) + 1); ++i) {
System.out.println(getFib(i));
}
}
How do i change it to make it print like the attached picture?
Thank you guys for your help!

Here is an example.
Instead of instant printing add all numbers into a list:
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= number; i++) {
numbers.add(fibonacci(i));
}
Then make a pattern for printf():
String pattern = "%" + (numbers.get(numbers.size()-1).toString().length() + 10) + "d";
where (numbers.get(numbers.size()-1).toString().length() + 10) is the sum of the number of characters in the largest number plus 10 spaces between columns.
Then print all elements of the list. The counter is needed in order to have no more than 6 columns:
int counter = 0;
for (Integer integer : numbers) {
if (counter == 6) {
System.out.println(" ");
counter = 0;
}
System.out.printf(pattern, integer);
counter++;
}

Related

how to match the index value in LinkedList

so this a part of my code containing my LinkedList. How can I find the match in my set of numbers.
LinkedList <Integer> mylist = new LinkedList<> ();
for(int i : 1; i<=5; i++){
System.out.println("Process " + i + has :);
int numINPUT = scan.nextint();
mylist.add(numINPUT);
}
My desired output is:
Process 1 has : 3
Process 2 has : 4
Process 3 has : 1
Process 4 has : 5
Process 5 has : 2
Matched : Process 1 and Process 3.
A brute force thing could look like this:
for (int i=0; i<mylist.size(); i++) {
int pointingToIndex = mylist.get(i);
if (pointingToIndex > 0 && pointingToIndex < mylist.size) {
int pointedTo = mylist.get(pointingToIndex);
if (pointedTo == i) {
System.out.println("match for index: " + i + " and " + pointingToIndex);
}
}
}
you simply iterate your list; and for each index you check if the value on that index is another valid index
if so, you fetch the value for that other index, and then you check for a match
you might need some additional "marker" to avoid printing duplicates (I think my solution will print 1-3, and then 3-1 later on)
and yes, this is not exactly printing what you ask for - but should give you enough to get going and finish your homework yourself
Besides: look into your naming. mylist says ... nothing. Why not call it numbers or maybe processIDs or something like that?
You just have to compare all pairs of list items. If an index of one item equals the value of another one and vice versa, you have a match. Keep in mind, that Java indices start with 0, your indices start with 1.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
LinkedList <Integer> mylist = new LinkedList<> ();
for(int i = 1; i<=5; i++){
System.out.print("Process " + i + " has: ");
int numINPUT = scan.nextInt();
mylist.add(numINPUT);
}
for(int i = 0; i < mylist.size(); i++) {
for(int j = i + 1; j < mylist.size(); j++) {
int value1 = mylist.get(i);
int value2 = mylist.get(j);
if(value1 == (j + 1) && value2 == (i + 1)) {
System.out.println("Matched : Process " + (i + 1) + " and Process " + (j + 1) + ".");
}
}
}
}

Arithmetic that takes three command-line arguments and output required as java Arithmetic: 3 + 2 = 5

class CommandLineArgs {
public static void main(String args[]) {
int l = args.length;
int sum = 0;
for (int j = 0; j < l; j++) {
sum = Integer.parseInt(args[j]) + sum;
}
System.out.println("The Sum of All Elements entered at command line is : " + sum);
}
}
I tried using arguments but not able to do in using function as my required output is a=number1 and b=number2 and c=operator (+,-,/,*). Please help me in writing the program.
You need to use a case or if statement.
if(args[2].equalsIgnoreCase("+")
{
sum = Integer.parseInt(args[0]) + Integer.parseInt(args[1]);
}
else if(args[2].equalsIgnoreCase("*")
{
sum = Integer.parseInt(args[0]) * Integer.parseInt(args[1]);
}
etc...
you can use array for this
String[] arr= new String[l]; create a string array
for(int j=0;j<l ;j++){
arr[j] = args[j];// first of all store all inputs in the array
}
for(int i=0;i<arr.length;i++){
// then iterate over the array and check for the last char of array
if(arr[2].equalsIgnoreCase("+"){
sum = Integer.parseInt(arr[0]) + Integer.parseInt(arr[1]);
System.out.println("The Sum of All Elements entered at command line is : " + sum);
}else if(args[2].equalsIgnoreCase("*")
{
code for multiplication
}
}

Using FOR loop and summing values between rounds in Java

this is my task:
"Write program LoopForNumberSum.java. Display only every second number, starting from 2, to the screen and sum in parenthesis between the last round and current round so far. The looping range is defined in separate variables. Use FOR-loop to solve the problem."
This is the code I have so far:
public class LoopForNumberSum {
public static void main(String args[]) {
int min = 2;
int max = 10;
for(int i = min; i <= max; i+=2) {
int j = i+i;
System.out.println(i + "(" + j + "), ");
}
}
}
^This code prints:
2(4),
4(8),
6(12),
8(16),
10(20),
But I need the number in the parenthesis to start from 2 and the rest would need to be 6, 10, 14 and 18. Like this: "2(2), 4(6)..."
Try:
int sum = 0;
for(int i = 2 ; i <= 10 ; i += 2) {
sum += i;
System.out.println(i + "(" + sum + "), ");
}

Array Out of Bound Index Error

I am attempting to find the occurrence frequency of a number in a sequence.
for example when sequence is :
1, 1, 3, 4
output should be
1 found 3 times
, 3 found 1 times
, 4 found 1 time
and so on. I have the following code
import java.util.*;
class fre {
public static void main(String a[]) {
int c = a.length;
int d[] = new int[c];
int num = 0;
for (int p = 0; p < c; p++)
d[p] = Integer.parseInt(a[p]);
for (int z : d)
System.out.println(z);
for (int i = 0; i < c - 1; i++) // FROM THIS LINE ERROR IS THROWN
{
for (int t = 0; t < c - 1; i++) {
if (d[i] == d[t]) {
num++;
}
}
System.out.println("the element" + i + "found" + num + "times");
}
}
}
ERROR : ARRAY OUT OF BOUND INDEX
Shouldn't
for (int t = 0; t < c - 1; i++)
be
for (int t = 0; t < c - 1; t++)
You are incrementing i again in the second loop.
Well, first of all, you increment i instead of t in the inner loop.
Changing this, the program seems to work.
Change the output line to sth. like
System.out.println("the element " + d[i] + " found " + num + " times");
To make it readable.
Not saying there is no better way to solve this...
ok
Benno
a is an array that holds all the command line parameters. You are using a.length which determines the amount of command line parameters given. I guess you probably want to pass the length of the array by a command line parameter instead. If I am correct, you should use something like int c = a[0]; to get the first command line parameter. Of course that is not good style without any checks, but if I get started on that I had to rewrite your whole code ;)
Your example is wrong.
Untested:
public static void main(String args[])
{
Map<Integer, Integer> result = new HashMap<>();
for (String s : args) {
Integer currentNumber = Integer.parseInt(s);
// don't forget error handling if s is not a number
Integer currentCount = result.get(currentNumber);
if (currentCount == null) { // you could also check with result.containsKey(..)
currentCount = 0;
}
result.put(currentNumber, currentCount + 1);
}
for (Map.Entry<Integer, Integer> entry : result) {
System.out.println("The element: " + entry.getKey() + " found " + entry.getValue() + " times");
}
}
This is probably slower than your version, but easier to understand.

Loop through a counting String value [duplicate]

This question already has answers here:
How to format numbers to same number of digits, 0-padded?
(3 answers)
Closed 9 years ago.
I must display all server names in the range of v10000 up to v10500.
Below is the code that I tried, but sometimes it displays a zero.
String template = "v10";
int count = 0;
while (count < 501) {
String number;
if (count < 100) {
number = "00" + Integer.toString(count);
} else if(count < 10) {
number = "0" + Integer.toString(count);
} else {
number = Integer.toString(count);
}
String server = template + number;
System.out.println(server);
count++;
}
But when I show this solution to my boss, he just laughs and says:
I can do this better.
How can I alter my code to make it work properly? I'm new to Java.
I would do
for(int i = 10000; i <= 10500; i++)
System.out.println("v" + i);
It is a very long way. Better use String.format()
A working solution for you would be:
for (int i = 0; i <= 500; i++) {
String server = String.format("v10%03d", i);
System.out.println(server);
}
The format String is builded like that:
v10 -> your String template of the server
%0 --> the zeros you need
3d --> three digits will be added
So your int i will be formatted like that.
Every other answers suggest a better approach to this problem. I was going myself to suggest to use format, but a loop starting from 10000 is fine too:
for (int i = 0; i <= 500; i++) {
String server = String.format("v10%03d", i);
System.out.println(server);
}
or simply (and faster):
for(int i = 10000; i <= 10500; i++) {
System.out.println("v" + i);
}
But I think that we should also fix the bug in OP's code:
while (count < 501){
String number;
if(count < 100){
number = "00" + Integer.toString(count);
}else if(count < 10){
number = "0" + Integer.toString(count);
}else{
number = Integer.toString(count);
}
String server = template + number;
System.out.println(server);
count++;
}
I would recommend using a for-loop instead but that's not the problem. The problem is the order of the tests. if count < 100 is false, then count < 10 is also false. You will never enter this block. Switch the order of your if statements.
So the fixed code:
for (int count = 0; count <= 500; count++){
String number;
if(count < 10){
number = "00" + Integer.toString(count);
}else if(count < 100){
number = "0" + Integer.toString(count);
}else{
number = Integer.toString(count);
}
String server = template + number;
System.out.println(server);
}
Just use a for loop:
for(int i = 10000; i <= 10500; i++)
System.out.println("v" + i);
String template = "v";
for(int i=10000;i<=10500;i++){
System.out.println(template+i);
}
Use String.format inside a for loop:
for (int i = 10000; i <= 10500; ++i) {
System.out.println(String.format("v%d", i));
}
This will count through those integers and prepend a "v" to each.
You can do a for from 10000 to 10500 and convert that int (or whichever numeric type you use) to String using a variety of solutions, e.g. Integer.toString().
Then you can concatenate "v" and your result using a StringBuilder.

Categories

Resources