Hi this code is part of my code that is supposed to check if the number string is palindrome.
I want to iterate from top to botoom of my code but it doesn't iterate at all , what is wrong ??
I searched in youtube and realized this kind of things , people usually use do-while loop so I was trying to follow the instruction but it doesn't give me what I want .
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
Here is my full code.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ", '-');
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt, char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
Change this:
String str = kbd.nextLine().trim();
to this
String str = kbd.next();
When read choice, using nextLine() intead of next():
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.nextLine().charAt(0); // <---here, change to nextLine()
}while(choice=='y'||choice =='Y');
}
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. so in next loop it reads last input line that will be empty string.
Related
I'm having a problem with my code. I know that it has to do something with a Count constructor and its parameters. However, I can't wrap my mind around it.
What parameters should I add to the Count constructor to make the code work?
import java.util.Scanner;
public class CH9Assignment
{
public static void main (String [] args)
{
count();
//Create Scanner object
Scanner input = new Scanner (System.in) ;
System.out.println ("Enter a sentence:");
String s1 = input.nextLine();
System.out.println ("Enter 1 to count characters, 2 to count words");
int x = input.nextInt();
if (x == 1)
System.out.println ("There are " + s1.length() + "characters");
}
public static int count(String word)
{
if (word == null || word.isEmpty())
{
return 0;
}
int wordCount = 0;
boolean isWord = false;
int endOfLine = word.length() - 1;
char[] characters = word.toCharArray();
for (int i = 0; i < characters.length; i++)
{
if (Character.isLetter(characters[i]) && i != endOfLine)
{
isWord = true;
}
else if (!Character.isLetter(characters[i]) && isWord)
{
wordCount++; isWord = false;
}
else if (Character.isLetter(characters[i]) && i == endOfLine)
{
wordCount++;
}
if (x == 2)
System.out.println ("There are " + wordCount + "words");
}
}
}
You only have one method called count, it requires a String parameter, yet you try to call it without parameters.
import java.util.Scanner;
public class CH9Assignment
{
public static void main (String [] args)
{
// count(); --> DELETE THIS CALL, you don't have such a method
//Create Scanner object
Scanner input = new Scanner (System.in) ;
System.out.println ("Enter a sentence:");
String s1 = input.nextLine();
int result = count(s1); // ADD THIS LINE
System.out.println ("Enter 1 to count characters, 2 to count words");
int x = input.nextInt();
if (x == 1)
System.out.println ("There are " + s1.length() + "characters");
}
// Your count method
}
This will solve the compilation issues. You should be able to work out the logical issues.
You have to call the count method with something as a parameter. So just call it with s1 as parameter inside the if block. Your count method also seems too big and blown up. So I changed it, to just split the string by a simple regex. Try the following snippet:
public static void main (String [] args){
//Create Scanner object
Scanner input = new Scanner (System.in) ;
System.out.println ("Enter a sentence:");
String s1 = input.nextLine();
System.out.println ("Enter 1 to count characters, 2 to count words");
int x = input.nextInt();
switch(x){
case 1;
System.out.println ("There are " + s1.length() + " characters");
return;
case 2:
System.out.println ("There are " + count(s1) + " words");
return;
}
}
public static int count(String word){
if(word == null || word.isEmpty()){
return 0;
}
return word.split("(\\s|\\S)+").length;
}
I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code
I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)
I am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1
This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.
You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());
I need help getting this program to loop within its self after it runs the first time. It asks the user if they want to encode, decode or exit. The program runs, it encodes/decodes like it should. I now need to get another Pane to pop up and ask if they user wants to code another input then loop through everything it ran through the first time. I have the pane to where it asks the user if they want to run again but cant get it to loop through the coder.
public void encoding()
{
int userChoice;
int i;
int p=1;
int counter=0;
counter++;
String fin = "";
String input = JOptionPane.showInputDialog("Want to ENCODE, DECODE or EXIT? Press
1, 2, or 3");
userChoice = Integer.parseInt(input);
if (userChoice == 1 )
{
String encode = JOptionPane.showInputDialog(null, "What Are We
Encoding? ");
char[] array = encode.toCharArray();
for(i=0; i <array.length; i++)
{
char Ecode = encode.charAt(i);
Ecode--;
Ecode--;
fin += Character.toString(Ecode);
}
JOptionPane.showMessageDialog(null, fin);
}
else if (userChoice == 2)
{
String decode =JOptionPane.showInputDialog(null, "What Are We
Decoding? ");
char[] array1 = decode.toCharArray();
for(i=0; i < array1.length; i++)
{
char Dcode = decode.charAt(i);
Dcode++;
Dcode++;
fin += Character.toString(Dcode);
}
JOptionPane.showMessageDialog(null,fin);
String again = JOptionPane.showInputDialog("Want to code another?
Press 1 or 2");
int aChoice = Integer.parseInt(again);
if (aChoice==1)
{
System.out.print("bob");
}
else
{
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
}
Wrap you code starting int i; and include if-else block in a do-while loop as:
do{
int i;
int p=1;
.....
.....
}while(userChoice != 3);
Please Note: This will not let you exit, until you enter 3.
You may want to add another block to handle th conditions when user enters anything other that 1,2 or 3.
Alternatively, you can do like:
do{
String input = JOptionPane.showInputDialog...
.....
.....
}while(userChoice == 1 || userChoice == 2);
This will exit the loop for any choice other than 1 or 2.
EDIT: Please find below the fixed code:
public void encoding(){
int userChoice, i;
do{
String fin = "";
String input = JOptionPane
.showInputDialog("Want to ENCODE, DECODE or EXIT? Press 1, 2, or 3");
userChoice = Integer.parseInt(input);
if (userChoice == 1 ){
String encode = JOptionPane.showInputDialog(null, "What Are We Encoding?");
char[] array = encode.toCharArray();
for(i=0; i <array.length; i++){
char Ecode = encode.charAt(i);
Ecode--;
Ecode--;
fin += Character.toString(Ecode);
}
JOptionPane.showMessageDialog(null, fin);
} else if (userChoice == 2) {
String decode =JOptionPane.showInputDialog(null, "What Are We Dencoding?");
char[] array1 = decode.toCharArray();
for(i=0; i < array1.length; i++){
char Dcode = decode.charAt(i);
Dcode++;
Dcode++;
fin += Character.toString(Dcode);
}
JOptionPane.showMessageDialog(null, fin);
}
}while(userChoice != 3);
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
You could enclose the JOptionPane inputs + the full corresponding if block in a while loop:
int userChoice = 0;
while (userChoice != 3) {
int i;
int p=1;
// the rest of the params here
String input = JOptionPane.showInputDialog(...)
...
}