Trying to combine multiple programs together - java

I am trying to take 3 different programs I have created and put them under a single class. My professor has stated I must do this and I have no clue on how to. I am not looking for a hand out here, just some how I can do this quickly and efficiently. I am also trying to figure out how to call from the same scanner for each program or if I should just make multiple ones.
import java.util.Scanner;
public class AssignmentOneFahrenheit {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesF;
double degreesC;
Scanner keyboard = new Scanner(System.in);
degreesF = keyboard.nextDouble(); //Allows user to input decimal number
keyboard.close();
System.out.println("The temperature in Degrees Celsius is: ");
degreesC = 5*(degreesF - 32)/9;
System.out.printf("%.2f", degreesC);
}
import java.util.Scanner;
public class AssignmentOneHate {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a line containing 'hate'.");
String text = keyboard.nextLine();
System.out.println("I have changed that line to read: ");
System.out.println(text.replaceFirst("hate", "love"));
keyboard.close();
}
import java.util.Scanner;
public class AssignmentOneVerticalDisplay {
public static void main(String[] args) {
// TODO Auto-generated method stub
int userInput;
System.out.println("Please enter a 4 digit integer.");
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
I basically just copied and pasted 2 programs I created. If anybody can help guide me in the correct direction here that would be great.

You can use the Double.parseDouble(String string); function together with a try-Catch to check if it was a number or a string in the input.
(...)
String text = keyboard.nextLine();
try {
//We try and assume that it is a number
Double number = Double.parseDouble(text);
/**
* Do stuff with the number like in the 1st program
*/
}
catch (NumberFormatException e)
{
//The input turned out not to be a number.
/**
* Do stuff here with the string like the 2nd program
*/
}

Am not really certain what your trying to accomplish, but if it's really necessary you combine all three classes together try using Java Inner Classes

I think that your professor is looking for a more object oriented solution. You can create a class that contains the three programs as separated methods like this
import java.util.scanner;
public class AssignmentScanner {
public double convertToCelsius() {
Scanner keyboard = new Scanner(System.in);
double degreesF = keyboard.nextDouble();
keyboard.close();
return 5*(degreesF - 32)/9;
}
public String replaceHate() {
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
String replacedText = text.replaceFirst("hate", "love");
keyboard.close();
return replacedText;
}
public int oneVerticalDisplay() {
Scanner keyboard = new Scanner(System.in);
int userInput = keyboard.nextInt();
System.out.println(userInput / 1000);
userInput = userInput % 1000;
System.out.println(userInput / 100);
userInput = userInput % 100;
System.out.println(userInput / 10);
System.out.println(userInput % 10);
keyboard.close();
}
}
You still need to create a main program that use this object like this:
public class AssignmentMain {
public static void main(String[] args) {
AssignmentScanner assignmentScanner = new AssignmentScanner();
System.out.println("Hello, I can convert Fahrenheit to Celsius!");
System.out.println("Please enter the degrees Fahrenheit you want converted.");
double degreesC = assignmentScanner.convertToCelsius();
System.out.println("The temperature in Degrees Celsius is: ");
System.out.printf("%.2f", degreesC);
System.out.println("Please enter a line containing 'hate'.");
String replacedText = assignmentScanner.replaceHate();
System.out.println("I have changed that line to read: ");
System.out.println(replacedText);
System.out.println("Please enter a 4 digit integer.");
assigmentScanner.oneVerticalDisplay();
}
}
This way your main program only knows about the AssignmentScanner and its three methods. This make the main program easier to read and maintain. There is still room for improvement but i think it's OK for a first approach.

Related

How to create a helper method that takes 2 double inputs into a class global array?

I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;
public class FunFormulas {
public void sd(){
double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
if (durationOfStorm > 0)
System.out.println("The storm will last: " + durationOfStorm);
}
public void sl(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of seconds since the lightning strike:");
double secondsSinceLightning = Double.valueOf(scanner.nextLine());
double distanceFromLightning = (1100 * secondsSinceLightning);
System.out.println(distanceFromLightning);
}
public void si(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the edge of cube in inches:");
double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
if (edgeOfCubeInInches < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
System.out.println(weightOfCube);
}
public void dt(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the time in hours:");
double timeInHours = Double.valueOf(scanner.nextLine());
if (timeInHours < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
System.out.println("Enter the rate of speed in mph:");
double rateOfSpeed = Double.valueOf(scanner.nextLine());
if (rateOfSpeed < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double distanceTravelled = (rateOfSpeed * timeInHours);
System.out.println(distanceTravelled);
}
public void sa(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your weight in pounds:");
double weight = Double.valueOf(scanner.nextLine());
weight = weight * 0.4536;
System.out.println("Enter your height in inches:");
double height = Double.valueOf(scanner.nextLine());
height = height * 2.54;
double BSA = ((Math.sqrt(weight * height)) / 60);
System.out.println(BSA);
}
public double get_S_Input(String promptStr){
//Scanner helper method
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double value = Double.valueOf(scanner.nextLine());
if (value < 0 ){
System.out.println("ERROR: please enter a non-negative number!!!");
}
return value;
}
public void get_2_Invals(String promptStr){
/*Prompt the user with the promptStr passed in as a parameter
ii. Read in the first double precision value entered by the user with the Scanner
iii. Read in the second double precision value entered by the user with the Scanner
iv. Check to make sure the values entered by the user are non-negative
a. If either number entered by the user is negative, the method should print out an
error message, and return to step i. above.
b. If the number is non-negative (that is greater than or equal to zero) the method
should record the numbers obtained from the user in a class-global array of
doubles and exit.*/
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double firstValue = scanner.nextInt();
double secondValue = scanner.nextInt();
if (firstValue < 0 || secondValue < 0)
System.out.println("ERROR: please enter non-negative number!");
else
}
public static void main(String [] args){
FunFormulas fun = new FunFormulas();
fun.sd();
}
}

How to apply operations on scanner inputs in java?

I have the following code:
import java.util.Scanner;
public class Calculator{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = keyboard.nextDouble();
while (go){
String next = keyboard.next();
if (next.equals("done") || next.equals("calculate")){
System.out.print(grade);
go = false;
}else{
grade+=keyboard.nextInt();
}
}
I am trying to find the average as it is a grade calculator, what i want to know is how would I apply The addition operation only to scanner inputs, and then ultimately find the average by how mnay inputs were entered.
Sample input:
60
85
72
done
Output:
72 (average) ===> (217/3)
You need a counter (e.g. count as shown below). Also, you need to first check the input if it is done or calculate. If yes, exit the program, otherwise parse the input to int and add it to the existing sum (grade).
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
boolean go = true;
System.out.println("PLEASE ENTER YOUR GRADES");
double grade = 0;
int count = 0;
while (go) {
String next = keyboard.nextLine();
if (next.equals("done") || next.equals("calculate")) {
go = false;
} else {
grade += Integer.parseInt(next);
count++;
}
}
System.out.println((int) (grade / count) + " (average) ===> (" + (int) grade + "/" + count + ")");
}
}

only allowing java scanner to allow numbers

I've been having issues catching non numbers.
I tried try / catch but I can't grasp a hold of it. If anything I get it to catch non numbers, but doesn't let the user try entering again... It just stops my code completely.
Here is my code:
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner angle1 = new Scanner(System.in); // Reading from System.in
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
Scanner angel2 = new Scanner(System.in);
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
Scanner angel3 = new Scanner(System.in);
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();
//this is just telling how much degrees the user had in total if they didnt match up to triangle standards
This should get you started.
package triangle;
import java.util.Scanner;
public class triangle {
public static void main(String[] args){
//explaining what the program is going to do
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\n");
System.out.println("this automated program will tell you if the angle you entered is isoceles, eqilateral or scalene");
//creating input 1,2,3 for user
Scanner s = new Scanner(System.in); // Reading from System.in
String line;
int [] angles = new int [3];
int count = 0;
do {
System.out.print("Enter angle degree number " + (count+1) + ": ");
line = s.nextLine();
while (true ) {
try {
angles[count] = Integer.parseInt(line);
System.out.println("You entered " + angles[count]);
count++;
break;
} catch (NumberFormatException e ) {
System.out.println("Invalid number: try again: ");
line = s.nextLine();
}
}
} while (count < 3);
}
}
You have a simple issue.. You just use one Scanner for the code in main method.
package triangle;
import java.util.Scanner;
public class traingle {
public static void main(String[] argc){
System.out.println("You will be able to enter 3 angles to equal the sum of a triangle,\nthis automated program will tell you if the angle you entered is issosoliese, eqilateral or scalene");
Scanner angle1 = new Scanner(System.in);
System.out.println("Enter angle degree number 1: ");
int n = angle1.nextInt();
System.out.println("Enter angle degree number 2: ");
int n2 = angel2.nextInt();
System.out.println("Enter angle degree number 3: ");
int n3 = angel3.nextInt();

why does my scanner(system.in) run twice

I am new to java, been self teaching for the last week. I cannot find the reason why the if else statement runs twice. here is the whole code, I know is simple but still trying to learn.
package tickets;
import java.util.Scanner;
public class tickets {
public static void main(String[] args) {
//program designed to ask how many visitors
//are in a party of people and work out
//the total cost of the entry tickets.
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
//adding code that would give a percentage discount for
//4 adults or more
{
if ( adult1.nextInt() >= 4
{
double adult2 =( adult1.nextInt() * percentage);
}else {
double adult2 = (adult * adult1.nextInt());
System.out.println("please enter the amount of consessions");
Scanner consession1 = new Scanner (System.in);
double consession2 = (consession *consession1.nextInt());
System.out.println("please enter the amount of children");
Scanner child1 = new Scanner (System.in);
double child2 = (child * child1.nextInt());
System.out.println( "total"+" " + (adult2 +consession2 + child2) );
System.out.println("hope you enjoy your visit today!");
//woop woop it works!!!!!!!!!!
}
}
}
}
The reason why your program asked for two inputs was because adult1 is the name of your scanner and in your if statement the condition was if the user input is >= 4 then take an Integer input again from the user and multiply that with percentage and store it in adult2, instead this should be done as follows
public static void main(String[] args)
{
double adult = 12.50;
double consession = 9.90;
double child = 6.25;
double percentage = 0.80;
double adult2 = 0.0 // you dont need to redeclare below
System.out.println("please enter the amount of adults");
Scanner adult1 = new Scanner (System.in);
// remove this unneccessary bracket {
int num = adult1.nextInt();
if ( num >= 4)
{
adult2 =( num * percentage);
}
else
{
adult2 = (adult * num);
}
System.out.println("Adult2 is " + adult2);
}
Store the int from the scanner and use that value in your ifs and calculations. You're calling nextInt() more than once and each time you get another int.
After you enter the if or else you will wait for more input of the integer type stopping the program.

Scanner inside method does not wait for answer

Have been struggling with this for a day, reading the discussion forum back and forth, no result. Anyone can tell me why the second call of the function aMenu() returns a zero and does not wait for new user input instead? I tried various things, like hasNextInt(), nextLine(), nothing worked. Shouldn't hasNextInt() block until the user writes something? How can I solve this? Thanks.
package FirstJavaPackage;
import java.util.Scanner;
public class testScanner
{
public static void main(String[] args)
{
int choice = aMenu();
System.out.println("You typed: "+choice);
choice = aMenu();
System.out.println("You typed: "+choice);
}
public static int aMenu()
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
Scanner keyboard = new Scanner(System.in);
if (keyboard.hasNextInt())
result = keyboard.nextInt();
keyboard.close();
return result;
}
}
The output is:
In aMenu... enter an int:
2
You typed: 2
In aMenu... enter an int:
You typed: 0
You need to re-use the same Scanner object across the calls to aMenu():
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int choice = aMenu(keyboard);
System.out.println("You typed: "+choice);
choice = aMenu(keyboard);
System.out.println("You typed: "+choice);
}
public static int aMenu(Scanner keyboard)
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
result = keyboard.nextInt();
return result;
}
For further discussion, see How to use multiple Scanner objects on System.in?
After the first call, you actually close the System.in input stream.
From the Scanner.close() documentation:
When a Scanner is closed, it will close its input source if the source
implements the Closeable interface.
Try not to close your scanner at the end of aMenu: initialize the scanner outside the aMenu method and make the method use it.
Since scanner.close will close the entire input source, you should pass scanner to your aMenu method and do something like this:
import java.util.Scanner;
public class TestScanner
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int choice = 0;
do
{
choice = aMenu(keyboard);
System.out.println("You typed: " + choice);
} while (choice > 0);
keyboard.close();
}
public static int aMenu(Scanner keyboard)
{
int result = 0;
System.out.println("In aMenu... enter an int: ");
if (keyboard.hasNextInt())
result = keyboard.nextInt();
return result;
}
}

Categories