For my program below, I want it so that the user must enter a word 2 or more characters long, but I do not know how to make that restriction.
This is a palindrome program, and it is used to test whether the word is a palindrome or not. It lets me enter a word of any length but I want to restrict to 2 or more, and if they enter only a one character word, a message should display "Wrong word".
import java.util.*;
class PalindromeTesterSamJiang1 {
public static void main(String [] arg) {
int x=0;
Scanner in=new Scanner(System.in);
System.out.printf("Menu: Please select an option \n"
+ "1)Palindrome Tester\n"
+ "0)Exit program \n");
x=in.nextInt();
switch (x){
case 1:
lol test=new lol();
test.palindromeTester("");
test.displayInfo();
break;
default:
System.out.println("Goodbye");
break;
}
}
}
class lol {
String original, reverse = "";
public String palindromeTester(String reference) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word to Test: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
return original;
}
public void displayInfo() {
if (original.equals(reverse))
System.out.println("RESULT: A PALINDROME");
else
System.out.println("RESULT: NOT A PALINDROME");
String[] arguments = new String[] {"123"};
PalindromeTesterSamJiang1.main(arguments);
}
}
You can read the input in a loop,
print an error if the input is too short,
break out when you get a valid input, for example:
while (true) {
System.out.println("Enter a word to Test: ");
original = in.nextLine();
if (original.length() > 2) {
break;
}
System.out.println("Too short. Word must be at least 2 characters");
}
System.out.println("Enter a word to Test: ");
original = in.nextLine();
String[] array = original.split(" ");
if(array.length < 2)
System.out.print("Enter atleast 2 sentence");
Related
I am new to Java and have a task: Scanner a number of "strangers' " names, then read these names and print "Hello+name" to the console. If number of strangers is zero, then print "Looks empty", if the number is negative, then print "Looks negative to me".
So the input and output to console should look like this:
3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel
So I have this code edited from someone with some related task, but it seems I miss something as I am new to Java...
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
while (num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
} while (num<0) {
System.out.println("Seriously? Why so negative?");
break;
}
String[] numbers = new String[num];
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +input.nextLine());
}
With using do while loop you can ask the number to the user again and again if it is negative number.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int num;
String name;
Scanner scan = new Scanner(System.in);
//The loop asks a number till the number is nonnegative
do{
System.out.print("Please enter the number of strangers: ");
num = scan.nextInt();
if(num<0) {
System.out.println("It cannot be a negative number try again.");
}else if(num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
}else{
String[] strangers = new String[num];
//Takes the names and puts them to the strangers array
for(int i=0;i<num;i++) {
System.out.print("Name " + (i+1) + " : ");
name = scan.next();
strangers[i] = name;
}
//Printing the array
for(int j=0; j<num; j++) {
System.out.println("Hello, " + strangers[j]);
}
break;
}
}while(num<0);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
if(num==0) {
System.out.println("Oh, it looks like there is no one here");
}
else if(num<0) {
System.out.println("Seriously? Why so negative?");
}
else {
String numbers[] = new String[num];
input.nextLine();
for (int i=0; i< num;i++) {
numbers[i]=input.nextLine();
}
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +numbers[i]);
}
}
}
}
This is how your code will look and you'll need to add member function input.nextLine(); to read newline character, so there can't be problem regarding input
New to java. I need to ask the user the number of strings (consisting only of upper and lowercase letters, spaces, and numbers) they want to input. These strings need to be stored in an array. Then I created a boolean method to be able to tell if those strings are palindromic (ignoring spaces and cases). If it is palindromic then I add to the result list to print later on. I am confused on how to ask the user to input that exact amount of strings and how to check each individual string. I must use StringBuilder. This is what I have so far (it's kind of a mess, sorry). I feel like I'm using the StringBuilder/array wrong, how can I fix this?
public class Palindromes {
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder(numOfStrings);
for(int n=0; n < paliString; n++){
paliString[n] = scan.nextLine();
scan.nextLine();
String[] stringPali = new String[numOfStrings];
StringBuilder str = paliString;
if(isPali(userString)){
paliString = append.userString;
}
System.out.println("The palindromes are: " + userString ";");
}
static boolean isPali(String userString) {
int l = 0;
int h = userString.length() - 1;
// Lowercase string
userString = userString.toLowerCase();
// Compares character until they are equal
while (l <= h) {
char getAtl = userString.charAt(l);
char getAth = userString.charAt(h);
// If there is another symbol in left
// of sentence
if (!(getAtl >= 'a' && getAtl <= 'z'))
l++;
// If there is another symbol in right
// of sentence
else if (!(getAth >= 'a' && getAth <= 'z'))
h--;
// If characters are equal
else if (getAtl == getAth) {
l++;
h--;
}
// If characters are not equal then
// sentence is not palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
}
SAMPLE RESULT:
Enter the number of strings: 8
Enter the strings:
Race Car
Mountain Dew
BATMAN
Taco Cat
Stressed Desserts
Is Mayonnaise an instrument
swap paws
A Toyotas a Toyota
The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota
As I think the best way to answer this is to help you learn in small steps, I tried to stick with your initial idea on how to solve this and edited your main method with minimal changes.
This one does the trick.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
StringBuilder paliString = new StringBuilder();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
if (paliString.length() > 0) {
paliString.append("; ");
}
paliString.append(userString);
}
}
System.out.println("The palindromes are: " + paliString);
}
Key changes:
I added scan.nextLine(); right after reading the number of strings. This handles the newline you get when the user hits enter.
You don't need to initialize the StringBuilder with numOfStrings. This just preallocates the size of the StringBuilder in characters. Not the number of strings. Either way, it's not necessary. StringBuilder grows as needed.
I suggest you inspect what I did inside the for-loop. This was the biggest mess and changed significantly.
Last but not least: Writing the result needs to be outside of the for-loop, after all palindromes have been added to the StringBuilder.
Edit
Based on your comment, in this next iteration, I changed the usage of StringBuilder to the usage of an ArrayList. (Which is something completely different)
I am using it here because Lists in Java grow on demand. And since the number of palindromes is probably not equal to the number of input strings, this is the way to go. To really assign it to an array, one could always call String[] paliStringsArray = paliStrings.toArray(new String[]{}); but as ArrayLists already use an underlying array and are not necessary to to generate the output you want, I didn't put it into the new version.
Please compare the differences of this step to the previous version. I also added this String.join("; ", paliStrings) part, which creates the output you want.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = scan.nextLine();
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
And now to the last step. Arvind Kumar Avinash actually solved a part that I also missed in the initial question. (I'll read more carefully in the future). He was validating the user input. So for the last iteration, I added his validation code in a modified way. I put it into a method as I think that makes things clearer and gets rid of the necessity of a the boolean valid variable.
public static void main(String[] args) {
int numOfStrings;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the number of strings: ");
numOfStrings = scan.nextInt();
scan.nextLine(); // you need this to catch the enter after the integer you entered
System.out.print("Enter the strings: ");
List<String> paliStrings = new ArrayList<>();
for (int n = 0; n < numOfStrings; n++) {
String userString = readNextLine(scan);
if (isPali(userString)) {
paliStrings.add(userString);
}
}
System.out.println("The palindromes are: " + String.join("; ", paliStrings));
}
static String readNextLine(Scanner scanner) {
while (true) {
String userString = scanner.nextLine();
if (userString.matches("[A-Za-z0-9 ]+")) {
return userString;
} else {
System.out.println("Error: invalid input.");
}
}
}
I need to ask the user the number of strings (consisting only of upper
and lowercase letters, spaces, and numbers) they want to input. These
strings need to be stored in an array.
I have done the above part of your question. I hope, this will give you direction to move forward.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
System.out.print("Enter a string consisting of only letters and digits: ");
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !#£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello #
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123
Feel free to comment in case of any doubt/issue.
Wish you all the best!
[Update]
Based on your request, I have posted the following update which asks for the strings only once and then allows the user to enter all the strings one-by-one:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
boolean valid = true;
int numOfStrings = 0;
do {
valid = true;
System.out.print("Enter the number of strings: ");
try {
numOfStrings = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
String[] stringPali = new String[numOfStrings];
String input;
System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
for (int i = 0; i < numOfStrings; i++) {
do {
valid = true;
input = scan.nextLine();
if (!input.matches("[A-Za-z0-9 ]+")) {
System.out.println("Error: invalid input.");
valid = false;
}
} while (!valid);
stringPali[i] = input;
}
}
}
A sample run:
Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits:
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash
Feel free to comment in case of any doubt.
first off, the secret word is printed out as dashes, then the user puts in what letter they want to guess. if they guess the letter correctly then it will update the dashes. so if the word is java, it will show as ---- and if the user types a, then it will update and show -a-a . my program does that but it also adds extra dashes at the end and i don't know how to make it not print those extra dashes. and that brings me to another problem i am having, the user is asked at what indexes they want to guess the letter. so if the user types the letter a and at index 1, then the updated word will show -a--, but my program updates all instances of where the a is at, so it shows -a-a. here is my code:
import java.util.Scanner;
public class HangMan2 {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int guessRemaining = 20;
int rounds = 1;
int roundScore;
String wordString = "";
String word = RandomWord.newWord();
int length = word.length();
for(int i = 0; i < length; i++)
{
wordString += "-";
}
System.out.println("The word is: " +wordString);
System.out.println("The secret word is: " +word);
System.out.println("Enter the number of spaces allowed");
int spacesAllowed = keyboard.nextInt();
keyboard.nextLine();
if(spacesAllowed > length)
{
System.out.println("Invalid input. Try again.");
System.out.println("Enter the number of spaces allowed");
spacesAllowed = keyboard.nextInt();
}
while(guessRemaining > 0) {
System.out.println("Please enter the letter you want to guess: ");
String letterGuess = keyboard.next();
char letterCharacter = letterGuess.charAt(0);
System.out.println("Please enter the number of spaces you want to check (seperated by spaces): ");
String spacesChecked = keyboard.next();
boolean guessCheck;
// check if the letter is in the string
guessCheck = (word.indexOf(letterCharacter)) != -1;
if(guessCheck == true)
{
for (int i = 0; i < word.length(); i++) {
if (letterCharacter == word.charAt(i)) {
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
System.out.println("Your guess is in the word!");
System.out.println("The updated word is: " +wordString);
} //end of if statement
} //end of for loop
}
else
{
System.out.println("Your letter was not found in the spaces you provided");
guessRemaining--;
System.out.println("You have " +guessRemaining+ " guesses remaining.");
}
}
if(guessRemaining != 0)
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
roundScore = (guessRemaining * 10) / spacesAllowed;
} //end of if
else{
System.out.println("Guesses Remaining: 0");
System.out.println("You have failed to guess the word... :(");
}
System.out.println("Would you like to play again? Yes (y) or No (n)");
String playAgain = keyboard.next();
if(!playAgain.equals("y") && !playAgain.equals("n"))
{
System.out.println("Invalid response, please try again... ");
}
if(playAgain.equals("y"))
{
rounds++;
}
else
{
System.exit(0);
}
}
}
wordString = wordString.substring(0, i) + letterGuess + wordString.substring(i);
if ((wordString.substring(0,i) + wordString.substring(i)).equals(wordString))
System.out.println("These are completely identical");
else
System.out.println("You solved it yourself ;)");
hint: it's 58 in your posted code.
Second part: Completely different program structure.
You'll need to track user's two guessed values, one as a character, the other as an int.
You will compare wordString.toCharArray()[indexUserGuessed] to characterUserGuessed and update the result or game state as needed, using similar code from the way you solved the if statement paradox I provided.
Finally, Welcome to Stack Exchange. MOST of us won't do your homework for you.
Oh and I would look up examples of "StringBuilder Java" as you might find it easier to manipulate your String with this class than with String.
I am writing a program for homework where I am to modify a string using a menu. The rest of the code works fine except for one part that has me in a bind. I am using a method in order to find a word and all its occurrences in the String. Whenever I execute this method outside of a loop, I get the result I need, but whenever I use it inside of a while or switch statement, the program does not give me anything back. The method needs to return an int for the number of occurrences. This is the excerpt of that code:
import java.util.Scanner;
public class test {
public static Scanner scnr = new Scanner(System.in);
public static int findWord(String text, String userText) {
int occurance = 0;
int index = 0;
while (index != -1) {
index = userText.indexOf(text, index);
if (index != -1) {
occurance++;
index = index + text.length();
}
}
return occurance;
}
public static void main(String[] args) {
System.out.println("Enter a text: ");
String userText = scnr.nextLine();
System.out.println("Enter a menu option");
char menuOption = scnr.next().charAt(0);
switch (menuOption) {
case 'f':
System.out.println("Enter a phrase from text: ");
String text = scnr.nextLine();
int occurance = (findWord(text, userText));
System.out.println("" + text + " occurances : " + occurance + "");
break;
default:
System.out.println("Goodbye");
}
return;
}
}
Now a couple things I have noticed. If I prompt the user while inside the method, i do get back my integer, but not the text that i was looking for in order to complete my println inside the switch statement. And whenever i prompt the user for the word inside the switch statement, i get nothing back. If anyone has any solutions for me, i would greatly appreciate it, since i haven't a clue what i could be overlooking or missing.
You need to change char menuOption = scnr.next().charAt(0); to char menuOption = scnr.nextLine().charAt(0);.
The problem is with your Scanner method, which you are reading the continuously with scnr.next(), but should be changed to scnr.nextLine()` as shown below:
public static void main(String[] args) {
Scanner scnr = null;
try {
scnr = new Scanner(System.in);
System.out.println("Enter a text: ");
String userText = scnr.nextLine();
System.out.println("Enter a menu option");
char menuOption = scnr.nextLine().charAt(0);
switch (menuOption) {
case 'f':
System.out.println("Enter a phrase from text: ");
String text = scnr.nextLine();
int occurance = (findWord(text, userText));
System.out.println("" + text + " occurances : " + occurance + "");
break;
default:
System.out.println("Goodbye");
}
return;
} finally {
if(scnr != null)
scnr.close();
}
}
Also, ensure that you are closing the scanner object properly in thefinally block.
so my problem is that I need to get the user to enter a string. then they will enter a character that they want counted. So the program is supposed to count how many times the character they entered will appear in the string, this is my issue. If someone can give me some information as to how to do this, it'll be greatly appreciated.
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they wan counted in the string
String character= keyboard.nextLine();
}
}
Here is a solution taken from this previously asked question and edited to better fit your situation.
Either have the user enter a char, or take the first character from
the string they entered using character.chatAt(0).
Use word.length to figure out how long the string is
Create a for loop and use word.charAt() to count how many times your character appears.
System.out.println("please enter a word");//get the word from the user
String word= keyboard.nextLine();
System.out.println("Enter a character");//Ask the user to enter the character they want counted in the string
String character = keyboard.nextLine();
char myChar = character.charAt(0);
int charCount = 0;
for (int i = 1; i < word.length();i++)
{
if (word.charAt(i) == myChar)
{
charCount++;
}
}
System.out.printf("It appears %d times",charCount);
This should do it. What it does is that it gets a string to look at, gets a character to look at, iterates through the string looking for matches, counts the number of matches, and then returns the information. There are more elegant ways to do this (for example, using a regex matcher would also work).
#SuppressWarnings("resource") Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string:\t");
String word = scanner.nextLine();
System.out.print("Enter a character:\t");
String character = scanner.nextLine();
char charVar = 0;
if (character.length() > 1) {
System.err.println("Please input only one character.");
} else {
charVar = character.charAt(0);
}
int count = 0;
for (char x : word.toCharArray()) {
if (x == charVar) {
count++;
}
}
System.out.println("Character " + charVar + " appears " + count + (count == 1 ? " time" : " times"));