import java.util.Scanner;
import java.text.DecimalFormat;
public class WeightConverter
{
private double numOfLbs2Conv, numOfKilos2Conv, converted2Pounds, converted2Kilograms;
private final double WEIGHT_CONVERSION_FACTOR = 2.20462262;
private int desiredDecimalPlaces;
private boolean toKilos, toPounds;
public void readPoundsAndConvert()
{
toKilos = true;
System.out.print("Enter the number of pounds to convert to "
+ "kilograms: ");
Scanner keyboard = new Scanner(System.in);
numOfLbs2Conv = keyboard.nextDouble();
converted2Pounds = numOfLbs2Conv / WEIGHT_CONVERSION_FACTOR;
}
public void readKilogramsAndConvert()
{
toPounds = true;
System.out.print("Enter the number of kilograms to convert to "
+ "pounds: ");
Scanner keyboard = new Scanner(System.in);
numOfKilos2Conv = keyboard.nextDouble();
converted2Kilograms = numOfKilos2Conv * WEIGHT_CONVERSION_FACTOR;
}
public void displayBothValues()
{
System.out.print("How many places after the decimal would you like? ");
Scanner keyboard = new Scanner(System.in);
desiredDecimalPlaces = keyboard.nextInt();
String decimalCounter = "0.";
for (int i = 0; i < desiredDecimalPlaces; i++)
{
decimalCounter = decimalCounter + "0";
}
DecimalFormat decimalsConverted = new DecimalFormat(decimalCounter);
if (toKilos)
{
System.out.println("The number of kilograms in "
+ decimalsConverted.format(numOfLbs2Conv) + " pounds is "
+ decimalsConverted.format(converted2Kilograms) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
if (toPounds)
{
System.out.println("The number of pounds in "
+ decimalsConverted.format(numOfKilos2Conv) + " kilograms is "
+ decimalsConverted.format(converted2Pounds) + ".");
System.out.print("Press Enter to continue ... ");
System.out.println("");
keyboard.nextLine();
}
}
}
Hi all.I'm having trouble getting this together. The output is screwed. If the user converts to pounds (readPoundsAndConvert()) first, the output will say that the converted answer is 0. If the user convert kilograms first, the kilograms will convert properly and then for somereason the readPoundsAndConvert() method will be called an d behave properly. I have no clue why this is happening and have been spending hours on it. Can someone tell me how to get this to behave properly? If you need me to post the rest of the program, I will.
You're using your variables backwards... In readPoundsAndConvert() you're storing the converted value in converted2Pounds, but when you try to display it, you're reading from converted2Kilograms.
It looks like you're setting toKilos and toPounds to true in your two "convert" methods, but you aren't simultaneously setting the other to false. Thus, if you've called one of the convert methods before, when you call displayBothValues() both toKilos and toPounds will be true and both will be printed.
Related
I am fairly new to Java and am attempting to build a "Top 10 Java Projects for Beginners" project, more specifically, a temperature converter. My code throws the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at TempConvert.convertToFar(TempConvert.java:78)
at TempConvert.main(TempConvert.java:15)
I was originally using the scanner "*.nextDouble()" method to grab the double but changed it to the "parseDouble" method as I thought this was perhaps the issue. Alas, this has not helped. Any help resolving this would be greatly appreciated!
public static double convertToFar()
{
Scanner in = new Scanner(System.in);
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
userDouble = Double.parseDouble(userEntry);
in.close();
formula = (userDouble - 32) * (5/9);
return formula;
}
I think that the in.nextLine() in the methods you wrote eventually collided with the string that was inputted by the user before the input stream had been closed.
I created one Scanner object and sent it to the methods so that they will be able to use that same object. I close it only when the program ends once the user enters 'E'. It worked for me:
import java.util.*;
public class TempConvert {
public static void main(String[] args)
{
double far, cel;
char userChoice;
Scanner in = new Scanner(System.in); // I added this line
userChoice = displayMenu(in);
while (userChoice != 'E')
{
if (userChoice == 'F')
{
far = convertToFar(in);
System.out.println("Converted: " + far + "\u00B0");
userChoice = displayMenu(in);
}
else if (userChoice == 'C')
{
cel = convertToCel(in);
System.out.println("Converted: " + cel + "\u00B0");
userChoice = displayMenu(in);
}
else
{
System.out.println("Invalid Entry");
userChoice = displayMenu(in);
}
}
in.close(); // closing the input stream when the program ends
}
public static void displayTitle()
{
String title = "||---- TEMPERATURE CONVERTER ----||";
String one = "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-";
String two = "|| ** Auth: Arranic ||";
String three = "|| ||";
System.out.println(one + "\n" + three + "\n" + title + "\n" + three + "\n" + two + "\n" + three + "\n" + one);
}
public static char displayMenu(Scanner input)
{
ClearScreen();
displayTitle();
System.out.println("\n");
String choiceString;
char choice;
System.out.println("F - FARENHEIGHT C - CELSIUS E - EXIT");
System.out.print("CONVERT TO: ");
choiceString = input.nextLine();
// input.close() --> removed this line
choice = Character.toUpperCase(choiceString.charAt(0));
return choice;
}
public static void ClearScreen()
{
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static double convertToCel(Scanner in)
{
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Fahrenheit: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble - 32) * (5.0/9);
return formula;
}
public static double convertToFar(Scanner in)
{
String userEntry;
double userDouble, formula;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble * (9.0/5)) + 32;
return formula;
}
}
BTW your calculations are not precise. You should remember that integer/integer = integer. That said, writing 5/9 or 9/5 is not accurate, since the result is an integer type number, and not a double type number, as I assume you wanted to get. (5/9 = 0, 9/5 = 1) So you should have added a 5.0 or 9.0 to the calculations so that Java would understand that you want to get a double type result (double/int = double).
And one more thing, your calculations where misplaced (fahrenheit to celsius gave me the opposite result and vice versa) so I switched them up ;).
I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).
I have a Java program that is designed to take an input of customers, then run a loop for each. Then the user has 3 choices to input: clowns, safari sam, or music caravan. I just don't understand what is wrong with my if statements. You see, if a user enters "clowns", the corresponding if statement works fine and the if statement is executed. However, if a user inputs "safari sam" or "music caravan", the if statements do not execute.
My question is: If the first if statement is executed, then why are the other 2 being skipped (not executing when conditions are met)?
CODE:
import java.util.Scanner;
public class FunRentals {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of customers: ");
int num_customers = new_scan.nextInt();
for(int i = 1; i<=num_customers; i++){
System.out.println("Please enter the service used (\"Clowns\", \"Safari Sam\", or \"Music Caravan\") for customer #"+i);
String service_type = new_scan.next();
String service_type_real = service_type.toLowerCase();
if(service_type_real.equals("clowns")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ clowns(additional_hours));
}
else if(service_type_real.equals("safari sam")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ safari_sam(additional_hours));
}
else if(service_type_real.equals("music caravan")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ music_caravan(additional_hours));
}
}
}
public static double clowns(double a){
double additional_cost = a*35;
double total_cost = additional_cost + 45;
return total_cost;
}
public static double safari_sam(double a){
double additional_cost = a*45;
double total_cost = additional_cost + 55;
return total_cost;
}
public static double music_caravan(double a){
double additional_cost = a*30;
double total_cost = additional_cost + 40;
return total_cost;
}
}
You need to use nextLine() instead of next() to read user input. nextLine() will read the entire line, but next() will only read the next word.
For reading String provided by the user in console you have to use .nextLine()
So try by using this -
String service_type = new_scan.nextLine();
This should store the value of whatever you are providing in the console to the String "service_type".
I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
this is what ive tried
import java.util.Scanner;
class VariableExample
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
string e = scan.next();
string f = scan.next();
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
}
i told you... im really new
You forgot to declare entry point i.e. main() method, String S should be capital and in System.out.println() you used wrong variables:
class VariableExample {
public static void main(String... args) { // Entry point..
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value");
int a = scan.nextInt();
int b = scan.nextInt();
System.out.println("Please enter an integer value");
double c = scan.nextDouble();
double d = scan.nextDouble();
System.out.println("Please enter an integer value");
String e = scan.next(); // String S should be capital..
String f = scan.next();
System.out.println("Your integer is: " + a + " " + b + ", your real number is: " + c + " " + d
+ " and your string is: " + e + " " + f); // here you used wrong variables
}
}
If still your problem not clear then let me know where you actually stuck.
There are a couple of issues.
(1) You need to declare an "entry" point for your program. In Java, you must create a method with the exact signature:
public static void main(String args) {
// Your code here
}
(2) The "string" type in Java is capitalized.
(3) You are referencing variables that have been neither declared nor defined:
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
In this case, you've never told Java what the value of intValue, etc is. It seems like you want to use the variables you have declared and defined like:
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
(4) It looks like you're reading in two sets of variables for each prompt. Based on your prompt "Please enter an...", you really are expecting one input.
Altogether, I think your code should look like this:
class VariableExample {
public static void main(String args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer value: ");
int a = scan.nextInt();
System.out.println("Please enter a double value: ");
double c = scan.nextDouble();
System.out.println("Please enter a string: ");
String e = scan.next();
System.out.println("Your integer is: " + a + ", your real number is: "
+ c + " and your string is: " + e);
}
}
I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)