Hello I am a fairly new to Java, below I have created a program for calculating the distance between two cites that is inputed by the user. For the second part of my program I need to have a menu system and the constant SPEED value to change according to the type of road that is selected by the user before hand in the menu system.
So I figure I need to the change the constant Speed value depending on what the user has selected before hand, I understand that I need to use some sort of 'switch' and methods to cut the code down (which I don't quite get), Also how would I get the program work again without restarting from the beginning, would this be done by a boolean value? Is there a book you recommend reading or a similar piece of code I could look through to get an idea where to start. It took me a while just to do this which I understantd is pretty basic so any help would be appreciated.

 import java.math.*;
 public class TravelPrograms {
    public static final double SPEED = 50;
    public static void main(String[] args) {

        //local variables 
        String city1;
        String city2;
        int hours;
        int mins;
        int distance;
        double timeInMins = 0;
        int timeInHours;

        // prints out user prompt 
        System.out.println ("Welcome to Isfandyar Ali Travel Calculator" + "\n");

        System.out.println ("====================================================="+ "\n");

        System.out.print ("Please enter the name of the first city: ");
        city1 = UserInput.readString();
        System.out.println(); // insert blank line

        System.out.print ("Please enter the name of the second city: ");
        city2 = UserInput.readString();

        System.out.println(); // insert blank line
        System.out.print ("please enter the distance in miles: ");
        distance = UserInput.readInt();

        System.out.println ("============================Result========================"+ "\n");

        //Error message recieved if the distance is negative
        if (distance < 1) {
            System.out.println ("Error. distance must be a positive nmumber");
        }
        else {


            timeInMins = (distance/SPEED*60);
            timeInHours = (int)(timeInMins/60);
            timeInMins = timeInMins -(timeInHours *60);
            timeInMins = Math.round(timeInMins);
            mins = (int) timeInMins;
            hours = (int) timeInHours;

        System.out.println("The time required to travel " + distance+" miles"+" between " + city1+ "and " + city2 +" is " + hours+" hours and "+mins+" minutes"+ "\n");     
        }   
        System.out.println ("===================================================="+ "\n");   
        System.out.println ("Please enter C to continue or any other character to quit: q"+ "\n");
        System.out.print ("Thank you for using Travel program");                

    } //end of method

 } // end of class

Recommended Answers

All 21 Replies

Just have the user enter a number for the road type. Then your switch can simply be

switch  (roadType) {
  case 1:
    speed = 50;
    break;
  case 2:
      // ... etc
}

You will have to remove the "final" from your SPEED declaration.

Ok remove that final that makes sense since its going to change but I need it to be using only A and B, That wouldn't be possible with case 1 and case 2 as they are integers or have I got that wrong?

For A and B you could use char values, but not string values in the switch. If you use a String, you would have to use if() statements.

So would that look like this, have I changed the speed correctly?

switch  (roadType) {  

case 'A':
    System.out.println
   ("You have chosen Type A, your average speed was 50" + speed = 50;   
          break; 
case 'B':    
      System.out.println ("You have chosen Type A, your average speed was 50")+ speed = 70;   
         break;
}

No. Change the value of speed separately from your print output.

Oh yh of course, more like this then

Switch (roadType) {
Case 'A': System.out.println ("You have chosen Type A, your average speed was 50");
speed = 50;
break;

Case 'B': System.out.println ("You have chosen Type B, your average speed was 70");
speed = 70;
break;
}

How would I get the user input to work for that though, I mean they type A

Just like you got the other input, but you will need to use something like charAt(0) to get the first character of the String as a char value for your switch.

Im a little confused about how to use the charAt (0), can you give me an example?

I have been using UserInput.readString(); so would I have to define the varibles A and B or what I have done in bold work?
roadType =UserInput.readString(); ???

Switch (roadType) {
Case 'A': System.out.println ("You have chosen Type A, your average speed was 50");
speed = 50;
break;

Case 'B': System.out.println ("You have chosen Type B, your average speed was 70");
speed = 70;
break;
}


System.out.println ("Welcome to the Travel Calculator" + "\n");
System.out.println ("====================================================="+ "\n");
System.out.print ("Please enter the type of road, A or B: ");

// Getting a choice
System.out.print( " Enter Choice: " );
roadType = UserInput.readChar();

A and B are not variables themselves. They are two possible values for a variable that you want the user to set. So use a String variable for roadChoice that you read the input into. Then you can use roadChoice.charAt(0) to check the first character as a char value.

ok cool I get that making String roadChoice as a variable. I dont think i am wrting the code down write bc I am getting some errors, am I on the write track with this, I am still not quite getting to grips with it.

 public class TravelProg {
    public static void main(String[] args) {

    //local variables 
    String roadChoice;


    Switch (roadType); {

        Case 'A': System.out.println ("You have chosen Type A, your average speed was 50");
        speed = 50; 
        break; 

        Case 'B': System.out.println ("You have chosen Type B, your average speed was 70");
        speed = 70; 
        break; 
default:
      System.out.println("Default");
      break;
}


System.out.println ("Welcome to the Travel Calculator" + "\n");
System.out.println ("=================================================="+ "\n");
System.out.print ("Please enter the type of road, A or B: ");

// Getting a choice
System.out.print( " Enter Choice: " );
roadChoice = UserInput.readString();
roadChoice.charAt(0);

}

Move your switch down below the point you are getting the input. You want to set the speed based on what they input and you want to switch on the first char of that entry

switch(roadChoice.charAt(0)) {

If you don't want to deal with the whole char/switch thing, you can always just use if()-else statements with the string data.

I wish I could use if()-else statements, I get those but I have to learn how to use switch, hmmm I get a strange error ' case, default, or '}' expected'

public class TravelProg {
public static void main(String[] args) {

//local variables 
String roadChoice;

System.out.println ("Welcome to the Travel Calculator" + "\n");
System.out.println ("=================================================="+ "\n");
System.out.print ("Please enter the type of road, A or B: ");

// Getting a choice
System.out.print( " Enter Choice: " );
roadChoice = UserInput.readString();

switch(roadChoice.charAt(0)) {

Case 'A': System.out.println ("You have chosen Type A, your average speed was 50");
speed = 50; 
break; 

Case 'B': System.out.println ("You have chosen Type B, your average speed was 70");
speed = 70; 
break; 

default:
System.out.println("Default");
break;

        }
    }
}

"case" is not capitalized.

thank you very much, that is awesome. Sorry to annoy you with another question but I have to create a method for it to get a city name
I have done this in a sperate file.

public class getCityName{
    public void getCityName (String city1) {
        System.out.print ("Please enter the name of the first city: ");
        city1 = UserInput.readString();
    }
}

and that complies fine, in my original file I have done this

 import java.util.Scanner;
 public class TravelProg {
    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        printWelcome printWelcomeObject = new printWelcome ();
        printWelcomeObject.printWelcome();

        getCityName getCityNameObject = new getCityName ();
        String city1 = input.nextLine();
        getCityNameObject.getCityName(city1);

the printWelcome method works fine but getCityName doesn't quite work as well because it cpoplies fine but it doesnt print out the line ("Please enter the name of the first city: "); untill after I hit the enter key, i have written it out wrong?

Don't put it in a separate class. It doesn't really have any context as a separate object.

Just make a method getCityName() that returns the String that the user entered.

Oh ok that would make sense, I just spend last half hour learning how to do it in different classes but not in the same lol, ermmm this is embrasing how would I do that exactly. I understand that it is a a static method and goes before the Main but I don't know how I would recall it exactly, would it look like


import java.util.Scanner;

public static void getCityName()
System.out.print("Please enter the name of the first city: ");
city1 = UserInput.readString();

public class TravelProg {
public static void main(String[] args) {

Scanner input = new Scanner (System.in);

//then recalling it by doing this
TravelProg.getCityName ();
System.out.println();

am I on the right track? probably gone off the rails lol

It has to be inside the class. Just declare it after main(). It should return a String.

public static String getCityName() {

after you get a value from the user, return that value;

public class TestTwo {

  public static void printWelcome () {

    System.out.println ("Welcome to the Travel Calculator" + "\n");
    System.out.println ("====================================================="+ "\n");
    }

 public static String getCityName (String city1) { 
    System.out.print("Please enter the name of the first city: ");
    city1 = UserInput.readString();
    }

    public static double Speed = 50;
    public static void main(String[] args) {

        //local variables 
        String city1;
        String city2;
        String roadChoice;
        int hours;
        int mins;
        int distance;
        double timeInMins = 0;
        int timeInHours;
        int speed;

    TravelProg.printWelcome();
    System.out.println();

    TravelProg.getCityName();
    System.out.println();

I get an error saying cannot find symbol
symbol : method getCityName() and cannot find symbol
symbol : method printWelcome()

hmmm I must of done something wrong but I just can't see it

You don't need a class name to call static methods within the same class - and that class name doesn't match anyway.

Also, make sure your method call matches the signature you wrote. You can't call a method that requires a String parameter without supplying a parameter.

'city1' shouldn't really be a parameter to the method. That is the value you want to send back from the method

return city1;

Re-read your class material on using methods.

Thank you very much for your help on this, it was a class error, I got book on java finally and your guidence has really helped, thanks again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.