Here's my current code:
import java.util.Scanner;
public class Addition
{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int area;
int number1;
int number2;
System.out.print( "Input base value = " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Input height value = " ); // prompt
number2 = input.nextInt(); // read second number from user
area = 1/2*(number1*number2); // add numbers
System.out.printf( "The Area of the right triangle is %d\n", area ); // display sum
} // end method main
} // end class Addition
I would like to make it display the decimal point when i input 5 as the first and second number. i tried replacing int area with double area but doesn't work..
If you want two digits after the decimal point, you must make area a double and use a format string of %1.2f.
Example:
System.out.printf("%1.2f\n", 78785.7);
You can check out the vast array of examples here:
Formatting Numerical Data
Hope it helps :) Cheers!
In addition to making area a double, you'll also need to make at least one of the terms in 1/2*(number1*number2) a double, or you'll only be doing int math, which won't turn out how you expect. For example:
1.0/2*(number1*number2)
In your output, you'll also have to use %f instead of %d.
Related
I was trying to run my code with a scanner and suddenly it errors when it goes to the 2nd question.
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner stats = new Scanner(System.in);
double base,current;
float bonus;
int level;
System.out.print("Enter the base attack speed: ");
base = stats.nextDouble();
System.out.printf("Enter the bonus attack speed %: " + "%.2f");
bonus = stats.nextFloat();
System.out.println("Enter the level: ");
level = stats.nextInt();
current = (base*1+bonus*level-1) /100;
System.out.print("The character's current speed is: " + current);
}
}
% is what printf (and String.format) use for identifying a placeholder which will be filled in by a parameter provided as second argument.
You therefore have 2 bugs in this code:
The % in attack speed %: is being identified by printf as a placeholder, but you want to print an actual percent symbol. To print that, write 2 percent symbols, which is 'printf-ese' for a single percent symbol: "Enter the bonus attack speed%%: ".
You then add "%.2f" to it which is bizarre, what do you think that does? As written, if you fix the bug as per #1, you immediately get another exception because this requires an argument. The idea is that you can do something like: System.out.printf("The speed of the vehicle in km/h is: %.2f", someValue);. If someValue is, say, 39.8993, that will print the string "The speed of the vehicle in km/h is: 39.90", because you asked for: Print a value as floating point value with max 2 fractional digits. You don't have any input to print there - you're still asking the user, and you can't use this kind of thing to 'format' what the user is supposed to put in. That comes later. So presumably you want to just get rid of that entire "%.2f" thing there.
I'm struggling with an assignment. I need help figuring out how to call the right methods within each other and eventually in main. My whole code might need work at this point, what am I doing wrong? I've been stuck on this for a week.. (Guidelines at the bottom) Thanks!
import java.util.Scanner;
public class AverageWithMethods {
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
userPrompt(); //Can't figure out how I'm supposed to set this up.
}
public static String userPrompt()
{
System.out.println("Enter 5 to 10 numbers separated by spaces, then press enter: ");
String num = in.nextLine();
return num; //I think I'm supposed to call the averager method here somehow?
}
public static double averager(String userPrompt)
{
double nums = Double.parseDouble(userPrompt);
double average = 0;
int counter = 0;
char c = ' ';
for (int i = 0; i < userPrompt.length(); i++)
{
if(userPrompt.charAt(i) == c)
{
counter++;
}
average = nums / counter;
}
return average;
}
public static void result(double average, String userPrompt)
{
System.out.println("The average of the numbers" + userPrompt + "is" + average);
}
}
GUIDELINES:
The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the user calculates the average of those numbers, and displays the numbers and their average to the user.
The program uses methods to:
Get the numbers entered by the user Calculate the average of the numbers entered by the user Print the results with the whole number, a decimal, and two decimal positions The first method should take no arguments and return a String of numbers separated by spaces.
The second method should take a String as its only argument and return a double (the average).
The third method should take a String and a double as arguments but have no return value.
For example, if the user input is... 20 40 60 80 100
...the program should give as output... The average of the numbers 20 40 60 80 100 is 60.00.
I will not exactly provide complete solution to your questions but guide you in solving the problem:
User input : 1 2 3 4 5
Thus, now you need to read it in a String which you are already doing in your userPrompt() method.
Post that you need to call your averager() method to get the average
of the numbers. In that averager method you can need to split the
String to get the numbers. Check : String.split() method
documentation on how to achieve that. Then, you need to call
Double.parseDouble() for your String array of numbers.
Finally , you need to make a call to result method in you main()
method.
I hope it helps you on how to approach the problems and has sufficient hints to get the correct solution
I keep getting the error "String can not be converted to double" I have tried re-defining my variables as int but that doesn't seem to work — I just get a flag saying that loss will occur converting double to int. Im curious as to wether or not I'm using the wrong JOptionPane when calling for input from the user or if my variable declarations are wrong.
Any help would be greatly appreciated.
package pf_javaass01c;
import javax.swing.JOptionPane;
public class ConversionCalculator
{
final static String HEADING = "Conversion Calculator";
final static double CONVERSION = 0.6214;
final static double PI = 3.14159;
public static void main(String[] args)
{
// Input Variables
double kilometers, convertedKilometers, miles, convertedMiles;
double width, length, areaRectangle, perimeterRectangle;
double radius, circumference, areaCircle;
// Kilometer to Miles Calculator
kilometers = JOptionPane.showInputDialog(null, "Please enter a kilometer value you wish to convert to miles;", HEADING, JOptionPane.QUESTION_MESSAGE);
convertedKilometers = kilometers * CONVERSION;
JOptionPane.showMessageDialog(null, kilometers + " kilometers is equal to " + convertedKilometers + " miles.", HEADING, JOptionPane.INFORMATION_MESSAGE);
} // End of main
} // End of ConversionCalculator
The value returned by the JOptionPane is a String. You are trying to put that value into kilometers, which is a double. You're basically trying to fit a sphere into a triangular hole. As a result, the error occurs.
The solution is to simply parse, or convert, the string to a double. To do that, call Double.parseDouble():
// get the user input and put it into a string variable first
String userInput = JOptionPane.showInputDialog(null, "Please enter a kilometer value you wish to convert to miles;", HEADING, JOptionPane.QUESTION_MESSAGE);
// parse the user's input and assign the result to kilometers
kilometers = Double.parseDouble(userInput);
Double.parseDouble() was the answer with new variables that allow for user input to be converted to double!
this is my first entry to stackoverflow so please let me know if something is wrong.
I know how to show an imported float number with x decimal numbers. But how do you define the amount of decimal numbers via a new scanned int number?
This is my code: (of course "%.decimalf" doesn't work, I just wanted to test it)
anyone? thanks in advance!
import java.util.Scanner;
public class Fliesskommazahl{
public static void main (String[] args){
// ask for/import floating point number
System.out.println("Please enter a floating point number like 1,1234: ");
Scanner scanner = new Scanner(System.in);
float number = scanner.nextFloat();
// show floating point number
System.out.println("You've entered: " + number);
/* show number with exactly two decimal places
In short, the %.02f syntax tells Java to return your variable (number) with 2 decimal places (.2)
in decimal representation of a floating-point number (f) from the start of the format specifier (%).
*/
System.out.println("Your number with two decimal places: ");
System.out.printf("%.02f", number);
System.out.println();
// import second (positive) number.
System.out.println("Please enter a positive integer number to define amount of decimal places: ");
Scanner scanner2 = new Scanner(System.in);
int decimal = scanner.nextInt();
// show imported floating point number with imported number of decimal places.
System.out.printf("%.decimalf", number);
}
}
This could work
System.out.printf ("%." + decimal + "f", number);
You should use this class I think this could work out really good for you here it is:
double num = 123.123123123;
DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(num));
In this case the output would be 123,123, the amount of zeros after the #. is the amount of numbers you want after the dot.
I want to make a calculator that greets the user by name then multiplies one number that the user enters and one number that I set. For instance, if the user enters the number 10, I want my code to take the 10 and multiply it by 6.
Here's what I have so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello" + userName + "how many steps do you take in a ten second interval?");
}
}
This part is working, but I can't figure out what to do next.
If you take a look at the Javadoc for Scanner, there is a nextInt() method, which will do the same thing as nextLine() but return an integer. You can set that to an integer variable.
To multiply two variables, it's as simple as
int z = x * y;
Then print out the result, or to simplify it, you could just print out the calculation without setting it equal to a variable
System.out.println("The awnser is: " + (scanner.nextInt() * 6));
Keep in mind, this are integers, you could also use doubles or floats, or even longs. See the scanner documentation for all the methods you can use to get input.
Use nextInt() (or nextDouble() or ...) method to read the number the user will input.
int userNumber = (userInputScanner.hasNext()) ? userInputScanner.nextInt() : 0;
System.out.println("6 * " + userNumber + " = " + (6 * userNumber));