java - Checking text length is divisible by 2 -
i want check whether length of input text divisible 2.
so
if text length 3, result 1.5 , display not divisible 2 , if text length 6, result 3.0 , display divisible 2
but codes display output "not divisible 2" regardless text length. have done wrong?
import java.util.scanner; public class test1 { public static void main (string[]args) { string =null; int l = 0; double result = 0.0; scanner scan = new scanner(system.in); system.out.println("enter string\n"); = scan.nextline(); l = a.length(); result = (double)l/2.0; system.out.println(result); if((double)result % 2 != .0) { system.out.println("not divisiable 2"); } else { system.out.println("divisiable 2"); } } }
first, length()
returns int
, , it's simpler work integers, why casting length double
? %
(modulo) operator meant work integers, not doubles; remember, double numbers floating-point numbers, there's room numerical error if utilize them.
second, don't need utilize many variables; maintain simple:
a = scan.nextline(); if(a.length() % 2 == 0) system.out.println("length of string divisible 2"); else system.out.println("length of string not divisible 2");
easier read (and write), don't think?
java
No comments:
Post a Comment