I want output(mix of double res and String resString) is assigned a single variable.
import java.util.Scanner;
public class Lab3Task02_08 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("х = ");
int x = in.nextInt();
System.out.print("y = ");
int y = in.nextInt();
double arithm = (x+y)/2;
double geom = Math.sqrt(Math.abs(x*y));
//////////////////////////////////////////////////////////////
double res = x>y? arithm:geom;
String resString = x>y? "Arithm.average = ":"Geom.average = ";
//////////////////////////////////////////////////////////////
System.out.print(resString + res);
in.close();
}
}
You could do something like this:
String format = "%s.average = %d";
String res = x > y
? String.format(format, "Arithm", arithm)
: String.format(format, "Geom", geom);
— But, really, I question the logic of having two different averages conflated in this way in the first place.
As I understand you want to output two different values depending on the same condition. One of the option, it could be done with String.format(), Double.compare() and x ? y : x.
public static void main(String... args) throws ParseException {
Scanner scan = new Scanner(System.in);
System.out.print("х = ");
int x = scan.nextInt();
System.out.print("y = ");
int y = scan.nextInt();
double arithmetic = (x + y) / 2.;
double geometric = Math.sqrt(Math.abs(x * y));
int res = Double.compare(arithmetic, geometric);
System.out.format(Locale.ENGLISH, "%s average = %.2f\n",
res > 0 ? "Arithmetic" : "Geometric",
res > 0 ? arithmetic : geometric);
}
Output:
х = 3
y = 5
Arithmetic average = 4.00
х = -4
y = 3
Geometric average = 3.46
If i understand the question , is this what you want ?
import java.util.Scanner;
public class Lab3Task02_08 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("х = ");
int x = in.nextInt();
System.out.print("y = ");
int y = in.nextInt();
double arithm = (x+y)/2;
double geom = Math.sqrt(Math.abs(x*y));
//////////////////////////////////////////////////////////////
double res = x>y? arithm:geom;
String resString = x>y? "Arithm.average = ":"Geom.average = ";
//////////////////////////////////////////////////////////////
String combinedRes = resString + res;
System.out.print(combinedRes);
in.close();
}
}
Related
when I attempt to run this program it will accept the inputs but will only print out 0.0 0.0 0.0 for all prints. I need it to print the imputed numbers and then print the average to 2 decimal accuracy. Why is it only printing 0s and not the numbers put in
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate
{
double[] pcPrice = new double [10];
public static void main(String[] args)
{
Quiz input = new Quiz();
Quiz display = new Quiz();
Quiz avgCalc = new Quiz();
input.arrayInput();
display.displayPCPrices();
avgCalc.avgPCCalc();
}
public void displayPCPrices()
{
System.out.println(Arrays.toString(pcPrice));
}
public double avgPCCalc()
{
int sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum = (int) (sum + pcPrice[i]);
}
double average = sum / (double)pcPrice.length;
return average;
}
public void arrayInput()
{
Scanner price = new Scanner(System.in);
System.out.println("Enter Prices");
pcPrice[0] = price.nextDouble();
pcPrice[1] = price.nextDouble();
pcPrice[2] = price.nextDouble();
pcPrice[3] = price.nextDouble();
pcPrice[4] = price.nextDouble();
pcPrice[5] = price.nextDouble();
pcPrice[6] = price.nextDouble();
pcPrice[7] = price.nextDouble();
pcPrice[8] = price.nextDouble();
pcPrice[9] = price.nextDouble();
}
}
Arrays are better in loops, in this case, I would to something like this:
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate {
double[] pcPrice = new double [10];
public static void main(String[] args){
Scanner price = new Scanner(System.in);
for(int i=0; i< pcPrice.length; i++){
System.out.print("Set Price " + (i + 1) + ":");
pcPrice[i] = price.nextDouble();
}
displayPCPrices();
System.out.println("The average is :" + avgPCCalc());
}
public void displayPCPrices()
{
System.out.println("The prices are: " + "\n");
for(int i = 0; i< pcPrice.length; i++){
System.out.print(pcPrice[i] + " ");
}
}
public double avgPCCalc()
{
double sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum += pcPrice[i];
}
double average = sum / 10;
return average;
}
}
Call your displayPCPrices method from your main and pass in pcPrice as a parameter:
import java.util.Scanner;
import java.util.Arrays;
public class pcCalculate
{
public static void main(String[] args)
{
double[] pcPrice = new double [10];
Scanner price = new Scanner(System.in);
System.out.println("Enter Prices");
pcPrice[0] = price.nextDouble();
pcPrice[1] = price.nextDouble();
pcPrice[2] = price.nextDouble();
pcPrice[3] = price.nextDouble();
pcPrice[4] = price.nextDouble();
pcPrice[5] = price.nextDouble();
pcPrice[6] = price.nextDouble();
pcPrice[7] = price.nextDouble();
pcPrice[8] = price.nextDouble();
pcPrice[9] = price.nextDouble();
displayPCPrices(pcPrice);
}
public void displayPCPrices(Array pcPrice)
{
System.out.println(Arrays.toString(pcPrice));
}
public double avgPCCalc()
{
int sum = 0;
for (int i=0; i < pcPrice.length; i++)
{
sum = (int) (sum + pcPrice[i]);
}
double average = sum / (double)pcPrice.length;
return average;
}
}
EDIT: And just so you're aware, main(String[] args) is where your program will always start, from there you call other methods and do your work. Nothing else will be calling your main method.
EDIT2: If you'd like to have a conversation about your coding practices shoot me a message, I see you've changed your question and you're missing some basic concepts that would help you easily solve this issue.
I have tested the numbers and they hold the correct values but it is printing out the end result completely wrong. E.X: If I put 2/4, it outputs 1
Here is my code:
import java.util.Scanner;
public class FractionConverter {
public static void main(String[] args) {
System.out.println("Welcome To The JEM Fraction Converter!\n");
Scanner sc = new Scanner(System.in);
String num = "0", choice;
System.out.println("Would You Like To Convert From 'Fraction - Decimal'(a) or 'Decimal - Fraction'(b)?");
choice = sc.nextLine();
if (choice.equalsIgnoreCase("a")) {
System.out.println("Please Enter A Fraction (x/y)");
num = sc.nextLine();
String[] parts = num.split("/");
String numerator = parts[0];
String denominator = parts[1];
double result = Double.parseDouble(numerator);
double result2 = Double.parseDouble(numerator);
System.out.println("\n" + numerator + "/" + denominator + " In Decimal Form Is: " + (result/result2));
}
}
}
Appreciate the help!
Replace this line:
double result2 = Double.parseDouble(numerator);
with this:
double result2 = Double.parseDouble(denominator);
double result = Double.parseDouble(numerator);
double result2 = Double.parseDouble(numerator);
... I suppose is a copy/paste problem, isn't it? (both times numerator)
I was wondering if someone could tell me
1. why, when i input weightNumber with a decimal place, weightConverted doesn't convert it to the whole number, even though I create variable for it?
2. how could i improve this "program" in any way, THANK YOU !!
here is the problem:
code:
import java.util.Scanner;
public class cofee {
public static void main (String []args){
double weightNumber = 0;
String packageType = "";
String serviceType ="";
double totalFee = 0;
double weightConverted = Math.round(weightNumber); // <- this is the problem, should i put it somewhere else?
final double LETTERCOSTP = 12.00;
final double LETTERCOSTS = 10.50;
final double BOXCOSTP = 15.75;
final double BOXCOSTS = 13.75;
final double BOXWEIGHTP = 1.25;
final double BOXWEIGHTS = 1.00;
// input
Scanner input = new Scanner(System.in);
System.out.print("Enter package type (letter/box): ");
packageType = input.nextLine().toLowerCase();
System.out.print("Enter type of service (standard/priority): ");
serviceType = input.nextLine().toLowerCase();
switch(packageType)
{
case "letter":
System.out.print("Enter the weight in ounces: ");
weightNumber = input.nextDouble();
break;
case "box":
System.out.print("Enter the weight in pounds: ");
weightNumber = input.nextDouble();
break;
default:
System.out.print("WRONG PACKAGE TYPE !!!");
}
// letter
if (packageType.equals("letter") && serviceType.equals("priority"))
{
totalFee = LETTERCOSTP;
}
if (packageType.equals("letter") && serviceType.equals("standard"))
{
totalFee = LETTERCOSTS;
}
// box
if (packageType.equals("box") && serviceType.equals("priority"))
{
totalFee = BOXCOSTP + ((weightConverted - 1.0) * BOXWEIGHTP);
}
if (packageType.equals("box") && serviceType.equals("standard"))
{
totalFee = BOXCOSTS + ((weightConverted - 1.0) * BOXWEIGHTS);
}
// display
System.out.println("The fee is € "+ totalFee + " for a package with");
System.out.println("\tType: "+packageType);
System.out.println("\tService: "+serviceType);
System.out.println("\tOunces: "+weightConverted);
}
}
The line double weightConverted = Math.round(weightNumber); will call round() with the value of weightNumber, which is 0, so it rounds 0 to... well... 0, and assigns it to weightConverted.
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
Having trouble with this final program for my Java class. We have to only use concepts we have learned so far so I cannot use other classes. Basically just loops and arrays and methods.
So for this program we have to add any five sets of fractions entered and give the GCD and the results in the lowest form. I have to show all data in the first table and then a second table with the original data and the GCD and the results in the lowest form. It has to be tested with this data:
1/4 + 1/2
2/3 + 1/3
7/8 + 1/8
2/9 + 4/27
7/25 + 2/5
Here is the code I have so far. (Be gentle, I'm still new at this)
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) throws Exception{
int[] num1Array = new int[5];
int[] num2Array = new int[5];
int[] deno1Array = new int[5];
int[] deno2Array = new int[5];
Scanner input = new Scanner(System.in);
for(int x=0;x<5;x++) { //Get all data from user
System.out.println("Enter data for problem " + (x+1));
System.out.println("Enter numberator for fraction 1");
num1Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 1");
deno1Array[x] = input.nextInt();
System.out.println("Enter numberator for fraction 2");
num2Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 2");
deno2Array[x] = input.nextInt();
System.out.println("********************");
}
System.out.println("*****ORIGINIAL DATA ******"); //Output all entered data
System.out.println("First Fraction \t Second Fraction");
for(int y=0;y<5;y++) {
System.out.printf("%1d/%1d \t\t %1d/%1d\n", num1Array[y], deno1Array[y], num2Array[y], deno2Array[y]);
}
System.out.println("*******FRACTIONS SHOWING ADDED RESULTS*********"); //Display results
System.out.println("First Fraction \t Second Fraction GCD Results");
for(int z=0;z<5;z++){
int finalgcd = gcdfinal(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
int addFrac = fracAdd(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
System.out.printf("%1d/%1d \t\t %1d/%1d\t\t %1d \t %1d", num1Array[z], deno1Array[z], num2Array[z], deno2Array[z], finalgcd, addFrac);
System.out.println();
}
}
public static int fracAdd(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //denominator
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int adding = g1 + g2;
int k = gcd(adding, e);
int final_num = adding / k;
int final_deno = e / k;
if(final_num == final_deno){
return 1;
}
else {
return (final_num, final_deno);
}
}
public static int gcd(int a, int b) //Calculate GCD
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int gcdfinal(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //Calculate the GCD for display
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int end = g1 + g2;
int k = gcd(end, e);
return k;
}
public static int lcm(int a, int b) //Calculate LCM
{
return a * (b / gcd(a, b));
}
}
How can I approach doing this? Am I on the right track?
Try with this, hopefully it helps you. :)
import java.util.Scanner;
public class AddingFraction {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("please enter a fraction number in a/b format: ");
String fraction1 = sc.nextLine();
System.out.println("please enter another fraction number in a/b format: ");
String fraction2 = sc.nextLine();
addFractions(fraction1, fraction2);
}
public static void addFractions(String fractionNum1, String fractionNum2) {
int numResult = 0;
String resultFraction;
String[] frcNum1 = fractionNum1.split("/");
int numerator1 = Integer.parseInt(frcNum1[0]);
int Denomenator1 = Integer.parseInt(frcNum1[1]);
String[] frcNum2 = fractionNum2.split("/");
int numerator2 = Integer.parseInt(frcNum2[0]);
int Denomenator2 = Integer.parseInt(frcNum2[1]);
if (Denomenator1 == Denomenator2) {
numResult = numerator1 + numerator2;
resultFraction = numResult + "/" + Denomenator1;
System.out.println("Resultant Fraction is : "+resultFraction);
} else {
int denLcm = Denomenator1 * (Denomenator2 / gcd(Denomenator1, Denomenator2));;
numResult = numerator1 * (denLcm / Denomenator1) + numerator2
* (denLcm / Denomenator2);
resultFraction = numResult + "/" + denLcm;
System.out.println("Resultant Fraction is : "+resultFraction);
}
}
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
}