My program method will not ouput anything - java

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.

Related

Parsing string generating my generated error message when nothing is entered

I am currently working on an assignment to parse strings and I am running into an issue.
It appears, that if nothing is entered, it is generating my error message I have created when a comma is not inputted.
According to the assignment in zybooks, it should not be outputting anything. Below is my code.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
//local variables
String lineString;
String firstWord;
String secondWord;
int commaLocation;
boolean inputDone;
//checks to end the program
inputDone = false;
//keeps the loop running until q is entered
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
//checks comma
commaLocation = lineString.indexOf(',');
if (commaLocation == -1) {
System.out.println("Error: No comma in string");
}
else {
firstWord = lineString.substring(0, commaLocation);
firstWord = firstWord.replace(" ", "");
secondWord = lineString.substring(commaLocation + 1, lineString.length());
secondWord = secondWord.replace(" ", "");
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
System.out.println();
System.out.println();
}
if (lineString.equals("q")) {
inputDone = true;
}
}
return;
}
}
It happens because when nothing is entered, comma cannot be found, therefore indexOf returns -1.
I would add something like
if (lineString.isEmpty()) {
continue;
}
right after lineString = scnr.nextLine();
EDIT:
I just noticed, that your error message will be printed in case, when your input equals 'q'. I assume this is not an expected behaviour, so I recommend to place
if (lineString.equals("q")) {
inputDone = true;
}
right after assignment of lineString or the if block I suggested above.

Java basic usage of string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am trying to code a program that allows to enter various words(step by step) until one types in "quit" .
I am having trouble stopping the loop (even with the word quit typed, it doesn't stop)
Using System.out.println(sum); I can check that the words are adding up, but it never stops..
((Summary : if(string == "quit") does not work and for (String end = "quit"; string!=end;) does not work ))
Sorry if its hard to read. its my second day coding :(
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
if (string == "quit")
{System.out.println("Ending system");
}
else{
for(String end = "quit"; string!=end; )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
String stringextra = scanner.nextLine();
if(stringextra == "quit"){break;}
string = stringextra;
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}}
Strings string and "quit" are not the same objects(as stored in the jvm) yet equal so checking with == will not work.
You need to use:
string.equals("quit")
see Object.equals() for more information
As pointed out in the other answer you need to use .equals() to compare strings. Also, your for loop is incorrect. A while loop is what is normally used in this case:
public class end_on_quit {
public static void main(String[] args)
{
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while ( ! string.equals("quit") )
{
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
}
Easiest way to doing something like your code using do while so your code running until user write quit. I will give you simple example :
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String stringextra = scanner.nextLine();
if (stringextra.equalsIgnoreCase("quit")) {
System.out.println("Bye bye");
System.exit(0);
} else {
do {
sum = sum + " " + stringextra;
System.out.println(sum);
System.out.println("Type in another word");
stringextra = scanner.nextLine();
} while (!stringextra.equalsIgnoreCase("quit"));
}
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
}
I hope this help you, good luck.
You should use equalsto compare strings. In this case for you example is better use while instead of for to loop.
When you use equalsIgnoreCase it means that is no matter if the word is upper case or lower case (is the same).
The application finishes when the user types "quit or ends or QUIT or ENDS"
Example:
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
String sum = "";
System.out.println("Type in a word");
String string = scanner.nextLine();
while (!string.equalsIgnoreCase("quit")) {
sum = sum + " " + string;
System.out.println(sum);
System.out.println("Type in another word");
string = scanner.nextLine();
if (string.equalsIgnoreCase("ends")) {
string = "quit";
}
}
System.out.println("Ending system");
scanner.close();
System.out.println("Stopping... due to the word quit");
System.out.println("all the words typed are " + sum);
System.exit(0);
}
Output:
Type in a word
hi
Type in another word
this
Type in another word
an
Type in another word
example
Type in another word
ENDS
Ending system
Stopping... due to the word quit
all the words typed are hi this an example
Process finished with exit code 0
Simply do System.exit(0) after System.out.println("Ending system");

How to restrict amount of characters a user can enter?

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");

How do I make my do while loop with user prompt work?

I'm creating an application that basically works as a guessing game. At the end of the game I want to ask the user if they want to play again. If they type "Y" or "y", the game will restart, if any other character is entered, then the loop ends.
public class NumberGame {
public static void main(String[] args) throws java.io.IOException {
int NumberGame;
int NumberUser;
char BonusResponse;
char charGen;
String Guess = " ";
String Bonus = " ";
do {
NumberGame = (int) (Math.random() * 10);
charGen = (char)(NumberGame + 48);
//for(NumberGame < 1; NumberGame++){
System.out.print("The computer generated number was " + NumberGame);
System.out.print("\nGuess a number between 1 and 9: ");
NumberUser = (char) System.in.read();
NumberUser = (int) (NumberUser - 48);
if (NumberGame > NumberUser)
Guess = " Too low! Try again";
else if (NumberGame == NumberUser)
Guess = " Congratulations, you win!";
else if (NumberGame < NumberUser)
Guess = " Too high! Try again";
System.out.println("You guessed " + NumberUser + "." + Guess);
if (NumberGame == NumberUser)
Bonus = "Now that you've won, wanna play again? Type Y to play again or any other key to exit:";
else
Bonus = " ";
System.out.println(Bonus);
BonusResponse = (char) System.in.read();
} while (BonusResponse == 'Y' || BonusResponse == 'y');
}
}
You could use the Scanner Class instead of plain System.in.read()
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
String response= sc.next();
You can use Scanner class as seen on this answer or BufferedReader as seen on this answer.
Example with BufferedReader class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Areas {
public static void main(String args[]){
float PI = 3.1416f;
int r=0;
String rad; //We're going to read all user's text into a String and we try to convert it later
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
System.out.println("Radius?");
try{
rad = br.readLine(); //We read from user's input
r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
}
catch(Exception e){
System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
Areas a = new Areas(); //We call this class again, so user can try it again
//You can also print exception in case you want to see it as follows:
// e.printStackTrace();
}
}
}
Example with Scanner class:
import java.util.Scanner;
public class Main{
public static void main(String args[]){
Scanner scan= new Scanner(System.in);
//For string
String text= scan.nextLine();
System.out.println(text);
//for int
int num= scan.nextInt();
System.out.println(num);
}
}
You can try adding the reading code inside a do-while loop to validate user input. Then add this code after your while (BonusResponse == 'Y' || BonusResponse == 'y');
if (BonusResponse == 'y' || BonusResponse == 'Y') {
startApplication();
}
move all your main() code to startApplication() method. And change main to:
public static void main(String args[]) {
startApplication();
}
Also please follow Java naming conventions:
Except for variables, all instance, class, and class constants are in
mixed case with a lowercase first letter. Internal words start with
capital letters. Variable names should not start with underscore _ or
dollar sign $ characters, even though both are allowed.

trying to find a different way to write this code

I have wrote this code and now i'm practicing and i'm trying it to write it in a different or more efficient way. Basically this code asks the user to enter a word and the second player guesses the letters of the word with 6 tries and at the end there is one last chance to guess the whole entire word. Any suggestions on how i can write this code in a simple way?
static int NUM_OF_TRIES = 6;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
boolean a = true;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(0) == word.charAt(j)) {
System.out.println(" at position " + (j + 1));
a = false;
break;
}
}
if (a) {
System.out.println("Sorry not letter " + guess.charAt(0));
continue;
}
}
System.out.println("Enter your last guess: ");
String wordComp;
wordComp = keyboard.next();
if (wordComp.equals(word)) {
System.out.println("You got it!");
} else {
System.out.println("Sorry you lost!");
}
}
}
Well, here is a shorter version:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1 please enter the word");
String word = keyboard.next();
for (int i = 0; i < NUM_OF_TRIES; i++) {
System.out.println("Enter your guess please");
String guess = keyboard.next();
int index = word.indexOf(guess.charAt(0));
if (index == -1)
System.out.println("Sorry not letter " + guess.charAt(0));
else
System.out.println(" at position " + (index + 1));
}
System.out.println("Enter your last guess: ");
String wordComp = keyboard.next();
if (wordComp.equals(word))
System.out.println("You got it!");
else
System.out.println("Sorry you lost!");
}
---First of all you'll have to ensure that
word.length <=guess.length
or you'll run into an exception.--- edit: that was obv not correct
Can't test right now bc I'm on my mobile, but as far as I can see, you'll run into problems if the word to guess has the same letter multiple times, since you're breaking out of the loop after finding the equal first letter.
As mentioned in comments, the comparison could be done by a method like
private static List<Integer> getLetterIndices(String word, char letter);
Then you won't need your boolean to indicate correct guesses, but a list of indices found
And of course you can do an object oriented approach instead of the static main method (not that it's faster to implement or better performance, just for practicing), perhaps something in the lines of this:
public class WordToGuess{
private Map<Character,List<Integer>> letter2indices;//...
public WordToGuess(String word){
parseIndices(word);
}
//parse indices of each letter to the map
private void parseIndices(String word);
public List<Integer> getLetterIndices(char letter);
}

Categories

Resources