0

I have done thorough research on this topic but cannot seem to find anything on exactly what I'm after. I am creating a toll invoice (for a school assignment) which requires users to input data via the scanner to be saved under the relevant string and int variables to be called upon at a later time. The issue I'm facing is whilst creating if statements. I have an if statement for the type of vehicle being entered into the system, if it is a Heavy Vehicle (HCV) the user will be prompted to enter the relevant trip time which is then saved into the String "uTripTime."

However from here the String "uTripTime" cannot be recalled later in my code.

The only thing I can assume is that because an if statement is a separate code block the user input being stored in the String 'uTripTime' is only stored within that code block. Is there any way to use this variable later in my code?

Sorry if the format of my question isn't correct, my first time asking a question here.

1
  • So if i understood your problem you are unable to use uTripTime variable further right ? Why don't you make uTripTime a global variable ? Commented Sep 20, 2017 at 6:48

2 Answers 2

2

MAke the variable uTripTime global to access it in outer block, its current scope is local to the if block.

String uTripTime = ""; // initializing empty
if (uVehicleType.equals("HCV")) {
   System.out.print("Enter Trip Time (Peak, Off-Peak or Night): ");  
   uTripTime = uInput.nextLine();
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to declare uTripTime outside of the if block:

String uTripTime = "";
if (uVehicleType.equals("HCV")) {
    System.out.print("Enter Trip Time (Peak, Off-Peak or Night): ");  
    uTripTime = uInput.nextLine();
}
// now you can access uTripTime here

Note that prefixes (like "u" in uTripTime) is not Java coding style.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.