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)
Related
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();
}
}
I'm currently working on a GPA calculator for a class of mine. I keep getting an error that has to do with the division I'm trying to do on the GPA calculation and am having trouble with the syntax for sub-strings and how to use them correctly. Below is the code I have so far. If you see anything I can fix that's not to complicated I'm open to all suggestions.
import java.util.Scanner;
public class GPA
{
public static void main(String[] mydata)
{
Scanner sc = new Scanner(System.in);
String choice = "";
String cnum;
String grade;
double points;
double gpa = 0;
int count = 0;
String credit= "", totalCredit = "";
while (!choice.equalsIgnoreCase("Q"))
{
cnum = (mydata[0]);
grade = (mydata[1]);
if (grade.equalsIgnoreCase("A")) {points = 4.0;}
else if (grade.equalsIgnoreCase("B")) {points = 3.0;}
else if (grade.equalsIgnoreCase("C")) {points = 2.0;}
else if (grade.equalsIgnoreCase("D")) {points = 1.0;}
else if (grade.equalsIgnoreCase("F")) {points = 0.0;}
credit = cnum.substring(3,4);
//System.out.println("credits = " + totalCredit);
System.out.println("GPA = " points/Double.parseDouble(credit));
System.out.print("Enter next course number and grade or ‘Q’ to quit: ");
System.out.println();
choice = sc.nextLine();
}
System.out.println("Bye!");
}
}
Not bad but there are a couple syntactical errors with your code:
The println argument needs to be concatenated with a +:
System.out.println("GPA = " + points / Double.parseDouble(credit));
The local variable, points, needs to be initialized since your if-else conditions are not exhaustive (ie: grade has a runtime range of A, B, C, D, or F but grade can technically be assigned to whatever is in mydata[1]). Either add an else condition or assign an initial value to points:
double points = 0.0;
Be sure to include + to concat the strings together :)
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
I believe you want to be concatenating here.
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
Instead of
System.out.println("GPA = " (points/Double.parseDouble(credit)));
And if you want
int theGpa = points/Double.parseDouble(credit));
System.out.println("GPA: " + theGpa);
I'm working on an assignment in which I use scanners to read lines and tokens of a .txt file. I need to do some conversions and rearrange a few strings, which I have done using some helper methods. The problem is that the code is only working for every other line that it reads from the file. I think I may have messed something up somewhere in the beginning of the code. Any hints or tips on what I would need to modify? Here's what I have thusfar:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("PortlandWeather2013.txt"));
while (input.hasNextLine()) {
String header = input.nextLine();
System.out.println(header);
Scanner input2 = new Scanner(header);
while (input2.hasNextLine()){
String bottomHeader = input.nextLine();
System.out.println(bottomHeader);
String dataLines = input.nextLine();
Scanner linescan = new Scanner(dataLines);
while (linescan.hasNext()){
String station = linescan.next();
System.out.print(station+ " ");
String wrongdate = linescan.next();
String year = wrongdate.substring(0,4) ;
String day = wrongdate.substring(6);
String month = wrongdate.substring(4,6);
System.out.print(month + "/" + day + "/" + year);
double prcp = linescan.nextDouble();
System.out.print("\t "+prcpConvert(prcp));
double snwd = linescan.nextDouble();
System.out.print("\t " + snowConvert(snwd));
double snow = linescan.nextDouble();
System.out.print("\t" + snowConvert(snow));
double tmax = linescan.nextDouble();
System.out.print("\t" + tempConvert(tmax));
double tmin = linescan.nextDouble();
System.out.println("\t" + tempConvert(tmin));
}
}
}
}
public static double prcpConvert(double x){
double MM = x/1000;
double In = MM * 0.039370;
double rounded = Math.round(In * 10)/10;
return rounded;
}
public static double snowConvert(double x){
double In = x * 0.039370;
double rounded = Math.round(In * 10)/10;
return rounded;
}
public static double tempConvert(double x){
double celsius = x/10;
double fahrenheit = (celsius *9/5)+32;
double rounded = Math.round(fahrenheit *10)/10;
return rounded;
}
nextLine() doesn't just fetch the last line, it also advances a line. Before your second loop you are calling nextLine() twice causing you to advance two lines each iteration of the loop.
You can fix your problem by setting dataLines = bottomHeader instead of calling nextLine() again.
This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}
import java.util.Scanner;
public class Assignment3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pi = 3.142;
double T, v, a, x, r;
System.out.println("3.Centrifuge. The rotor of an ultracentrifuge rotates at x rev/s.");
System.out.println("A particle at the top of the test tube is r meter from the rotation axis.");
System.out.println("Calculate it’s centripetal acceleration.");
System.out.printf("Enter the number of rotation in rev/s : ");
x = input.nextInt();
System.out.printf("Enter the distance in meter : ");
r = input.nextInt();
T = 1/x;
v = (2*pi*r)/T;
a = (v*v)/r;
System.out.println("\n\nAnswer");
System.out.printf("The centripetal acceleration is : %.2f m/s^2\n", a);
}
}
Hi all. This is my coding and it cannot run when I put decimal point. how to fix it?
Replace input.nextInt(); with input.nextDouble();
x = input.nextInt(); // It will simply ignore decimal values
Hence you need to use nextDouble()
x = input.nextDouble(); // This will read the entire decimal value
You read a int with
input.nextInt();
Try
input.nextDouble();
Try it.
import java.util.Scanner;
public class JavaScannerDouble {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String data = input.next();
double decimalValue = Double.parseDouble(data);
System.out.println("Decimal value : " + decimalValue);
// test of decimal value
double response = decimalValue / 0.1;
System.out.println("response : " + response);
}
}