FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
basic-programs/java/PalindromeCheck.java at master · Scarlet-Coder/basic-programs · GitHub
Scarlet-Coder
/
basic-programs
Public
forked from
utkarsh-shekhar/basic-programs
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
basic-programs
/
java
/
PalindromeCheck.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
45 lines (39 loc) · 1.75 KB
Breadcrumbs
basic-programs
/
java
/
PalindromeCheck.java
Copy path
File metadata and controls
45 lines (39 loc) · 1.75 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import
java
.
util
.
Scanner
;
/**
* To check if a given string is a palindrome
*/
public
class
PalindromeCheck
{
public
static
void
main
(
String
[]
args
) {
// Accept input from the console
System
.
out
.
print
(
"Please enter a string: "
);
String
input
=
null
;
String
s
=
null
;
try
{
Scanner
sc
=
new
Scanner
(
System
.
in
);
input
=
sc
.
next
();
s
=
input
.
toLowerCase
();
// convert all characters to lower case so that palindrome check is case insensitive.
sc
.
close
();
}
catch
(
Exception
e
) {
outputAndEnd
(
"Unexpected error, please try to re-run the program."
);
// Error message for any unknown issues while reading the input
}
int
len
=
s
.
length
();
/*
Loop through all the characters and evaluate if given string is a palindrome
For even length strings - Say SaaS (or Java)
S(J) and a(a) from beginning are compared against S(a) and a(v) from the end
For odd length strings - Say madam (or fruit)
m(f) and a(r) from beginning are compared against m(t) and a(i) from the end, the middle character d(u) is ignored
*/
for
(
int
i
=
0
;
i
<
len
/
2
;
i
++) {
if
(
s
.
charAt
(
i
) !=
s
.
charAt
(
len
-
1
-
i
)) {
outputAndEnd
(
input
+
" is not a palindrome"
);
// Report failure when the first mismatch is found.
}
}
// If no mismatch is found and the loop is successfully complete, report the success.
outputAndEnd
(
input
+
" is a palindrome"
);
}
private
static
void
outputAndEnd
(
String
message
) {
System
.
out
.
println
(
message
);
// output the given message
System
.
exit
(
0
);
// exit the program
}
}
Back
|
FazBrowse Home
|
New Git URL