Skip to content
Advertisement

Doing a beginner’s course on Java, having problems with do-while and if-else loops, as well as string validation

I’m doing a beginners course on Java, and there is no one currently I can ask for help.

The program is simple, you put in your details and the program will offer you a price quote for car insurance.

  1. The program is supposed to give quotes to those between the ages of 18 – 70. Out with that the program is supposed to print a message explaining they can’t have a quote.

This is what I’ve written

JavaScript

I can’t imagine why this won’t work. When I input an invalid age (eg. 12) the program returns the default quote of £400. When I remove the default case it returns the quote as being £12. So it seems to be ignoring the if else loop entirely.

(I know switch-case is an inefficient way to do this, but that was part of the task.)

  1. The program is supposed to ask for an input of the users title, in the form of “MR”, “MRS”, or “MS”. It is supposed to reject anything that doesn’t fit this and ask for another input. I have it working for the most part except the program always reads the first input as an error, whether it is or not. Then it performs as intended when you re-input the title.

eg. I input MR as title.

Program prints “Invalid Response. Use ‘MR’, ‘MRS’ or ‘MS’ Please enter your title”

I input MR again. The program advances to the next stage.

I created a method which validates the title which I have written here.

JavaScript

Can anyone spot what the issue is?

  1. Finally I have a problem rejecting an empty input for a string. The program will currently accept an empty input for the Forename and Surname. Whereas it should demand that the user enter something for these fields. I created two seperate methods, one to vailidate each name. I found a piece of code on this site I thought would help, but it doesn’t appear to do anything.

These are the methods

JavaScript

The piece of code I took is if(xx != null && !xx.isEmpty()). I thought I would have needed to remove the “!”s but doing so prevents the program from compiling. Any Ideas?

I’m so sorry for asking, but my tutor is unavailable today to explain where I’m going wrong.

Advertisement

Answer

1

JavaScript

Is wrong, because 12 is less than 70.

You need to say and (&&):

JavaScript

But also it is valid to be exactly 18 or 70 so:

JavaScript

2

Again you have && and || confused.

JavaScript

Reads: if title equals mr and title equals mrs and title equals ms.

title cannot be all of those.

3

JavaScript

You mean to say if surname is null or surname is empty:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement