java using printf for arrays [duplicate] - java

This question already has answers here:
Java: return 2D Array with very varying entry lengths as formatted string
(2 answers)
Closed 9 years ago.
I have a question on how to use printf on arrays. In my case, I displayed arrays by using import java.util.Arrays; and displayed them by Arrays.toString(). Or is it not possible with this method for displaying arrays, like do I need to use printf on arrays that are displayed by for loops? Any help will be greatly appreciated. Below is what I did in code:
public static void printResults(String[] name, double[] radius, double[] mass, double gravity[])
{
// fill in code here
System.out.println(Arrays.toString(name));
System.out.println(Arrays.toString(radius));
System.out.println(Arrays.toString(mass));
System.out.println(Arrays.toString(gravity));
}
and I called it in the main method like this:
printResults(names, radii, masses, gravities);
below is the output of my program when I execute it:
run:
[Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto]
[2439.7, 6051.9, 6378.0, 3402.5, 71492.0, 60270.0, 25562.0, 24774.0, 1195.0]
[3.3022E23, 4.8685E24, 5.973600000000001E24, 6.4185E23, 1.8986000000000002E27, 5.6845999999999996E26, 8.681E25, 1.0243E26, 1.312E22]
[3.700465457603474, 8.8661999605471, 9.794740681676519, 3.697967684866716, 24.776754466506414, 10.43814587026926, 8.861473215210253, 11.131680688084042, 0.6128071987535232]
BUILD SUCCESSFUL (total time: 3 seconds)
I want to display it so that the number align with the names of the planets and limit the decimal place values to only 2 place values after the decimal (3.14)

This may be helpful for your needs.
public static void printResults(String[] name, double[] radius, double[] mass, double gravity[]){
DecimalFormat decimalFormat=new DecimalFormat("#0.00");
if(name!=null && radius!=null
&& mass!=null && gravity!=null){
if(name.length==radius.length
&& radius.length==mass.length
&& mass.length==gravity.length){
for(int i=0;i<name.length;i++){
System.out.println("Name="+name[i]);
System.out.println("Radius="+decimalFormat.format(radius[i]));
System.out.println("Mass="+decimalFormat.format(mass[i]));
System.out.println("Gravity="+decimalFormat.format(gravity[i]));
System.out.println();
}
}
}
}
Sample Output:
Name=Mercury
Radius=10.56
Mass=5.12
Gravity=1054.12
Name=Venus
Radius=10.67
Mass=10.45
Gravity=10.24

Option 1
for (int index = 0; index < blam.length; ++index)
{
String formattedOutput = String.format("format string", objects...);
System.out.println(formattedOutput);
}
Reading assignment: String API Page
Option 2
for (int index = 0; index < blam.length; ++index)
{
System.out.printf("format string", objects...);
}
Reading assignment: PrintWriter API Page

Yes you need to loop through the arrays unto length of array and use System.out.format method as #Keppil told.

Related

ThreadLocalRandom double 2 decimal

I try to print my Array Double with only 2 decimals. But I can not find in google how to do. Please any help?
package com.company;
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
public class java_05_16_05_01 {
public static void main(String[] args){
ArrayList<Double> salary=new ArrayList<Double>();
int NumberPersonSurveyed = ThreadLocalRandom.current().nextInt(1, 10+1);
for(int i=0; i<NumberPersonSurveyed; i++){
double salaryPerson = ThreadLocalRandom.current().nextDouble(1000, 10000+1);
salary.add(salaryPerson);
}
System.out.println(salary);
}
}
Actually the OUTPUT is:
[9803.056390825992,
2753.180103177606,
2602.5359323328644,
3319.2942269101018]
But I Expect:
[9803.056,
2753.18,
2602.53,
3319.29]
Note I want use ThreadLocalRandom instance of Math.random or similar.
Thanks so much!
Since you are simulating salaries, you could simply generate int values, which will be in cents, and then divide by 100 (and convert to double) to get your result.
Like so:
double salaryPerson = ThreadLocalRandom.current().nextInt(100 * 1000, 100 * (10000 + 1)) / 100d;
This approach frees you from string formatting issues, and also allows you to process your data with the exact values if you wish to perform extra operations besides printing.
There are 2 ways of doing this, the most common way I have seen is based off of the C style printf.
System.out.printf("%.2f", sal);
printf uses modifiers determined by % operators. This one specifies that it should print floating point number (the f) with 2 decimal places (the .2). You can find a list of operators here.
Personally I prefer the C# styled MessageFormat
System.out.println(MessageFormat.format("{0,number,0.00}", sal));
MessageFormat backends off of DecimalFormat which represents a number in contexts of # and 0, where a # represents a potential but not required number, while a 0 represents a required number. Which is to say if you pass 10 into the specified format it would print 10.00.
Edit:
Just realized it was an ArrayList; you're going to have to iterate through each member of the array and print them out individually.
boolean USE_PRINTF = false;
System.out.print("[");
for(int i = 0; i < salary.size(); ++i)
{
if(USE_PRINTF) { System.out.printf("%.2f", salary.get(i)); }
else { System.out.print(MessageFormat.format("{0,number,0.00}", salary.get(i))); }
if(i < salary.size() - 1) { System.out.print(", "); }
}
System.out.println("]");

Is it possible to stream double values from an array using scanner?

I have a method that needs single values as the input, but I only have the information in an array. I have searched and found out that Scanner can stream values but only in string form. So I thought I should change the array into string and then convert it back into double before returning the value.
Here is what I had written.
double E;
public double StreamValue (double[]g2){
Scanner s = new Scanner(Arrays.toString(g2)); //PROBLEM HERE
while (s.hasNext()){
E = Double.parseDouble(s.next());
}
return E;
}
When I ran the code, it failed. My question is, is the idea right but I'm missing any part, or it's completely invalid?
Edited:
I need to feed the streaming values into a methode that will analyze each values and return an int.
This is kind of a short example of it:
public int EventAnalyzer(double E) {
if (E > c_max)
a = 0;
else
a = 1;
return a;
}
The returned value will be used for this method:
private void isDetected (int a){
CharSequence t0 = "No breathing";
CharSequence t1 = "Normal breathing";
TextView textView = (TextView)findViewById(R.id.apnea);
if(a==0)
textView.setText(t0);
if(a==1)
textView.setText(t1);
}
I think, your idea is right.
But your result E must be an array of double:
double[] E;
Your goal is not completely clear to me, but
if you have double[] g2:
You can use an enhanced for-loop:
for(double d : g2)
System.out.println("This is a double from array: "+ d);
If you need to return one double from the array, then you can retrieve it using the index by doing
return g2[x];
where x is a valid index between 0 and g2.length - 1.
#Alexander Anikin had answered the question in the comment. I'm working on the Arrays.stream but it requires API 24 while I have API 19. I'm looking for other way possible. Thanks everyone for the responses!

Displaying arraylist of objects containing one attribute whose value is superior to a certain value

I am trying to display an arraylist of recordings for mountain climbing where the mountain height was superior to 5K.
I am invoking an object method getheight() from another class but every time I try to compile, I am told that double can't be dereferenced. what am I doing wrong here? is there a better way of displaying a arraylist of objects containing an attribute whose value is superior to a certain number in Java? I have a feeling that I am close but yet far off the target. any tips?
public void Displayrecording()
{
double highestheights;
for(int i=0; i< 5; i++)
if(highestheights.getheight() > 5)
{
System.out.print(records.get(i));
}
}
A double is just a number. It does not have a height, or anything else. It's just a number.
So all you need is highestheights > 5.
If getHeight is going to give you altitude it looks you're looking for something like:
public void Displayrecording()
{
double highestheights;
for(int i = 0; i < 5; i++) {
highestheights = /*maybe some static class here*/getheight(/*maybe some parameter here*/);
if(highestheights > 5000)
{
System.out.print(records.get(i));
}
}
}
Generally your code is missing an array with mountain names or ids.

Programming average with arrays [closed]

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 8 years ago.
Improve this question
public static void main (String args[])
{
//10 name arrays
String players[]=new String[10];
players[0]="Kevin Love";
players[1]="Kyrie Irving";
players[2]="Lebron James";
players[3]="Dion Waiters";
players[4]="Shawn Marion";
players[5]="Tristan Thompson";
players[6]="Anderson Varejo";
players[7]="Joe Harris";
players[8]= "Mike Miller";
players[9]="Brendan Haywood";
//10 height arrays in centimeter
double heights[]= new double [10];
heights[0]=208;
heights[1]=191;
heights[2]=203;
heights[3]=193;
heights[4]=201;
heights[5]=206;
heights[6]=208;
heights[7]=198;
heights[8]=203;
heights[9]=213;
System.out.println("The average of the players height is: " + calcAverage(heights)+ " cm");
}
// for calculating average for the players height
public static double calcAverage(double[] heights) {
double sum = 0;
for (int i=0; i < heights.length; i++) {
sum = sum + heights[i];
}
double average = sum / (double)heights.length;
return average;
}
// comparing height with the average
public static void heightvsAverage(String [] players, double [] heights, double average)
{
for(int i=0;i<10;i++)
{
while (heights[i]>average)
{
System.out.println("Players with above average are:");
System.out.println();
System.out.println("Players|Heights");
System.out.println("---------+---------");
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(String.format("%-11s|%8s", players[i],df.format(heights[i])));
}
}
}
}
I am having a problem with the third method i am trying to compare the heights with the average, and i am trying to make a table in the third method that outputs players with height above average. Main method and method 2 are excellent it's just that i am having difficulty making the chart in method 3
Hints:
1) What is going on here?
while (heights[i]>average)
Think about it!
2) How many headers does a table need? How many times is your code printing the table header? Why?
Use if in place of while in third method
First of all you're never calling the method, so I've added the function call after you display the average
heights[9]=213;
System.out.println("The average of the players height is: " + calcAverage(heights)+ " cm");
//Add this line
heightvsAverage(players, heights, calcAverage(heights));
Make sure you remove the while back to the if, otherwise you'll have an infinite loop.
Finally, check what the other answers told you, you should only be displaying your header once, then the player's names.
EDIT
I changed the function to this:
// comparing height with the average
public static void heightvsAverage(String [] players, double [] heights, double average)
{
System.out.println("Players with above average are:\n");
System.out.println("Players|Heights");
for(int i=0;i<10;i++)
{
if (heights[i]>average)
{
System.out.println("---------+---------");
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(String.format("%-11s|%8s", players[i],df.format(heights[i])));
}
}
}
that and adding the function call that I mentioned before will get you the print that I'm guessing you need.
FYI, this is simple analysis, and I would think many would agree you gotta try a bit harder yourself before asking others to solve the problem for you, otherwise you won't learn much.
Good luck!

Maintaining proper spacing in Java

I made a program that should output 2 lists of strings (anywhere between 2 and 5) at the end of the line, I want to print an int in brackets.
I am having trouble right justifying the int and the brackets.
All of the printf formatting does not help with moving the int and its surrounding brackets!
while (dealerPoints < 17 && playerBust == false) {
System.out.printf("\nDealer has less than 17. He hits...\n");
int nextDealerCard = dealCard();
dealerPoints += cardValue(nextDealerCard);
dealerHand += faceCard(nextDealerCard);
System.out.printf("Dealer: %s\t[%d]\n", dealerHand, dealerPoints);
System.out.printf("Player: %s\t[%d]\n", playerHand, playerPoints);
}
When there are 4 strings on one line and only 2 on the other, the int and brackets don't align with each other (the one after 4 strings, gets tabbed over too far)
System.out.printf("Dealer: %s\t[%10d]\n", "lala", 22222);
System.out.printf("Player: %s\t[%10d]\n", "hoho", 33);
Outputs:
Dealer: lala [ 22222]
Player: hoho [ 33]
is this what you want?
If you want to right justify, you can either
- write the output in a file as a CSV and open it in an excel like program
- create a utility class that will make any input string a constant length:
public static String fixedCharCount( String input, int length ) {
int spacesToAdd = length - input.lengh();
StringBuffer buff = new StringBuffer(input);
for( int i=0; i<spacesToAdd; i++) {
buff.append(" ");
}
return buff.toString();
}
You can also loop on all your data befor display to see what is the longest String in your table and adapt the length to it (the code is not complete: you must check 'spacesToAdd' is positive.

Categories

Resources