So, The code SHOULD convert currencies, but it doesn't do it correctly. I have a variable k(Croatian kuna... 1 EURO = 7.5 KUNA)which is 1 and for example, if I want to convert 1 euro to 1 dollar, the program multiplies the amount (1) by 7.5, then I have that amount of euros in KUNA, and that Works. But, when I go to divide that result (7.5) with 6.3(1 DOLLAR IS 6.3 KUNA), I get the same number.
import java.util.Scanner;
public class Conv {
private double rez;
private double rez2;
private double svota;
Scanner ul = new Scanner(System.in);
public void PretvorbaInKunu(double y) {
System.out.print("Insert amomunt: ");
svota = ul.nextDouble();
rez2 = svota*y;
}
public void PR2(double x) {
rez = getRez2() / x;
}
public double getRez() {
return rez;
}
public double getRez2() {
return rez2;
}
public double getSvota() {
return svota;
}
}
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
public static void main(String[] args) {
double e = 7.5;
double d = 6.3;
double p = 9.5;
double k = 1.0;
Conv more = new Conv();
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
switch(iz) {
case "e":
more.PretvorbaInKunu(e);
break;
case "d":
more.PretvorbaInKunu(d);
break;
case "p":
more.PretvorbaInKunu(p);
break;
case "k":
more.PretvorbaInKunu(k);
break;
}
System.out.println(more.getRez2());
System.out.print(" To ");
String u = in.next();
switch(u) {
case "e":
more.PR2(e);
case "d":
more.PR2(d);
case "p":
more.PR2(p);
case "k":
more.PR2(k);
}
System.out.println(more.getSvota() + " " + iz + " is " + more.getRez() + " " + u);
}
}
The problem is in your second switch-case statement: You need to add a break at the end of every case.
If you change the class Vjezbica like this it should work:
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
public static void main(String[] args) {
double e = 7.5;
double d = 6.3;
double p = 9.5;
double k = 1.0;
Conv more = new Conv();
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
switch (iz) {
case "e":
more.PretvorbaInKunu(e);
break;
case "d":
more.PretvorbaInKunu(d);
break;
case "p":
more.PretvorbaInKunu(p);
break;
case "k":
more.PretvorbaInKunu(k);
break;
}
System.out.println(more.getRez2());
System.out.print(" To ");
String u = in.next();
switch (u) {
case "e":
more.PR2(e);
break;//added break here
case "d":
more.PR2(d);
break;//added break here
case "p":
more.PR2(p);
break;//added break here
case "k":
more.PR2(k);
break;//added break here
}
System.out.println(more.getSvota() + " " + iz + " is " + more.getRez() + " " + u);
//you should also close the scanner at the end...
in.close();
}
}
First of all - mistake was, as already pointed out by Tobias, the missing "break;"
But there are other mistakes in the code, e.g. Scanner is not closed.
I would also suggest to improve code quality. You could write an enum type that performs just calculation (no input - input should be separated). You can easily define currencies with different enum constructors then.
There was also discussion above if double or BigDecimal should be used. BigDecimal is an "expensive" type. I am wondering if float isn't enough, because currency values usually contain a precision of 2 digits - and if you are not dealing with very high amounts, a 32bit float type should already suffer.
I'd rewrite it as follows:
import java.util.Scanner;
//Currency Converter
public class Vjezbica {
private static enum Currency {
EURO(7.5), KUNA(1), DOLLAR(6.3), P(9.3);
private double cr;
Currency(double conversionRate) {
this.cr = conversionRate;
}
// precision: 2digits
public float fromKuna(double kuna) {
return (int) (((kuna) / cr) * 100) / 100f;
}
public float toKuna(double foreignCurrency) {
return (int) (((foreignCurrency) * cr) * 100) / 100f;
}
}
private static Currency readCurrency() {
Scanner in = new Scanner(System.in);
System.out.print("\t\tCurrency converter\nIz (e,p,d,k) - ");
String iz = in.next();
in.close();
switch (iz) { // no break required when returning directly
case "e":
return Currency.EURO;
case "d":
return Currency.DOLLAR;
case "p":
return Currency.P;
case "k":
return Currency.KUNA;
default:
throw new IllegalArgumentException("invalid input: " + iz);
}
}
private static float readAmount() {
Scanner ul = new Scanner(System.in);
float svota = ul.nextFloat();
ul.close();
return svota;
}
public static void main(String[] args) {
System.out.print(" From ");
Currency c1 = readCurrency();
System.out.print("Insert amomunt: ");
float svota = readAmount();
float amountInKuna = c1.toKuna(svota);
System.out.print(" To ");
Currency c2 = readCurrency();
float amountInC2 = c2.fromKuna(amountInKuna);
System.out.println(svota + " " + c1.toString() + " is " + amountInC2 + " " + c2.toString());
}
}
Not considered: conversion does first convert from X to Kuna, and then from Kuna to Y. In both conversions, we are performing an inprecise rounding (flooring instead of correct rounding, and flooring twice instead of just once).
Based on this suggestion, it would be even better if you calculate a precise conversion rate which allows direct conversion from X to Y in the end, and you perform a round operation on the final result then.
Related
//Inventory Items classs
import java.util.Scanner;
public class InventoryItems {
public int sackrice = 4;
public int animalfeed = 12;
public int trayeggs = 15;
public int bottlemilk = 9;
ItemSupplier supple = new ItemSupplier();
public void inventoryItem() {
System.out.println("\nAvailable items:\n");
sackrice = sackrice + supple.getRice();
System.out.println("Sack of rice: " + sackrice);
if(sackrice < 10)
System.out.println("Sack of rice low, please restock");
System.out.println();
System.out.println("Animal feed: " + animalfeed);
if(animalfeed < 10)
System.out.println("Animal feed low, please restock");
System.out.println();
System.out.println("Tray of eggs: " + trayeggs);
if(trayeggs < 15)
System.out.println("Tray of eggs low, please restock");
System.out.println();
System.out.println("Bottle of milk: " + bottlemilk);
if(bottlemilk < 15)
System.out.println("Bottle of milk low, please restock");
System.out.println();
press();
}
public static void press(){
Scanner input = new Scanner(System.in);
System.out.println("Press Enter to continue...");
String enter = input.nextLine();
}
}
//Item Supplier class
import java.util.Scanner;
public class ItemSupplier {
public int z;
Scanner scan = new Scanner(System.in);
public void ricesupplier() {
System.out.println("How many sacks of rice would you like to
order?");
z = scan.nextInt();
}
public int getRice() {
return z;
}
public void feedsupplier() {
}
public void eggsupplier() {
}
public void milksupplier() {
}
}
import java.util.Scanner;
public class InventoryManager{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int x;
int y;
do {
System.out.println("Input option:\n" + "\n1. Check inventory" + "\n2. Search item supplier" + "\n3. Exit\n");
x = scan.nextInt();
switch(x) {
case 1:
InventoryItems items = new InventoryItems();
items.inventoryItem();
break;
case 2:
ItemSupplier supply = new ItemSupplier();
do {
System.out.println("\nChoose supplier:\n" + "\n1. Rice supplier\n" + "2. Animal feed supplier\n" + "3. Egg supplier\n" + "4. Milk supplier\n" + "5. Back\n");
y = scan.nextInt();
switch(y) {
case 1:
supply.ricesupplier();
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
System.out.println("Invalid option");
break;
}
break;
} while (y != 5);
break;
case 3:
System.out.println("Program closed");
System.exit(0);
default:
System.out.println("Invalid option");
break;
}
} while(x != 3);
}
}
The "z" I get from getRice() is 0. It only takes the declared but initialized z. How do I get the "z" that was inputed in ricesupplier() method? Specifically, here: System.out.println("How many sacks of rice would you like to order?") and here z = scan.nextInt().
I'm really just a beginner. A lot of parts are still incomplete. I need to finish this problem first before I can proceed.
This won't be a direct answer to your question but here's some hints in order to improve your code and eventually solve your problem.
You should not make a new InventoryItems every time the user's input is 1. This will result into printing the initial inventory items, thus making your user order an item is useless
You should not make a new ItemSupplier every time the user's input is 2.
You don't need ItemSupplier in your InventoryItems
You don't need the variable z in ItemSupplier, you can directly return the input of the user in ricesupplier() method
thus if the user's input is 2 then you can just call ricesupplier() method and add it's return to the current items.sackrice
Hy guys i will need a quick help with my asigment. I tryed to debug this code and i dont know how do i got this error but when i try to calculate gpa it is sending me 0 instead of value from switch.
If user is pressing A and credits 4 it needs to return 4 * 4 but for letter A i am receiving 0
public class Gpa{
private int sumOfCredits;
private int sumOfPoints;
private int points = 0;
public Gpa(){
sumOfPoints=0;
sumOfCredits=0;
}
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
case "A":
points = 4;
break;
case "B":
points = 3;
break;
case "C":
points = 2;
break;
case "D":
points = 1;
break;
case "F":
points = 0;
break;
case "a":
points = 4;
break;
case "b":
points = 3;
break;
case "c":
points = 2;
break;
case "d":
points = 1;
break;
case "f":
points = 0;
break;
default:
points = -1;
}
return points;
}
public int getSumOfCredits(){
return sumOfCredits;
}
public int getSumOfPoints(){
return sumOfPoints;
}
public void addToTotals(String grade,int credits){
sumOfCredits =+ credits;
calcPoints(grade);
sumOfPoints =sumOfPoints + points * credits;
}
public double calcGPA(){
double gpa = sumOfPoints /sumOfCredits;
return gpa;
}
}
and this is my tester class:
import java.util.*;
public class ComputeGpa {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Gpa gpaC = new Gpa();
for (int i = 1; i <= 3; i++) {
System.out.printf("Enter grade (one character): ");
String grade = scan.next();
System.out.printf("Enter credits: ");
int credits = scan.nextInt();
gpaC.addToTotals(grade, credits);
System.out.printf("Sum Points: %d", gpaC.getSumOfPoints());
System.out.printf("\tSum Credits: %d\n", gpaC.getSumOfCredits());
}
System.out.printf("GPA: %.2f", gpaC.calcGPA());
}
}
in your calcGPA() method you are doing integer division when you want to do floating division. You either have to cast the sumOfPoints variable or the sumOfCredits to a double.
double gpa = sumOfPoints /sumOfCredits;
Is integer division in java and will return an integer value. Chances are it is always a value between 0 and 1, which will be equivalent to 0 after being casted to an integer. See if casting them to double fixes it.
double gpa = (double)sumOfPoints / (double)sumOfCredits;
You are also redefining points on each loop here:
public static int calcPoints(String grade) {
int points = 0;
switch (grade) {
Which means that instead of changing the global variable points you are changing the local variable points. So you need to remove that local variable points so it uses the global one, also you dont need to return anything so just use void:
public void calcPoints(String grade) {
switch (grade) {
//cont
Part of my java code is not running. I am fairly new to java and have been working out some new environment changes. My class was told to build a windchill temperature calculator. My main issue is that my code works up to the for (ws = wsp; ws <= c; ws += 0.5) then stops.
import java.util.*;
class Assign1
{
public static void main(String args[])
{
Menu user = new Menu();
Menu.mainmenu();
user.acceptSelection();
}
}
class Menu
{
public static void mainmenu()
{
System.out.println("Temperature Analysis MENU");
System.out.println("1.W)ind Chill Temperature");
System.out.println("0.E)xit");
System.out.println("Enter Selection:");
}
public void acceptSelection()
{
Scanner stdin = new Scanner(System.in);
String selection = stdin.nextLine();
char choice = selection.charAt(0);
switch(choice)
{
case 'W':
case 'w':
case '1':
processing.process(); break;
case 'E':
case 'e':
case '0':
System.out.println("E"); break;
}
}
}
class processing
{
public static void process()
{
Scanner stdin = new Scanner(System.in);
System.out.println("\n\n\n\n\n\n\n");
System.out.print("Please enter START air temp in celsius (decimal) MUST be BELOW 9: ");
double sa = stdin.nextDouble();
System.out.print("Please enter END air temp in celsius (decimal) MUST be BELOW 9: ");
double ea = stdin.nextDouble();
System.out.print("Please enter wind speed (decimal) FROM 8km/h to: ");
double w = stdin.nextDouble();
System.out.println("\n==================================================================\n");
calculation(sa, ea, w);
}
public static void calculation(double a, double b, double c)
{
double wsp = 8.0;
double airTemp;
double ws;
int size = 150;
double[] wChill = new double[size];
int count = 0;
System.out.print(" " + a);
while(a <= b)
{
System.out.print(" " + a);
a +=5;
count++;
}
System.out.print(" " + b);
int count2 = 0;
while(wsp <= c)
{
count2++;
wsp += 0.5;
}
double[][] chart = new double[count2][count];
int i = 0, j = 0, k = 0;
This is where it stops working. I cannot get it to print my loop out. Any help in fixing my problem would be appreciated as well as notes to my code as i am trying to improve. I am using JGrasp if it helps.
for (ws = wsp; ws <= c; ws += 0.5)
{
System.out.println(ws + " ");
for (airTemp = a; airTemp <= b; airTemp += 5.0)
{
if ((ws + 0.5) > c)
{
System.out.printf( "%2d %2d", c , chart[k][i]);
}
else
{
wChill[i] = (13.12 + (0.6215*airTemp)+(-11.37*Math.pow(ws, 0.16))+(0.3965*airTemp*Math.pow(ws, 0.16)));
chart[k][i] = wChill[i];
System.out.print(chart[k][i] + " ");
}
i++;
}
k++;
}
}
}
According to you code you have a while loop
while(wsp <= c) {...}
then you have a for loop
for (ws = wsp; ws <= c; ws += 0.5)
so as you can see ws is assigned the value of wsp which has in the while already exceeded the value of c
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
So I'm doing an assignment on modular programing and here Im getting a bracket expected error. Here is the code:
import java.util.*;
public class stlab09
{
public static void main (String args[])
{
System.out.println("\nLAB09 90 POINT VERSION\n\n");
enterData();
computeGPA();
displayData();
}
static String lGrade1;
static String lGrade2;
static String lGrade3;
static String lGrade4;
static int cHours1;
static int cHours2;
static int cHours3;
static int cHours4;
static String dummy;
public static double gpa;
public static void enterData()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter course 1 Grade ===>> ");
lGrade1 = in.nextLine();
System.out.print("enter course 1 Hours ===>> ");
cHours1 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 2 Grade ===>> ");
lGrade2 = in.nextLine();
System.out.print("enter course 2 Hours ===>> ");
cHours2 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 3 Grade ===>> ");
lGrade3 = in.nextLine();
System.out.print("enter course 3 Hours ===>> ");
cHours3 = in.nextInt(); dummy = in.nextLine();
System.out.print("Enter course 4 Grade ===>> ");
lGrade4 = in.nextLine();
System.out.print("enter course 4 Hours ===>> ");
cHours4 = in.nextInt(); dummy = in.nextLine();
}
public static void computeGPA()
{
Grades.gradeValue();
Grades.courseValue();
Grades.getGPA();
}
public static void displayData()
{
System.out.println();
System.out.println("Course1 Grade: " + lGrade1 + " Course1 Credit Hours: " + cHours1);
System.out.println("Course2 Grade: " + lGrade2 + " Course2 Credit Hours: " + cHours2);
System.out.println("Course3 Grade: " + lGrade3 + " Course3 Credit Hours: " + cHours3);
System.out.println("Course4 Grade: " + lGrade4 + " Course4 Credit Hours: " + cHours4);
System.out.println();
System.out.println("Current GPA: " + gpa);
}
}
public class Grades() ***<<<<<<<<<<<<<<<<<< bracket expected here***
{
public static void gradeValue()
{
int value = 0;
char lg1 = lGrade1.charAt(0);
switch(lg1)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal1 = value;
char lg2 = lGrade2.charAt(0);
switch(lg2)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal2 = value;
char lg3 = lGrade3.charAt(0);
switch(lg3)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal3 = value;
char lg4 = lGrade4.charAt(0);
switch(lg4)
{
case 'A': value = 4; break;
case 'B': value = 3; break;
case 'C': value = 2; break;
case 'D': value = 1; break;
case 'F': value = 0; break;
}
int gVal4 = value;
}
public static void courseValue()
{
int cVal1 = gVal1 * cHours1;
int cVal2 = gVal2 * cHours2;
int cVal3 = gVal3 * cHours3;
int cVal4 = gVal4 * cHours4;
}
public static void getGPA()
{
double totalValue = cVal1 + cVal2 + cVal3 + cVal4;
double totalHours = cHours1 + cHours2 + cHours3 + cHours4;
double gpa = totalValue / totalHours;
}
}
So yeah I need some help figuring this out because I'm kinda going crazy about it. The expected program is supposed to use keyboard input of letter grades and course hours to compute GPA and grades. The assignment is to get that outcome but the main method must stay exactly as is, and almost every method was provided to me and i just had to organize them.
You have declared the inner class Grades as if it's a method (you added () onto the end of it), look at how the class stlab09 is declared, there aren't any ().
I wanna be able to read the input star and calculate the distance in a method and the call the answer in the main. How do i do this? Here's what I have so far. what this does is it finds the distances of 5 stars which i need to show.
thanks!!
package desktop;
import java.util.Scanner;
import javax.swing.JOptionPane;
// *import io because of the file writing
public class distance {
public static void main (String [] args) {
double d = place ();
}
public static double findDistance (String distance) {
double result;
Scanner sc = new Scanner(System.in);
System.out.println("Where would you like to go?");
System.out.println();
System.out.println("Enter 1 for Proxima Centauri");
System.out.println("Enter 2 for Bernard's Star");
System.out.println("Enter 3 for Sirius A");
System.out.println("Enter 4 for Epsilon Eridani");
System.out.println("Enter 5 for Betelgeuse");
System.out.println();
System.out.println();
double operator;
int place = sc.nextInt();
switch (place) {
case 1:
result = timePC ();
System.out.println();
System.out.println();
System.out.println("Time to Proxima Centauri is: " + String.format("%.4g",timePC()) + " lightyears");
break;
case 2:
result = timeBS ();
System.out.println();
System.out.println();
System.out.println("Time to Bernand's Star is: " + String.format("%.4g",timeBS()) + " lightyears");
break;
case 3:
result = timeSA ();
System.out.println();
System.out.println();
System.out.println("Time to Sirius A is: " + String.format("%.4g",timeSA()) + " lightyears");
break;
case 4:
result = timeEE ();
System.out.println();
System.out.println();
System.out.println("Time to Epsilon Eridani is: " + String.format("%.4g",timeEE()) + " lightyears");
break;
case 5:
result = timeB ();
System.out.println();
System.out.println();
System.out.println("Time to Betelgeuse is:" String.format("%.4g",timeB()) + " lightyears" );
break;
default:
System.out.println("Invalid function");
}
return place;
}
public static double timePC () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 4.010*Math.pow(10, 16);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeBS () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 5.637*Math.pow(10, 16);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeSA () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 3.592*Math.pow(10, 18);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeEE () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 2.930*Math.pow(10, 18);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeB () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 6.079*Math.pow(10, 18);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
}
Your main method should probably look something like this:
public static void main (String [] args) {
System.out.println(findDistance());
}
which would require you change your method header for findDistance to be:
public static double findDistance () { ...
(Since you never use the string distance parameter).
I changed your method signature since you were not using the variable being passed in and renamed the Distance class properly. I also made the findDistance method not static and the rest of the methods shouldn't be static methods since you could create an instance of the class Java Classes. You also have a couple of unused primitive types that I left in there.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Distance {
public double findDistance () {
double result;
Scanner sc = new Scanner(System.in);
System.out.println("Where would you like to go?");
System.out.println();
System.out.println("Enter 1 for Proxima Centauri");
System.out.println("Enter 2 for Bernard's Star");
System.out.println("Enter 3 for Sirius A");
System.out.println("Enter 4 for Epsilon Eridani");
System.out.println("Enter 5 for Betelgeuse");
System.out.println();
System.out.println();
double operator;
int place = sc.nextInt();
switch (place) {
case 1:
result = timePC ();
System.out.println();
System.out.println();
System.out.println("Time to Proxima Centauri is: " + String.format("%.4g",timePC()) + " lightyears");
break;
case 2:
result = timeBS ();
System.out.println();
System.out.println();
System.out.println("Time to Bernand's Star is: " + String.format("%.4g",timeBS()) + " lightyears");
break;
case 3:
result = timeSA ();
System.out.println();
System.out.println();
System.out.println("Time to Sirius A is: " + String.format("%.4g",timeSA()) + " lightyears");
break;
case 4:
result = timeEE ();
System.out.println();
System.out.println();
System.out.println("Time to Epsilon Eridani is: " + String.format("%.4g",timeEE()) + " lightyears");
break;
case 5:
result = timeB ();
System.out.println();
System.out.println();
System.out.println("Time to Betelgeuse is:" + String.format("%.4g",timeB()) + " lightyears" );
break;
default:
System.out.println("Invalid function");
}
return place;
}
public static double timePC () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 4.010*Math.pow(10, 16);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeBS () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 5.637*Math.pow(10, 16);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeSA () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 3.592*Math.pow(10, 18);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeEE () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 2.930*Math.pow(10, 18);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static double timeB () {
double result;
double CC = 3.16887*Math.pow(10,7);
double distance = 6.079*Math.pow(10, 18);
double velocity = 3*Math.pow(10, 8);
result = (distance / velocity)/CC;
return result;
}
public static void main(String[] args){
Distance d = new Distance();
d.findDistance(null);
}
}