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!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm a beginner with java and have a problem. I have an assignment to do with the java.util.scanner class where you can put a value for radius in the console and get as output the diameter, surface etc.
My problem is, that I can enter the radius value, but it's not giving me the desired value for the diameter etc, only the text.
import java.util.Scanner;
public class Lab1_Aufg1
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Radius: ");
double Radius = s.nextDouble();
double durchmesser;
double umfang;
double flaeche;
durchmesser = Radius * 2;
umfang = 2 * Math.PI * Radius;
flaeche = Math.PI * Radius*Radius;
System.out.println("Durchmesser = " durchmesser);
System.out.println("Umfang = " umfang);
System.out.println("Fläche = " flaeche);
s.close();
}
}
You need to change s.Next() to s.nextDouble() to get a double input. also, you need to put a + between the variables and the strings instead of putting a space:
System.out.println("Durchmesser = " + durchmesser);
You are missing a } at the bottom of your file.
Always make sure to count your curly braces.
Edit:
Your code was edited by another user, if you pop it into jdoodle you should see that it works now.
All problem fixed use this code, it'll work:
import java.util.Scanner;
public class stackCircle
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Radius: ");
double Radius = s.nextDouble();
System.out.printf("Durchmesser = %.2f\n" , Radius * 2);
System.out.printf("Umfang = %.2f\n" , 2 * Math.PI * Radius);
System.out.printf("Fläche = %.2f\n" , Math.PI * (Radius*Radius));
s.close();
}
}
Note: I have added %.2f, this will make your output to display results up to 2 decimal positions. This is easy to read then using default 8 decimal places. Hope it helps.
You need to change Next() to nextDouble() to get an double-type input.
Also, String objects can be appended using the + operator in Java. You need to fix how you append strings within your System.out.println() statements:
System.out.println("Durchmesser = " + durchmesser); // Need to add the '+' symbol
System.out.println("Umfang = " + umfang);
System.out.println("Fläche = " + flaeche);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently taking a HS course on java, so I am a novice at java to say the least. Right now, for my own use, I am writing a program to take a 2 digit number, and then add up it and all the odd numbers before it till 1. I have the Scanner, calculating whether the number is odd or even, and the runner methods done already(the basic bit), but am a bit confused on the logic. I am trying to use a recursion, and do this code, but am a bit stuck. It would be helpful if you could point me in the right direction, without giving the whole code away. Thanks, - A Novice Programmer
public static void main(String[] args)
{
MathRecursion tester = new MathRecursion();
tester.Method1Runner();
}
public void Method1Runner()
{
GetIntM1();
OddOrEven();
System.out.println("\n\n");
}
public void GetIntM1()
{
Scanner kb = new Scanner(System.in);
System.out.print("\n\n\nEnter a 2 digit integer: ");
twoDig = kb.nextInt();
}
public void OddOrEven()
{
if (twoDig % 2 == 0)
{
//This is even method
Method1a(twoDig);
}
else
{
//This is odd method
Method1b(twoDig);
}
}
public int Method1a(int a)
{
//if (a = 1)
int result = 0;
while (a<=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
You don't need recursion. The sum of the first n odd numbers is n*n.
The number of odd numbers before a number x is floor(x/2) or in Java (int) x/2 or if x is an int, just x/2.
So the expression in Java that gives you "a 2 digit number, and then add up it and all the odd numbers before it till 1" where the number is stored in int x is:
x + (x/2) * (x/2)
or simplified:
x + x*x/4
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My very simple program should sort out the maximum one among 3 numbers. I have used a static method for algorithm and called that into the main method. User should enter 3 floating numbers by using a space. afetr pressing enter the program should print out the biggest floating number. But it doen't. It just shows a bunch of errors. The attachment shows what error I have:
MaximumFinder.java:
package maximumfinder;
import java.util.Scanner;
public class MaximumFinder {
public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
System.out.println("Enter 3 floating-pont value separated by space:");
double num1 = inScanner.nextDouble();
double num2 = inScanner.nextDouble();
double num3 = inScanner.nextDouble();
double result = maximum(num1, num2, num3);
System.out.println("Maximum number is: "+result);
}
public static double maximum(double x, double y, double z) {
double maximumValue = x;
if (y > maximumValue)
maximumValue = y;
//statement
if (z > maximumValue)
//statement
maximumValue = z;
return maximumValue;
}
}
If I exclude the package declaration it is working perfectly fine for me
Just make sure that the class is in the right package.
Note : compile & run from command line.
Why dont you simply use the max() method from Java? It may solve your problem...
EDITED
I've tried your code and it runs perfectly, but I got the same error as you, if I type the double numbers using dots, like "3.5". If I type the numbers using commas("3,5") the program is executed till the end.
I hope this help you.
public static double maximum(double firstValue, double... otherValues) {
double maximumValue = firstValue;
for (double v : otherValues) {
maximumValue = Math.max(maximumValue, v);
}
return maximumValue;
}
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
This is my first time doing java and I am am trying to get the largest number from an array of x numbers using a method called bigNum(). Can anyone tell me why this doesn't work?
class project3
{
public static void main(String args[])
{
int total =0;
int b;
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for (int i=0; i < maxItems; i++)
{
b = EasyIn.getInt();
}
bigNum(b);
}
public static void bigNum(int maxItems)
{
for (int i = 1; i >= maxItems; i++)
{
if (bigNum(b) >= maxItems)
bigNum(b) = maxItems;
}
return bigNum(b);
}
}
You're probably getting compiler errors at this point due to unmatched braces. You want your program to have matched braces, and you also want to avoid having methods inside of other methods.
You want to have something that has the following form
class project3
{
public static void main(String args[])
{
...
}
public static int bigNum(int maxItems[])
{
...
return someInt;
}
}
// capital letter for the class (convention)
public class Project3 {
public static void main(String args[]) {
//int total = 0; // you never used this number
System.out.println("How many numbers do you want in the array");
int maxItems = EasyIn.getInt();
int[] numbers = new int[maxItems];
for(int i = 0; i < maxItems; ++i) {
int newNumber = EasyIn.getInt();
/* you want to put the numbers into an array,
so don't call "bigNum" but put them there: */
numbers[i] = newNumber;
}
// now find the big number:
int bigNumber = bigNum(numbers);
System.out.println("The biggest number: " + bigNumber);
}
// first: change the return type to get the biggest number
// second: pass the reference to the array, not a single number
// public static void bigNum(int maxItems) {
public static int bigNum(int[] items) {
// create big number, assume it's very small:
int bigNumber = Integer.MIN_VALUE;
// this for loop will never run, change it a bit:
//for(int i = 1; i >= maxItems; i++) {
for(int i = 0; i < items.length; i++) {
// your idea is correct, but you can not use the
// method here, see explanations below
// Also don't check for the number of Items, but for
if(items[i] > bigNumber) {
bigNumber = items[i];
}
}
return bigNumber;
}
}
Explanations and further readings
Class name: Java has lots of different naming conventions, but the most common rules are: ClassNames/Types in CamelCase with a Capital at the beginning, variableNames following a similar convention but with a leading small letter. This makes it much easier to read code.
Indentation: Try to use a more consistent indentation. Also supports readability. Actually some other programming languages even rely on correct indentation.
Try to understand what variables and what methods are and how to use them (and return from them, you can not assign values to a method in Java. While you read the latter tutorial focus on return types and how to call methods correctly, you can not return an int when your method is of type void. Also the parameters need to be exactly defined.
Apart from that try to compile your code before you post it. As your code went, it should have thrown lots of compile errors, e.g. bigNum(b) = maxItems; should tell you that the left-hand side of an assignment needs to be a variable. This can help you a lot while tracking down mistakes.
Another error is that for most people EasyIn will not be defined (as it is for me, so the code I posted above might actually not be working, I didn't try). I suppose it's a learning library (we had our AlgoTools back in our first Java lectures). Still it would be nice to tell us what it is and what other imports you use (common mistake when I let my IDE decide my imports for me: java.util.Date and java.sql.Date).
Also try to make clear to yourself what you want to achieve with your program and how. Your algorithm actually looks like you didn't think too much about it: You try to find a biggest number and always check "a big number" against the number of expected items, which then might become "the big number" as well. Or something like that.
Programming is being concise and exact, so make a plan before. If it's too hard for you to think about a solution directly, you can maybe draw it on paper.
And if you then have problems, after compiling, asking your program, asking google, asking stack overflow: provide us with as many details as you can and we will be able to help you without just posting some code.
Good luck!
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.