Issue
import java.util.Scanner;
public class Polygons {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double side = 0;
double perimeter = 0;
boolean valid = true;
var counter = 0;
for (int x=0;x<5;x++) {
System.out.println("Please enter the length of one side of the irregular polygon");
side = input.nextInt();
}
// TODO Auto-generated method stub
}
}
I need to add this following to my code now, but I don't know what to add from here, can someone please help me out?
If the value of side is greater than 0 Add that value to perimeter (Hint: perimeter=perimeter+side;) and Set the value of valid equal to true
Solution
Your code is asking the user to enter an int
, so the type of variable side
should be int
and not double
. Alternatively, call method nextDouble rather than nextInt
.
Since you are summing int
values, the type for variable perimeter
should also be int
.
There is no need for variable counter
since you are you using a for
loop and variable x
is essentially your counter.
Also no need for variable valid
since a simple if
statement will suffice for determining whether the entered number is greater than zero or not.
After each number is entered, you need to add that number to the current value of variable perimeter
– but only if the entered number is greater than zero. So before adding the number, you need to test whether the entered number is greater than zero. If it is not, you need to decrement the value of x
, because it is automatically incremented before every loop iteration, and ask the user to re-enter the value.
import java.util.Scanner;
public class Polygons {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int side = 0;
int perimeter = 0;
for (int x = 0; x < 5; x++) {
System.out.println("Please enter the length of one side of the irregular polygon");
side = input.nextInt(); // store the user-entered number in variable 'side'
if (side > 0) { // test whether the user-entered number is greater than zero
perimeter += side; // add the user-entered number to current value of variable 'perimeter'
}
else { // user-entered number is not greater than zero
System.out.println("Must be greater than zero. Please re-enter.");
x--; // decrement the loop counter
}
}
System.out.println("Perimeter = " + perimeter);
}
}
Edit
Due to OP comment.
import java.util.Scanner;
public class Polygons {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double side = 0;
double perimeter = 0;
boolean valid = true;
var counter = 0;
while (counter < 5) {
System.out.println("Please enter the length of one side of the irregular polygon");
side = input.nextDouble();
if (valid) {
perimeter += side;
valid = side > 0;
}
counter++;
}
if (valid) {
System.out.println("Perimeter = " + perimeter);
}
else {
System.out.println("Please try again and make sure that all sides have a value greater than 0");
}
}
}
Answered By - Abra
Answer Checked By - Terry (JavaFixing Volunteer)