ProductsLogo
LogoStudy Documents
LogoAI Grader
LogoAI Answer
LogoAI Code Checker
LogoPlagiarism Checker
LogoAI Paraphraser
LogoAI Quiz
LogoAI Detector
PricingBlogAbout Us
logo

Why FOR Loop was Chosen and Input Validation

Verified

Added on  2019/09/13

|2
|331
|203
Report
AI Summary
This assignment discusses the use of a FOR loop instead of a WHILE loop in the main part of the program. The reason for this choice is that the number of iterations is known beforehand, as it is decided by the value of the `HowFar` variable. This ensures that the loop will execute exactly `HowFar` times. In contrast, a WHILE loop would continue executing until a certain condition is met, which could lead to unexpected termination if not handled properly. The assignment also touches on the topic of validating user input to prevent the program from terminating abruptly. An example of an invalid input and a method (`validateInput`) are provided to demonstrate this.

Contribute Materials

Your contribution can guide someone’s learning journey. Share your documents today.
Document Page
Task 2
2.2 The main part of the program can use a FOR repetition structure.
a) Explain why a FOR repetition structure was chosen instead of a WHILE repetition
structure.
Even though a check has been performed to make sure that the variable HowFar is greater
than 1 there could be inputs that might cause the program to terminate unexpectedly
(crash).
Ans: For loop is used because we know the exactly how many times for loop have to execute.
This is decided by HowFar value. Until the HowFar variable value will remain the greater than
MyLoop variable value the loop will continue to execute. Whereas while loop is used where we
do not know exactly how many times loop will execute.
b) Provide an example of an input that might cause the program to terminate and describe
a method that could be used to prevent this.
Ans: If user input a string value instead of number then it will cause program to abruptly
terminate execution. This problem could resolve by the one method that is validateInput()
method. First of all we read user input in string format and pass it to validateInput() method.
Here is the code describes the all functioning to validate the user input.
1. String inputVar = null;
2. do{
a. System.out.println(“Enter number: “);
intputVar = sc.next();
b. If(validateInput( String inputVar)){
break;
}else{
System.out.println(“Invalid input”);
c. }
3. }while(true);
4. double HorFar = double.parseDouble(inputVar);
5. public Boolean validateInput(String inputVar){
6. try{ double no = double.parseDouble(inputVar);
if(no < 1){ retrun false; }
i.
return true;
}catch(NumberFormatException ex){

Secure Best Marks with AI Grader

Need help grading? Try our AI Grader for instant feedback on your assignments.
Document Page
return false;
}
7. }
1 out of 2
[object Object]

Your All-in-One AI-Powered Toolkit for Academic Success.

Available 24*7 on WhatsApp / Email

[object Object]