I'm trying to make a program that converts a number the user inputs into a percentage. Once converted, I want to keep the first two numbers after the decimal, but without rounding off the number. For example, inputting 1.23456 would result in 123.45.
My line of thinking was that I could take the input, separate the string into before and after the decimal place, and from there create a loop that removes the last digits until it has at most 2 decimal places. My issue is that whenever I create something that would have an output greater than 9 for the decimal, I get the error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0, so I can only get decimals to the tenths place at the moment.
My code:
import java.util.Scanner;
public class percentage {
public static void main(String[] args) {
try (// TODO Auto-generated method stub
Scanner x = new Scanner(System.in)) {
System.out.println("Please input a number with a decimal to be converted into a percentage: ");
String numberAsString = x.next();
double number = Double.parseDouble(numberAsString);
double percentage = (number * 100);
String toString = Double.toString(percentage);
String[] parts = toString.split("[.]");
String integer = parts[0];
String decimal = parts[1];
int length = decimal.length();
while(length>2) {
decimal = decimal.substring(0,decimal.length()-1);
}
System.out.println("decimal is " + decimal);
System.out.println("integer is " + integer);
}
//System.out.println(decimal);
}
}
Multiply by 10,000 (100 for percentage, 100 for the two decimal places), truncate to integer, divide by 100 (to get back to percentage).
Writing it out one step at a time, for clarity of exposition:
Double n = input.nextDouble();
int i = (int)(n * 10_000);
Double pc = i / 100.0;
System.out.printf("%.2f\n", pc);
You have the number as a String in the variable toString. Use regex to trim all characters after the 2nd decimal (if any exist).
It’s a one-liner:
toString = toString.replaceAll("(?<=\\...).*", "");
Or just print it directly:
System.out.println(toString.replaceAll("(?<=\\...).*", ""));
Related
So I know I have to get the remainder in order for this to work. However, it works perfectly except for the first line where it gives me 6 instead of 5 for the first line. I think this is happening because 0 is considered a multiple of 5, but I am not really sure of how to get around this. I looked at How to display 5 multiples per line? but I am having trouble seeing how to fix my code using that as it doesn't appear like they had the first line being messed up issue. For example, if I enter 17 into the positive number it gives 6 numbers for the first line and then 5 for the rest. Then it gives the remaining ones which is what I want. For the average part you can type anything as I am going to work on that later. So the format should be something like this:
4.50, 5.56, 2.73, 8.59, 7.75,
...
5.34, 3.65,
Here is my code and thanks for the help:
import java.text.DecimalFormat;
import java.util.Scanner;
public class ArrayFun {
public static void main(String[] args) {
ArrayFun a = new ArrayFun();
}
public ArrayFun() {
Scanner input = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a positive number: ");
int limit = input.nextInt();
// Get input from the user
System.out.print("Enter the lower bound for average: ");
double lowerBound = input.nextDouble();
// Generate an array of random scores
double[] allScores = generateRandomArrayOfScores(limit);
// Display scores, wrapped every 5 numbers with two digit precision
DecimalFormat df = new DecimalFormat("0.00");
displayArrayOfScores(allScores , df);
// Calculate the average of the scores and display it to the screen
//double average = calculateAverage(lowerBound , allScores); //
System.out.print("Average of " + limit + " scores ");
System.out.print("(dropping everything below " + df.format(lowerBound) + ") ");
//System.out.println("is " + df.format(average) );//
}
private double[] generateRandomArrayOfScores(int num) {
double[] scores=new double[num];
for (int i=0;i<scores.length;++i) {
double number=Math.random()*100.0;
scores[i]=number;
}
return scores;
}
private void displayArrayOfScores(double[] scores, DecimalFormat format) {
System.out.println("Scores:");
for (int i=0;i<scores.length;++i) {
String num=format.format(scores[i]);
if ((i%5==0)&&(i!=0)) {
System.out.println(num+", ");
}
else{
System.out.print(num+", ");
}
}
System.out.println();
}
}
The problem is indeed the 0, exactly this part (i%5==0)&&(i!=0). Replace this by i%5==4 and it should work. It is because System.out.println(...) makes the new line after printing the string and if you count 0,1,2,3,4,5 those are 6 numbers, because you treat 0 differently. The last number in the groups of 5 has a modulo of 4. (i+1)%5==0 would work too fo course, it is the equivalent. Alternatively you could do an empty System.out.println() using your condition and print the number as the others afterwards.
I need to create a program that will calculate an average of arrays up to 10 numbers. Here are the requirements:
The program uses methods to:
1.Get the numbers entered by the user
2.Calculate the average of the numbers entered by the user
3.Print the results
The first method should take no arguments and return an array of doubles that the user entered.
The second method should take an array of doubles (the return value of the first method above) as its only argument and return a double (the average).
The third method should take an array of doubles and a (single) double value as arguments but have no return value.
I tried the below, but the biggest problem I'm running into (that I can tell so far at least) is that the program is printing both statements before allowing the user input. I know how to do this normally, but I think I'm getting confused because of the array piece. Thanks much.
public static void main(String[] args) {
double[] userNumbers = printUserNums();
double average = getAverage(userNumbers);
printAverage(average, userNumbers);
}
public static double[] printUserNums() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter five to ten numbers separated by spaces: ");
double[] userNums = new double[10];
return userNums;
}
public static double getAverage(double[] userNums) {
Scanner in = new Scanner(System.in);
int counter = 0;
double average = 0.0;
double sum = 0;
for (int i = 0; i < userNums.length; i++) {
sum = sum + userNums[i];
}
if (counter != 0) {
average = sum / userNums.length;
}
return average;
}
public static void printAverage(double average, double[] userNums) {
System.out.printf("The average of the numbers " + userNums + " is %.2f", average);
}
}
You are never asking for the numbers!
You need to ask for an input from the scanner:
String inputValue = in.next();
and then split your full string (containing the numbers separated by space) using space as your regex to get the numbers:
String[] stringValues = inputValue.split("\\s+");
You should probably have some kind of checking to verify that there is at least 5 values and no more than 10 values by your requirements.
If the checking passes, just loop through your array and convert the string values to double values with Double.valueOf(String s) and store them in your double array.
It's not how I would normally get numbers from user input but if you want to have them in one go, this should work.
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.
It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?
public class AverageWithMethods {
public static void main(String[] args) {
String userNumbers = getUserNums();
double average = userNumAvg(userNumbers);
printAverage(0, userNumbers);
}
public static String getUserNums() {
Scanner in = new Scanner(System.in);
String userNumInput = "";
System.out.print("Please enter five to ten numbers separated by spaces: ");
userNumInput = in.nextLine();
return userNumInput;
}
public static double userNumAvg(String userNumInput) {
Scanner in = new Scanner(System.in);
Scanner line = new Scanner(in.nextLine());
double count = 0;
double average = 0.0;
double sum =0;
while (in.hasNextDouble()) {
count++;
sum = line.nextDouble();
}
if (count != 0) {
average = sum / count;
count = Double.parseDouble(userNumInput);
}
return average;
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);
}
}
count how many spaces there are in your string. You can do this either by looping and checking the char value or you can do a replace on the string and compare the size of the new String
e.g.
String fiveNums = "1 2 3 4 5";
String noSpaces = fiveNums.replace(" ", "");
System.out.println(fiveNums.length() - noSpaces.length());
From your first section of code I am making the assumption all the numbers are entered on a single line all at once.
My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers?
The Scanner object you are using has a method hasNextInt() so you can construct a simple while loop to figure out how many numbers there are.
Scanner line = new Scanner(in.nextLine()); // Feed line into scanner
int numbers = 0;
double total = 0.0;
while(in.hasNextInt()) { // read all the numbers
numbers++;
total += line.nextDouble();
}
line.close(); // Good habit
You can then compute your average with all this information:
double avg = total/numbers;
Notes:
Making total a double to avoid integer math when computing the average. There are obviously other ways to avoid integer math and I can include more if you would like.
I use a second Scanner with a String parameter of in.nextLine() because if you skip that step, the code won't terminate when reading a continuous input stream such as a console/terminal. This is because there will be a next int possible since the terminal is still accepting input.
When you want to understand how many numbers input the user, you can:
String[] userNumInput = in.nextLine().split(" ");
int quantity = userNumInput.length;
User input quantity numbers.
Here is one of the possible ways to do from your original code:
import java.util.Scanner;
public class GetAverage {
public GetAverage() {
String getStr = getUserNums();
double result = userAvg(getStr);
printAverage(result, getStr);
}
public String getUserNums() {
Scanner in = new Scanner(System.in);
System.out.println("Please enter five to ten numbers separated by spaces: ");
return in.nextLine();
}
public static double userAvg(String str) {
String[] arr = str.split(" ");
double sum = 0.0;
double average = 0.0;
for (int i = 0; i < arr.length; i++) {
sum += Integer.parseInt(arr[i]);
}
if (arr.length > 0) {
average = sum / arr.length;
}
return average; // how do I get the program to count what to divide by since user can input 5- 10?
}
public static void printAverage(double average, String userNumInput) {
System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);
}
public static void main(String[] args) {
new GetAverage();
}
}
OUTPUT:
Please enter five to ten numbers separated by spaces:
5 7 8 9 6 3 2 4
The average of the numbers 5 7 8 9 6 3 2 4is 5.50
Hi I'm totally new to the Java language and my professor gave us an assignment that's not too complicated. I've done most of it correctly. Here's what we're supposed to do. If you enter two integers the sum should be an int. If you enter two doubles the sum should be a double. And if either of the two is a double then also the sum should be a double. And if either of the two can be interepreted as a Binary number, it should be treated as such. Lastly, if both numbers are Binary then the sum should be displayed in binary. The code I have so far, does everything except when I enter two ints it gives me the sum as a double, can somebody please suggest where I should make a change to fix that?
This is my code so far:
import java.util.Scanner;
public class ProjectZero
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
cin.useRadix(2);
System.out.print("Enter two numbers separated by a space: ");
if (cin.hasNextInt())
{
int first = cin.nextInt();
if (cin.hasNextInt())
{
int second = cin.nextInt();
bigFunction(first, second);
}
else if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else if (cin.hasNextDouble())
{
double first = cin.nextDouble();
if (cin.hasNextDouble())
{
double second = cin.nextDouble();
bigFunction(first,second);
}
else
System.out.println("Please try again and enter numbers.");
}
else
System.out.println("Please try again and enter numbers.");
cin.close();
}
public static void bigFunction(int a, int b)
{
int sum = a + b;
System.out.print("The sum of " + Integer.toBinaryString(a) + " (Decimal value: " + a + ")");
System.out.println(" and " + Integer.toBinaryString(b) + " (Decimal value: " + b + ")" + " is " + Integer.toBinaryString(sum));
}
public static void bigFunction(double a, double b)
{
double sum = a + b;
System.out.println("The sum of " + a + " and " + b + " is " + sum);
}
}
even easier answer do
instead of if .hasNextDouble
if (first % 1 ==0)
{
//you have an integer
}
else
{
//it is not an integer
}
the % means modulus which basically divides something and check if there is a remainder if there is a remainder after deviding a number by 1 it is not an int
The easiest way is to read the two inputs as Strings. Then check the strings to see whether they contain only the digits 0 and 1 (if so, binary number). If not binary, check whether it can be interpreted as a double. If so, cast to int and see if it is the same value (then it is an int). If it can't be read as a double, it is bad format. Note that you might have to consider if the number is too big to fit an int, or long, etc.
The reason why you are getting the sum as double when both the input's are int is because you are changing the default radix of scanner, hence it fails to recognize the input as int and instead reads it as a double.
If you don't change the radix of scanner, it will use the default radix (10) and scan input at base 10. Now this will work for input: int & double; but will not work for binary input's. All this boils down to your choice of implementation and I don't think you can accomodate all the required inputs with your current approach. I'd suggest following #FredK approach and take the input as string (even that approach has it's own flaws).
There is no way for you to check if the two numbers entered are in fact two separate ints. And also, you are asking for two double parameters and your sum is also a double so when you put the ints into the bigFunction, you are always casting them to doubles and the sum is a double so you will always get a double.
You need to have a check inside the bigFunction function to check if they are in fact two doubles or two ints, etc.
Or in fact make separate functions, but always strive for laziness!
Hope that gets the gears churning!
In java an integer is a form of double if you run the code
int a =4
int b =5
double b = a +c
System.out.print(b);
this would work as an integer is a form of double.
the easiest way would be to rename your double method to something else
best solution
userinput (the double) = variable
if ((variable == Math.floor(variable))
this rounds the number do so 5.9 would be 5 and if the that is equal to variable you have an int.
I tried searching for answers to this specific question, I could see formatting options and how to pad zeros to the left but my output cannot have decimal space designated zeros but only the zeros from the conversion result. For example if I convert 45 to binary it should display 00101101 but it omits the first two zeros, obviously, and displays 101101. If I format the output it displays extra or less zeros based on the format specifications. I am a beginner and not very good at JAVA. All help is appreciated. Here is the part of code specific to my question:
public class DecimalToBinary {
public String toBinary(int b) {
if (b==0) {
return "0";
}
String binary = "";
while (b > 0 && b < 256) {
int rem = b % 2;
binary = rem + binary;
b = b / 2;
}
return binary;
}
//MAIN:
public static void main(String[] args) {
int Choice;
Scanner input = new Scanner(System.in);
DecimalToBinary convertD2B = new DecimalToBinary();
BinaryToDecimal convertB2D = new BinaryToDecimal();
do{
System.out.println("Hello! What would you like to do today? Please enter 1, 2, or 3 based on the following: "+"\n"+
"1. Convert Decimal to Binary"+"\n"+"2. Convert Binary to Decimal"+"\n"+"3. Exit");
Choice = input.nextInt();
if(Choice==1){
System.out.println("Enter a Decimal Number between 0 to 255: ");
int decimalNumber = input.nextInt();
if(decimalNumber<256)
{String output = convertD2B.toBinary(decimalNumber);
System.out.println("The Binary equivalent of "+decimalNumber+" is: "+output);
}
else
{System.out.println("Please start over and enter a number between 0 and 255.");}
}
You can use printf to make a formated output. This line for example produces an output of the parameter value 2 consisting of 5 digits. It will fill up with leading 0's if neccessary.
System.out.printf("%05d", 2); // output is 00002
But this will only work with decimals and not with strings. But you can use this if you calc the difference manually and put in a 0 as paramter.
System.out.printf("The Binary equivalent of "+decimalNumber+" is: %0" + (8 - output.length()) + "d%s\n", 0, output);
If output is a string then you could put some zeros in front of it to it before printing.
Just measure the length of output and prepend the "0" string to it, 8 - length times.