Results 1 to 1 of 1
Thread: Need help with while loops
- 10-04-2011, 05:37 AM #1
Member
- Join Date
- Oct 2011
- Posts
- 4
- Rep Power
- 0
Need help with while loops
I am supposed to write a program that asks the user to enter an English sentence, phrase or paragraph, and then test the input for various properties.
The program has to allow the user to enter a sentence (through a dialog), and will respond by telling the user the answer to the following questions:
Is the input a palindrome?
here is what i have so far:
import java.util.*;
public class Lab4
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
//variables
String input ;
String line;
int length, pos1, pos2;
char char1, char2;
// Prompt, get, and save sentence
System.out.println("Please enter a sentence:");
input = in.nextLine();
System.out.println("Your input was: " + input + ".");
// Is the input a palindrome?
pos1 = 0;
pos2 =input.length()-1;
while (pos2>0)
{
char1=input.charAt(pos1);
char2=input.charAt(pos2);
if(char1 == char2)
{
pos1++;
pos2--;
}
else if (char1 == ',' || char1 == '.' ||
char1 == '-' || char1 == ':' ||
char1 == ';' || char1 == ' ')
pos1++;
else if (char2 == ',' || char2 == '.' ||
char2 == '-' || char2 == ':' ||
char2 == ';' || char2 == ' ')
pos2--;
else
break;
}
System.out.println();
if (pos1< pos2)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
}
}
i dont understand what i'm doing wrong. i am comparing the last and first character and moving toward the center. i also attempted to make sure it skipped punctuation and spaces. can somebody please help me?Last edited by tangel; 10-04-2011 at 08:45 PM. Reason: Redid the program
Similar Threads
-
[Semi-Beginner] (nested loops) What's wrong with my code? (nested loops)
By Solarsonic in forum New To JavaReplies: 20Last Post: 03-22-2011, 05:02 AM -
Help with Loops
By Spyderpig in forum New To JavaReplies: 10Last Post: 02-17-2011, 09:10 AM -
loops
By curioustoknow in forum New To JavaReplies: 3Last Post: 02-06-2011, 02:45 PM -
Help with loops
By pg5678pg in forum New To JavaReplies: 8Last Post: 10-17-2010, 07:51 PM -
need some help with loops!
By Chewart in forum New To JavaReplies: 2Last Post: 12-04-2009, 12:32 AM
Bookmarks