This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i have an assignment where i have to make a program that reads input and evaluates whether or not it is a palindrome until the user terminates. i am having issues with the while loop. it works like it should upon first input, but then when it re-enters the loop, it always says it is not a palindrome, even when it is.
Scanner in;
in = new Scanner (System.in);
String original = ""; //variable for user input
String original2 = ""; //variable to help make input case insensitive
String reverse = ""; //variable to compare word in reverse
int length; //variable used to
int i; //variable used in for loop
//String response = "";
System.out.println("Enter a word to check if it is a palindrome!");
original = in.nextLine();
while (!original.equals("n"))
{
length = original.length();
original2 = original; //assigning a new variable to hold the input, so as to not change it
original2 = original.toLowerCase(); //converting input to all lower case using the holder variable
for (i = length -1; i >= 0; i--) //for loop reversing the word to check for palindrome status
{
reverse = reverse + original2.charAt(i);
}
if (original2.equals(reverse)) //if statement determining output if palindrome is true or not
{
System.out.println(original + " is a palindrome");
}
else
{
System.out.println(original + " is not a palindrome");
}
System.out.println("Enter another word or enter 'n' to end"); //allowing to continue
original = in.nextLine();
}
System.out.println("thank you!");
in.close();
}
i initially thought that it was an issue with the buffer, but i no longer think that is an issue.
i will really appreciate any help at all
You don't reset reverse, so the reversed string is constantly being built on
Related
This question already has answers here:
when to use while loop rather than for loop
(14 answers)
Closed 1 year ago.
I am supposed to do a word-quiz game between two languages in Java, and I am not sure what type of loop should be used when controlling the input from the user! I have three "conditions/terms"
if the user types the right answer
if the user has some spelling mistake
if the user types q to quit the game
I was first thinking of using a for loop, but I don't seem to figure it out!
My code looks like this right now
public static int takeTest(ArrayList<Sweng> Wordlist) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < Wordlist.size(); i++) {
System.out.println(Wordlist.get(i).getSweWord());
String answer = keyboardInput.nextLine();
}
//...
}
If you don't know how many times the loop need to be executed, you can use a do-while loop.
This loop first execute the code inside the do brackets, and then check the condition.
This is an implementation example:
Scanner s = new Scanner(System.in);
String input; // a variable to store the input
do {
System.out.println(/*your question here*/);
input = s.nextLine();
// do something
} while(!input.equals("q")); // exit the loop if 'input' equals "q"
Otherwise, you can do something like that, but it's a very bad and rough way to do this. I don't recommend you to use it.
Note: You'll need to adjust this code with your ArrayList<Sweng> WordList. It's just an example!
ArrayList<String> questions = new ArrayList<String>();
ArrayList<ArrayList<String>> possibleAnswers = new ArrayList<ArrayList<String>>(); // list of a list because we need a set of strings for every questions
ArrayList<String> correctAnswers = new ArrayList<String>();
// init the lists
Scanner s = new Scanner(System.in);
int result = 0;
boolean quit = false; // if true, then quit the for loop
for(int i = 0; i < questions.size(); i++) { // repeat 'questions.size()' times
String answer = null;
do {
if(answer != null) System.out.println("This isn't a valid answer!"); // if 'answer' is null, don't show this output because it's the first time in the loop
System.out.println(questions.get(i));
answer = s.nextLine();
if(answer.equals("q")) { // if input is "q", set 'quit' to 'true' and break the do-while loop
quit = true;
break;
}
} while(!possibleAnswers.get(i).contains(answer)); // if the answer is a valid answer, quit the loop
if(quit) break; // if quit is true, break the for loop
if(answer.equals(correctAnswers.get(i))) { // check for correct answer
System.out.println("Correct!");
result++;
} else System.out.println("Wrong!");
}
System.out.println("You scored " + result + "!");
Since you actually know how often you want to loop at max (max. the amount of questions inside your wordList, since it's a quiz), you can actually keep the for loop.
You could use a while or do-while loop here, but then you would need a seperate index variable to keep track of the current question, and this fact alone indicates that a for loop is more suitable here.
I modified your code snippet to change / add the following things:
Variable names should start lowercase. So Wordlist -> wordList.
Added conditions regarding verification of the answer and quitting.
Added some print statements.
Example:
public static int takeTest(ArrayList<Sweng> wordList) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < wordList.size(); i++) {
System.out.println(wordList.get(i).getSweWord());
System.out.println("Please enter the answer:");
String answer = keyboardInput.nextLine();
if (wordList.get(i).getResultWord().equals(answer)) { // correct answer
System.out.println("Correct answer!");
result++;
} else if ("q".equals(answer)) { // quitting
System.out.println("Thank you for playing!");
break;
} else { // incorrect answer
System.out.println("Incorrect answer!");
}
}
return result;
}
Sidenote: Since I don't know the structure of your Sweng class, I called the method to retrieve the result word getResultWord().
My code for calculating average is correct but my program wont stop executing they way I want it to. I have to use scanner's functions in order to manipulate the string.
So I wanted to get better at Java and my tutor gave me a problem to solve. The program must accept student id, name of the subject and its marks, all in one string, and then calculate the average marks for this id. The format of the sting is "123456 math 5.5 physics 6.5 end" where the 6 digit number is the id and "end" is what makes the program stop waiting for numbers and calculate them.
ID is a 6 digit number from 0 to 9 which if it is 000000 the program must terminate.
"End" is stopping the entry but not the loop, but "000000" ends the loop.
In my code everything works fine but in order for the variables I use to reset I must type two times the word "end" and if I want to stop the loop I must type "000000" twice which is clearly not what I want. Can you point out my mistakes?
My teacher suggested to use Scanner's functions in order to get what I want. Is this problem something I cannot solve because of they way these functions work?
package averagemarks;
import java.util.*;
class AverageMarks {
public static void main(String args[]) {
String s = "123456 pr1 6.2 pr2 7.3"; //string input format
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\s+"); //space to split string tokens
sc.useLocale(Locale.US); //with that it can recognise float numbers
int count = 0;
double sum = 0.0;
String AM; //6 numbers from 0-9 consists the student id
System.out.println("Give string: ");
while(sc.hasNext()) {
String str = sc.next();
if (sc.hasNext("[0-9]{6}")) { //this is where i check for the id which if it is 000000 it must terminate the loop
AM=str;
System.out.println("AM: " + AM);
if (AM.equals("000000")) break;
} else if(sc.hasNext()== false) { //string must end with an end if user does not end it with it i must inform him
System.out.println("Data format error.");
//return;
} else if(sc.hasNextFloat()){ //this is where i gather data for the result
sum += sc.nextFloat();
count++;
} else if(sc.hasNext("end")){ //end means that you gonna calculate all the numbers till that point then reset for another student
System.out.println("Average is " + sum / count);
count = 0;
sum = 0.0;
}
}
}
}
"In my code everything works fine"
Well, it does not!
With the line String str = sc.next(); you read away required data.
You should put it in the end to read the course name away.
while(sc.hasNext()) {
// check student id
if (sc.hasNext("[0-9]{6}")) {
AM=sc.next(); // read student number
System.out.println("AM: " + AM);
if (AM.equals("000000")) break;
}
// check if line ends prematurely --> error
else if(sc.hasNext()== false) {
System.out.println("Data format error.");
//return;
}
// check for a float
else if(sc.hasNextFloat()){
sum += sc.nextFloat(); // read the float
count++;
}
// check for "end"
else if(sc.hasNext("end")){
String endStr = sc.next(); // read "end"
System.out.println("Average is " + sum / count);
count = 0;
sum = 0.0;
}
// all other not yet considered strings (e.g. a course)
else {
String course = sc.next(); // read course
}
}
Try this:
String AM = null; //6 numbers from 0-9 consists the student id
System.out.println("Give string: ");
String str = null;
while(sc.hasNext()) {
if (sc.hasNext("[0-9]{6}"))
{
str = sc.next("[0-9]{6}");
AM = str;
System.out.println("AM: " + AM);
if (AM.equals("000000")) break;
}
else if(sc.hasNext()== false) {
System.out.println("Data format error.");
//return;
}
while(sc.hasNextDouble()){
sum += sc.nextDouble();
count++;
}
if(sc.next().equals("end")){
System.out.println("Average is " + sum / count);
count = 0;
sum = 0.0;
}
}
I did not check if your sc.hasNext()==false works, but everything else seems to working properly. Only type end once to go to next option, "000000" to end entire program. I changed the next float to next double because you had sum declared as a double and put it into a loop so it finds all the next doubles. I moved all the next operations into the conditions as well. Remember that .next() moves to the next one. Your old code with sc.hasNext("end") did not move the cursor at all. Let me know if something is off or if you have a question!
My assignment is to write a program to scramble a word while maintaining the same first and last letter and only swapping two letters, then prompt the user to continue if they wish.
Example: userInput = bacon | Output = bcaon
I've attached an imagine of my program, there may be several issues, but as it stands I can't really run it due to the errors in the image. I'm really confused because I got a TA to help me on this assignment, and they seemed to think this would definitely work, but as you can see it does not.
I would really appreciate if someone could tell me what exactly is wrong and why. And if you have anything to add to make this program work, I'd really, really appreciate that too, but bottom line is I just want to understand what's wrong and why.
import java.util.Scanner;
import java.util.Random;
public class FreeStyle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // Importing and initializing keyboard to 'in'
System.out.println("Please enter a word to be scrambled"); // Asking user for a word
String word = in.next(); // Initializing the user's input
System.out.println(swapLetters(word));
System.out.println("Would you like to enter another word? y/n");
String answer = in.next();
boolean userDone = true; //Using a Boolean statement to ask the user if they are done enter words or not
while (userDone) {
if (answer.equals('y')) {
System.out.println("Please enter a new word"); //Ask user for new word to scramble
word = in.nextLine(); //New initialization for 'word'
} else if (answer.equals('n')) { //If user types 'n', loops then breaks because while(userDone) is false
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words."); // The logic doesn't flow or apply to words that are less than 4 letters, so this catches that error and notifies the user
}
}
}
private static String swapLetters(String word) { //Private method used for the program only, no need to involve the user
Random r = new Random(); //Using random instead of math floor
//int arraysize = word.length();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
//String word2 = word.substring(a, a+1);
String word2 = word.substring(0, a) + word.charAt(b)+word.substring(a+1, b)+word.charAt(a)+word.substring(b+1);
return word2;
}
Several points:
Why not use something already done exactly for what you are trying to do - Collections.shuffle? See comments in the code for understanding how it works.
You can't use equals() between a String and a char (' ' are for chars, " " are for Strings). Simple fix - just put your 'y' into "y", same for 'n'.
I've refactored the code at the beginning that we used to get user input and then scramble into a separate method, so we can reuse it again - getInputAndScramble.
And finally, I've used a do-while loop to keep looping until the user stops the loop with the "n" letter.
Please see my comments in the code, hopefully will clear things up.
public class Scrambler {
public static void main(String[] args) {
boolean userDone = true;
String word;
Scanner in = new Scanner(System.in);
getInputAndScramble(in); //Extracted method to get Scanner input and scramble
do {
System.out.println("Would you like to enter another word? y/n");
word = in.next();
while (userDone) {
if (word.equals("y")) {
getInputAndScramble(in);
break;
} else if (word.equals("n")) {
userDone = false;
} else {
System.out.println("Invalid input, please enter more than 3 letter words.");
}
}
} while (userDone); //continue until "n"
}
private static void getInputAndScramble(Scanner in) {
System.out.println("Please enter a word to be scrambled");
String word = in.next();
System.out.println(swapLetters(word));
}
private static String swapLetters(String word) {
/* Convert word into an ArrayList of characters.
Create ArrayList size of word,
convert String word into a char array and insert every char in
the char array into our ArrayList.
*/
ArrayList<Character> chars = new ArrayList<>(word.length());
for (char c : word.toCharArray()) {
chars.add(c);
}
//Shuffle, omitting first and last letters
Collections.shuffle(chars.subList(1, chars.size()-1));
//Add shuffled letters into an array to output as a word entity
char[] shuffled = new char[chars.size()];
for (int i = 0; i < shuffled.length; i++) {
shuffled[i] = chars.get(i);
}
//Return shuffled String
return new String(shuffled);
}
}
You are assuming that the two random number a and b have the property that a < b. What if a >= b? Then word.substring(a+1, b) will throw an error.
To fix it, just make sure that a < b is maintained (regenerating, swapping, etc.).
But to be sure, there are more than just this bug in your code. For example, using next(), comparing String with char, using wrong newline character, not striping newline character, and so on. You might want to add some print statements in your code you see what is actually happening.
Well, as for the swapping function, something like that should work:
private static String swapLetters(String word) {
char[] temp = word.toCharArray();
char swapHelper;
Random r = new Random();
int a = r.nextInt(word.length()-2)+1;
int b = r.nextInt(word.length()-2)+1;
swapHelper = temp[a];
temp[a] = temp[b];
temp[b] = swapHelper;
word = String.copyValueOf(temp);
return word;
}
Basically, im converting string to char array so i can operate on them with ease. A and B are variables that contain index of letters that should be swapped. After that, array is converted back to string and returned.
I'm having trouble activating my counter++. So far s2 is able to read s1, but cannot count amount of occurrences. Any help would be appreciated. (I realize that I am working in the wrong string, but it helps me to create the solution here first and then send it to a second string, is this poor logic?)
Sorry for the dumb question I am very new at programming
//i need a scanner that reads what i write that scanner should count
occurrences of a char another scanner declared scanner a would ask " write something" string s. = nextline etc new scanner asks for a letter string s1 = next line blb that input = something int count = StringUtils.countMatches(s1); System.out.print(amount ) i
//
public class Task07 {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("write something");
String text = s1.nextLine(); //reads user input value
Scanner s2 = new Scanner(System.in); // missing smth that limits length of s2
System.out.println("geb a letter");
String letter = s2.nextLine();
int counter = 0;
boolean found;
found = text.contains(letter);
if (found == true) {
counter++;
} else {
System.out.println(counter);
}
// could use counter from 6 here but need a way to tell counter
// that it should add +1 for every time something occurs in
// the other scanner
/*
Problems: text recognizer is boolean only
- doesnt activate counter
- doesnt activate counter based on X times occurence
- doesnt limit "letter" to only one char
-
*/
}
}
Basically a loop is the simple way to count character occurrences in a string. You would use something like
int counter = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == letter.charAt(0)) {
counter++;
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I want to give user a possibility to stop inputing new lines in my String array by entering the word "end". I checked out - it really inputs 'end' before the if statement, but for some reason this doesn't break the while cycle:
Scanner scan = new Scanner(System.in);
String[] str = new String[50];
int j=0;
int f = 0;
System.out.println("Input 'end' to see your previous input!");
while(f != -1)
{
the input goes well, but the if statement doesn't work completely
String choice = scan.nextLine();
if(choice == "end")
{
f = -1;
}
else
{
str[j] = choice;
j++;
}
}
Use
choice.equals("end") instead of ==
See here
Also see equalsIgnoreCase() method for string comparision