I am new to Java and am creating a project for class that basically asks the user to input a string, and then tests the string and prints whether or not it is a palindrome (the same forwards as backwards... i.e. mom or dad or racecar)
I have gotten the code to work, however i have a loop setup to rerun the program or quit at the end. My problem is that when you rerun the program and enter another String input then it's adding it to the original string.
How can I reset or delete the String input each time so that it starts fresh?
Thank you for any help! Also please note, there may be better or faster ways to accomplish what I have done here but my knowledge of java is limited and I am just getting started, so I have used the knowledge that I have thus far learned. Thanks!!
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Ok, figured it out thanks to your guys' help... also rewrote the code so that you can just keep entering new strings or type q to quit instead of the redo question at the end. Hopefully this is cleaner!
import java.util.Scanner;
public class Palindrome_Test {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
int length; //length of word entered by user
boolean redo = true; // boolean to rerun program
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please enter a string, or type Q to quit: ");
input = scan.nextLine();
if (input.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
redo = false;
} else {
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
reverse = "";
}
} while (redo);
} //end main
} //end class
At the end of your while loop add reverse = "";
You'll notice that I moved the following -
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
Inside of the first loop. Although you could simply reset both variables at the end of the loop...
input = "";
reverse = "";
There is no need to (Although, they both work!). By dealing with the scope of the variable inside of the loop, it will essentially "refresh" each time the loop executes.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// String input = ""; // Word entered by user
// String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
I am having an issue whereby whenever input validation is incorrect it breaks out of my current loop and continues with the next method can anyone help me so that when condition is false it re-asks for the same input until it meets the condition. Here's my source code for my method class
public class Student {
public int gradePt;
public int i;
public int credSum = 0;
public double gradeCredSum = 0;
public double gpa;
String [] moduleName;
String [] moduleGrade;
int [] moduleCred ;
Module[] modules;
public void createModules(){
getModuleNo();
modules = new Module[i];
moduleName = new String[i];
moduleGrade = new String[i];
moduleCred = new int[i];
getModule();
getGrade();
getCred();
for (int j = 0; j < modules.length; j++) {
modules[j] = new Module(moduleName[j],moduleCred[j],moduleGrade[j]);
}
}
public void getModuleNo(){
do{
String input = JOptionPane.showInputDialog(null,
"How many modules did you take?","Input");
int a = Integer.parseInt(input);
if (a<1 || a>8){
JOptionPane.showMessageDialog(null,
"Invalid input please enter a number greater than 0",
"Error",JOptionPane.ERROR_MESSAGE);
break;
} i = a;
}while(i<1 || i>8);
}
public void getModule(){
for (int i=0;i<moduleName.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter the name of module #"+(i+1));
moduleName[i] = input;
if (input == ""){
JOptionPane.showMessageDialog(null,
"Invalid input, module name cannot be blank","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
public void getGrade(){
for (int i=0;i<moduleGrade.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter grade (A,B,C,D,F) for module #"+(i+1));
moduleGrade[i] = input;
if (!"A".equals(input) && !"B".equals(input) && !"C".equals(input) && !"D".equals(input) &&
!"F".equals(input) && !"a".equals(input) && !"b".equals(input) && input!="c" &&
!"d".equals(input) && !"f".equals(input)){
JOptionPane.showMessageDialog(null,
"Invalid input!"+"\n"+"Please enter A,B,C,D or F","Error",JOptionPane.ERROR_MESSAGE);
break;
}
moduleGrade[i] = input;
}
}
public void getCred(){
for (int i=0;i<moduleCred.length;i++){
String input = JOptionPane.showInputDialog(null,
"Enter credit units for module #"+(i+1));
moduleCred[i] = Integer.parseInt(input);
if (moduleCred[i]<1 || moduleCred[i]>8){
JOptionPane.showMessageDialog(null,
"Invalid input!"+"\n"+"Please enter a number form 1 to 8","Error",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
This is a common process. You keep asking for input, checking it each time until the input is valid.
Pseudocode:
repeat
display("Please enter your input: ")
input <- getInput()
until (isValid(input))
There are many loops in your program asking for input. so here is some code for your problem
boolean inputOk=false;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
do{
// ask for input
System.out.println("Enter the value");
// capture input
String input = reader.readLine();
// evaluate input
if(input.equals("ok"))
inputOk = true; // set flag if input is ok
}while(!inputOk); // if flag is ok then exit loop
I count four getter methods where you use a JOptionPane to gather user input. In the code snippet below, I have refactored getGrade() such that it continues to prompt the user for input, for a given module grade, until valid input is received.
While the fix for your three other methods is not given here, you can try following a similar pattern.
public void getGrade() {
String invalidInputMsg = "Invalid input!" + "\n" + "Please enter A,B,C,D or F";
for (int i=0; i < moduleGrade.length; i++) {
do {
String enterGradeMsg = "Enter grade (A,B,C,D,F) for module #" + (i+1)";
String input = JOptionPane.showInputDialog(null, enterGradeMsg);
if (input.length() == 1 &&
"ABCDF".indexOf(input.toUpperCase().charAt(0)) != -1) {
moduleGrade[i] = input;
break;
}
else {
JOptionPane.showMessageDialog(null, invalidInputMsg, "Error",
JOptionPane.ERROR_MESSAGE);
}
} while(true);
}
}
If the input be valid, then break will end the do loop, and the next value of i will be used in the for loop, should it be available. If the input be invalid, then the do loop will continue and prompt the user again for input.
i have written this code that is a hangman game
however the code keeps running when the user enters all the letters unless i write the word so it congrats the user.
i want it to stop when the user inputs all correct letters
import java.util.Scanner;
public class question6 {
public static void main(String[] args) {
String str = "testing";
boolean[] strBoolean = new boolean[str.length()];
Scanner input = new Scanner(System.in);
String test = "";
int counter = 1;
System.out.println("Java word guessing testing");
// main for loop for guessing the letters
while(true){
System.out.println("Key in one word character or your guessed word:");
test = input.nextLine();
if(test.equals(str)){
System.out.println("Congratulation!");
break;
}else{
// for loop for checking the boolean array
for(int b=0; b<strBoolean.length; b++){
if(str.charAt(b) == test.charAt(0)){
strBoolean[b] = true;
}
}
// for loop for printing the correct letters
System.out.print("Trail "+counter+": ");
for(int j=0; j<str.length(); j++){
if(strBoolean[j] == true){
System.out.print(str.charAt(j));
}else{
System.out.print("_");
}
}
System.out.println();
counter++;
}
}
}
}
First off, you are using attempting to compare your String test to the String str, but since you accept new user input for test before the you make that comparison, that conditional will only ever be true if the user types in "testing". So make sure you keep track of the ordering in your instructions in the program for future cases.
You are keeping track of the user's progress by using an array of boolean values. Thus, you could create a method that checks if all the values in said array are true, and return true if so. See example:
import java.util.Scanner;
public class question6 {
public static void main(String[] args) {
String str = "testing";
boolean[] strBoolean = new boolean[str.length()];
Scanner input = new Scanner(System.in);
String test = "";
int counter = 1;
System.out.println("Java word guessing testing");
// main for loop for guessing the letters
while(true){
if(allTrue(strBoolean)){
System.out.println("Congratulation!");
break;
}else{
System.out.println("Key in one word character or your guessed word:");
test = input.nextLine();
// for loop for checking the boolean array
//and the rest of your code
}
}
}
public static boolean allTrue (boolean[] values) {
for (int index = 0; index < values.length; index++) {
if (!values[index]){
return false;
}
}
return true;
}
}
Here's the program that I'm working on but I'm having problems with figuring out how to ask the user if they are done with it by saying a word or number.
import java.util.Scanner;
class paliindrome {
public static void main(String args[]) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
System.out.println(" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + isPalindrome.charAt(i);
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
char answer;
do {
aGame.play ();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
} while (answer == 'y' || answer == 'Y');
}
}
Put your entire application within the loop. One easy way would be to default answer to y (and you can use Character.toUpperCase(char) to eliminate the or) and something like
PalindromeChecker aGame = new PalindromeChecker();
char answer = 'y';
while (Character.toUpperCase(answer) == 'Y') {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// ... The rest of your code ...
aGame.play();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
}
There is one more way to solve your problem:
Put your entire code in a infinite while loop like this while(true), on the last line of loop just before exiting from the loop, u can ask user if he/she wants to continue. If answer is yes, then use the code System.exit(0) to exit from the program or if you want to just break from the loop use break; in the if condition.
You can use below code to ask user for quit.
boolean quit = false;
Scanner scanner = null;
try {
do {
System.out.println("Do you want to quit? (true/false)\n");
scanner = new Scanner(System.in);
String input = scanner.nextLine();
quit = Boolean.parseBoolean(input);
} while (!quit);
} finally {
scanner.close();
}
import java.util.Scanner;
public class paliindrome {
public static void main(String[] args) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
for (;;) {// or while(true)
System.out.println(
" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + isPalindrome.charAt(i);
}
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
System.out.print("\n Do you want to continue (y or n)?");
char answer = keyboard.next().charAt(0);
if (answer != 'y' && answer != 'Y') {
break;
}else{
aGame.play ();
}
}
}
}
Alrighty, I'm currently trying to make a program that takes input, in the form of a email address, from the user and checks to see if it has a '#' in it. I want to use a loop to steps through the whole string that the user entered, and checks each character for the '#'. I'm a little lost as to how to get started.
What I did, was use a for loop to iterate through the whole string that the user entered. Then I used a do/while loop to execute a certain line of code until the user entered a valid email. However, it seems to always be valid no matter if it has a '#' or not. I also want to check if it only contains 1 '#' in it. I'm a little lost as you can see, but any help would be appreciated!
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
System.out.print("Enter an email address ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
valid c = new valid(input);
}
}
class valid
{
String scan2;
char amper = '#';
int i;
valid(String scan1)
{
scan2 = scan1;
for (i = scan2.length() - 1 ; i <= 0; i--)
do
{
System.out.print("That input is invalid");
} while(scan2.indexOf(i) != amper);
System.out.println("That input is valid");
}
}
Since you have to use a loop, I would recommend charAt. It gives you the character at a given index in a string:
boolean found = false;
//where string is the input that you are scanning to find an email address
for (int i = 0; i < string.length; i++){
if (string.charAt(i) == '#'){
found = true;
break;
}
}
if (found){
System.out.println("Found the # character!");
}
Hope it helps you
Loop the each character in the loop.
Check for '#' character
String email = "test#gmal.com";
boolean valid = false;
for (int i=0;i<=email.length();i++) {
if (email.charAt(i)== '#') {
valid = true;
break;
}
}
if (valid) {
System.out.println("This is valid email Id");
} else {
System.out.println("This is an Invalid email Id");
}
Others have already made some helpful comments, but here a few other things I have noticed:
Did you mean to have no "{} after the for statement? Not having that { } can change the program.
In the for statement, did you want it to be i <= 0 or i >= 0? If i starts out being the length of the input string and the test in the for statement is i <= 0, it will never be true unless the input is zero length.
Why do you have a scan1 and a scan2 String?
You may want to consider removing your search logic from the constructor.
I recommend using charAt() method in this case. Here is my code.
import java.util.Scanner;
public class EmailAddr {
private String emailAddress;
public EmailAddr(String emailAddress){
this.emailAddress = emailAddress;
}
public boolean isValid(){
boolean isValid = false;
int nAtSign = 0;
for (int i = 0; i < emailAddress.length(); i++){
if(emailAddress.charAt(i) == '#')
nAtSign++;
}
if(nAtSign == 1)
isValid = true;
return isValid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your email address: ");
EmailAddr emailTest = new EmailAddr(sc.nextLine());
sc.close();
if(emailTest.isValid()){
System.out.println("The email address is VALID!");
} else {
System.out.println("The email address is INVALID!");
}
}
}
Javadoc concerning indexOf:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your E-Mail:");
String line;
do {
line = sc.nextLine();
}
while(line.indexOf('#') == -1);
Why dont you try with regular expressions ??
public class EmailValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean flag;
do{
String pattern="[a-zA-Z]*#[a-zA-Z.]*";
//if u need to think of much better email validation..
//String pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
System.out.println("Enter your Email here :");
flag=scanner.next().matches(pattern);
if(!flag){
System.out.println("Not a valid Email.");
}else{
System.out.println("Valid Email.");
}
}while(!flag);
}
You can use this code as class valid.
class valid {
String scan2;
char amper = '#';
boolean isFound = false;
valid(String scan1) {
scan2 = scan1;
for (int i = 0; i < scan2.length(); i++) {
if (scan2.charAt(i) == amper) {
isFound = true;
}
}
if(isFound) {
System.out.println("Seems like valid email.");
}
}
}
This code based on your class valid and continue some critical errors. As example : "What happen if user input contains more # characters.