• 0

Java calling/importing classes


Question

I am working on a program that incorperates many little programs in to it. The user is asked what they would like to run and based on that the program will run that class. I am not having any luck calling classes and i am not sure what i am doing wrong. I also know that you can import classes with java and have tried this with no success. Any help is appreciated thanks.

import java.util.Scanner;

public class bundle{

	public static void main(String[] args){
		int selection = 0;


		System.out.println("1. Run Temp Conversion program");

		Scanner in = new Scanner(System.in);
		selection = in.nextInt();

		if(selection == 1){
			temp();

		}
	}



	public class temp{
		public static void CtF(){
			int CtF;
			int C;
			System.out.println("Enter a Celcius Temp: ");
			Scanner in = new Scanner(System.in);

			C = in.nextInt();
			in.close();

			CtF = C*9/5+32;
			System.out.printf("Your Temp in Fahrenheit is: ");
			System.out.print(CtF);
		}

		public static void FtC(){
			int FtC;
			int F;
			System.out.println("Enter a Fahrenheit Temp: ");
			Scanner in = new Scanner(System.in);

			F = in.nextInt();
			in.close();

			FtC = (F - 32)*5/9;

			System.out.printf("Your Temp in Celcius is: ");
			System.out.print(FtC);
		}

		public static void main(String[] args){
			int select = 0;

			System.out.println("1. If you wish to convert from Celcius to Fahrenheit");
			System.out.println("2. If you wish to convert from Fahrenheit to Celcius");

			Scanner in = new Scanner(System.in);
			select = in.nextInt();

			if(select == 1){
				CtF();
			}
			if(select == 2){
				FtC();
			}
			if(select == 3){
				System.exit(0);
			}

		}
	}
}

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

When you know which app you want to run, just call its main(...) method. When you have lots of apps, use the user's input to control a switch statement that has all the calls to each app's main(...)

switch (selection) {

case 1: temp.main(null); break;

case 2: OtherClass.main(null); break;

...

default: System.out.println("Invalid selection.");

}

The class files for these apps must be in your classpath, and you import them at the start of your main java program just like you imported java.util.Scanner.

ps: temp is a really bad class name - Java convention is that class names begin with a capital letter, and temp is used all the time as an abbreviation for temporary!

Edited by JamesCherrill
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.