my java program using scan read does not stop execution - java

I am a newbee in the Java world. I wrote this program which reads in string array... When I run it, it never stops?!! what shall I add /change to make it end scanning?
import java.util.*;
public class Ex21 {
public static void main(String[] args) {
int i, n = 5;
String c;
ArrayList<String>words = new ArrayList<>();
System.out.println("Enter multi strings: ");
Scanner input = new Scanner(System.in);
boolean loop = true;
while(loop) {
words.add(input.next());
Collections.sort(words);
System.out.println("The sorted list is: " + words);
}
}
}

A while loop by definition continues executing its body until its condition (in this case the variable loop) evaluates to false. You never set loop to false in the body of the while-loop, hence the condition will never evaluate to false and the loop will never end.
Additionally, it seems like you want to sort a list of words entered by the user. I wouldn't advise calling Collections.sort on every iteration of the loop. Maybe look into using a data structure that keeps its elements sorted on its own, such as a TreeSet. Or, at least, only call the sort method once, directly after the loop.

while(condition) {
/* do something */
}
means /* do something */ happens unless condition == false, in your case it alwats true, that is why it doesn't stop. So Java behaves ok in your case.

while(loop) with loop always having the value true in your program is a so called endless loop, as the name says it never ends and this is what you are experiencing.
To make a loop stop you have to set the value of loop to false if some condition is fulfilled or terminate the loop using the key word break.
A condition may be for example having a certain word witch lets your loop terminate when it is entered, something like "exit"
Here is an example how you could set loop to false
String word = input.next();
boolean loop = ! "exit".equalsIgnoreCase(word);
while (loop) {
words.add(word);
Collections.sort(words);
System.out.println("The sorted list is: " + words);
word = input.next();
loop = ! "exit".equalsIgnoreCase(word);
}
System.out.println("Bye!");
Here is an other example how you could cancel the loop using break
while (true) {
String word = input.next();
if("exit".equalsIgnoreCase(word)) {
break;
}
words.add(word);
Collections.sort(words);
System.out.println("The sorted list is: " + words);
}
System.out.println("Bye!");
Note that the word exit is banned from the set that your arraylist can contain, You can change the program though to have it saved too.

Related

How to repeatedly enter a string until user enters keyword to stop loop in java

I am stuck in this program that is string method, my issue is that I cannot get the loop to stop and the program to print the output that is currently stored after the keyword has been entered. I am not trying to compare strings, I am trying to input multiple strings and add a word, in this case, "not" to the strings until the word "stop" is entered. Once "stop" has been entered. the system will output the entire string stored.
Here is the question for the program:
(StringConcat.java) This program asks the user to repeatedly enter a String. It ,should concatenate those Strings together, but insert spaces and the word “not” between every pair of words the user enters. Stop when the user enters the String “stop”. Display the final String. For instance, the program output might look like:
Please enter some Strings:
"Such"
"eyes"
"you"
"have"
"stop"
"Such not eyes not you not have"
Here is my code so far:
import java.util.*;
public class StringConcat{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String s = new String();
System.out.print("Please enter some Strings: ");
for(int x=0; x<s.length(); x++){
s = sc.nextLine();
s = s + "not ";
if(s == "stop"){
System.out.println(s);
break;
}
else{
continue;
}
}
}
}
Several issues with your code:
(1) Why do you use a for loop and iterate up to s.length() when the length of s (which is 0 at that point) has nothing to do with your problem?
You need a loop which has not predefined number of iterations like a while (true) from which you will exit with a break.
(2) In each iteration you get the user's input and store it in s, so you lose all previous values.
You need a separate variable to store the user's input.
(3) The continue statement is not needed as the last statement in a loop.
(4) Because at each iteration you append " not " at the end, after the loop has finished you must delete that last " not " from s
(5) Don't use == when you compare strings. There is the method equals() for this.
This is my solution:
Scanner sc = new Scanner(System.in);
String s = "";
System.out.print("Please enter some Strings: ");
while (true){
String input = sc.nextLine();
if(input.equalsIgnoreCase("stop"))
break;
s += input + " not ";
}
if (s.length() >= 5)
s = s.substring(0, s.length() - 5);
System.out.println(s);
Use while loop.
Why while loop?
Usually we have to use while loops always when we don't know the number of loops we will do. In this case only when the user inputs "stop".
So you need a String field to hold the user words. Also we can use a number field to track if is the first or the second word, thinkg in append the "not" word.
Then, take a look in this example:
Scanner s = new Scanner(System.in);
String currentAnswer = "";
String userWords = "";
int tracker = 0;
while (!currentAnswer.equals("stop")){
currentAnswer = s.nextLine();
userWords += currentAnswer + " ";
if (tracker % 2 != 0) {
userWords += "not ";
}
tracker++;
}
System.put.println(userWords);
This can be done using for loop too but I really recommend the while loop to this case.
EDIT:
As you saw, I used equals() instead == to compare two Strings because we are wiling to check for its value, not for its object equality.
When we use == operator we are trying to check if two objects target to the same memory adress, but we only want to know if two Strings have the same value.
For this case is valid to know that we can compare it using other ways, such as Objects.equals() or even contentEquals().
Check this discussion to learn more about comparing strings.

Struggling with compare last 2/3/4 characters Java (repl.it 018 - Conditional Statement Practice 4)

Dear Stackoverflow community I am Struggling with one task on repl.it (018) Conditional Statements 4
So they want me to do that :
Instructions from your teacher:
For you to do:
Given a string variable "word", do the following tests
If the word ends in "y", print "-ies"
If the word ends in "ey", print "-eys"
If the word ends in "ife", print "-ives"
If none of the above is true, print "-s"
No more than one should be printed.
and my code looks like this :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//DO NOT CHANGE ABOVE CODE! Write your code below
if(word.endsWith("y"){
System.out.println("-ies");
}
else if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else{
System.out.println("-s");
}
}
}
When I run it for example my input is :Hey
and of course my code will go through the code and see if the first statement is correct and yes it is equal because y = y at the end and that is WRONG!
My question is how can i let my code compare the last 2 or 3 characters so it will print out the right value when I input Hey.
If I input Hey it should print out :
-eys and not -ies
Ty
Since ending with "ey" is a subset of ending with "y", your 2nd if will never be true.
Change the order of your tests to the most specific first:
if(word.endsWith("ey"){
System.out.println("-eys");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
reorder the conditions as such:
if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else{
System.out.println("-s");
}
This means we hoist the condition that is most specific and put the less specific ones below.
I've put the else if(word.endsWith("y")) as the last of the else ifs but it really doesn't matter where within the else if chaining you put it as long as it's before the condition if(word.endsWith("ey")) things should be fine.

Do While Loop Error, Stuck in while loop

I have a boolean Guess function:
public boolean guess() {
String checkInput = scanner.nextLine();
try {
guess = Integer.parseInt(checkInput);
} catch (NumberFormatException e) {
return false;
}
return true;
}
which is called by another function in a do while loop:
while (!player.guess()) {
player.guess();
}
If I enter an int, the program runs properly and terminates. But if input is a non-int character, the program gets stuck in the while loop. I don't know what's going on here.
Your guess function is designed that way.
It returns false if the input is not numeric (catch). So it stays in the loop until you input a numeric value.
Another problem is that you are calling the function twice every loop (once on the loop condition check and another inside the loop). So if you type a non numeric character on the first (loop condition) and a numeric on the second (inside the loop) it will still ask for an input a third time.
I don't know what your intention is but you probably would want something like:
while (!player.guess()) {
continue;
}
Unless you really want it to be called twice.
Your scanner.nextLine() reads the line forever, it doesn't ask for another input.
while (!player.guess()) { // Entered Integer. (!true) and loop breaks
player.guess();
}
while (!player.guess()) { // Entered Non-Integer. (!false) and program enters the loop
player.guess(); // You are not storing the result in some boolean variable
//Therefore, it doesn't matter whether true or false
//while (!player.guess()) will be checked once again
}
SOLUTION:
boolean flag = player.guess(); // capture the result
while (!flag) { // verify the result
flag = player.guess(); // capture the result again
}

Two problems, using charAt for undefined input and looping output

So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.

for loop for inputting variables into array not working?

I'm trying to input 3 different variables into an array inside a while loop, as long as i don't enter stop for any of the variables. the while loop is only suppose to let me input a second variable value if the 1st variable isn't stop, and likewise with inputting a third variable value
Right now, the first loop goes fine and i can input all 3 variables, but the 2nd and 3rd time, the for loop outputs the first variable, but doesn't allow me to input a value before skipping to the 2nd variable.
ex of what i mean:
name:afasdf
extra info:afdsaf
unit cost:123123214
name: extra info: adflskjflk
also, entering Stop isn't ending the loop either
unit cost:123217
i know that this loop works when there's only one variable, and i've tried using a for loop instead of a while loop, and adding tons and tons of else statements, but it seems to stay the same
is there something wrong with the way i set up my breakers?
is the way i set up the last breaker(the one that stops even when i put stop for a double variable) messing up the rest of hte loop?
thank you so much
here is my code
ArrayItem s = new ArrayItem();
String Name = null, ID = null;
double Money = 0;
boolean breaker = false;
while(breaker ==false)
{
System.out.print("Name:" + "\t");
Name = Input.nextLine();
if(Name.equals("Stop")) //see if the program should stop
breaker = true;
System.out.print("Extra Info:" + "\t");
Details = Input.nextLine();
if(ID.equals("Stop"))
breaker = true;
System.out.print("Unit Cost:" + "\t");
Money = Input.nextDouble();
// suppose to let me stop even if i input stop
// when the variable is suppose to be a double
if(Input.equals("stop") || Input.equals("stop"))
breaker = true;
else
s.SetNames(Name);
s.SetInfo(Details);
s.SetCost(Money);
}
A couple of things about the code: "Name:" + "\t" can be simplified ot "Name:\t". This is true for the rest of the code. In Java, it's customary to use camelcase where the first word is lowercase. For example, s.SetMoney would be s.setMoney. Also, variables follow the same rules where Money would be money, and ID would be id. If your teacher is teaching you otherwise, then follow their style.
The loop should also be a do-while loop:
do
{
// read each value in sequence, and then check to see if you should stop
// you can/should simplify this into a function that returns the object
// that returns null if the value should stop (requiring a capital D
// double for the return type)
if ( /* reason to stop */)
{
break;
}
s.setNames(name);
s.setId(id);
s.setMoney(money);
} while (true);
private String getString(Scanner input)
{
String result = input.nextLine();
// look for STOP
if (result.equalsIgnoreCase("stop"))
{
result = null;
}
return result;
}
private Double getDouble(Scanner input)
{
Double result = null;
// read the line is a string looking for STOP
String line = getString(input);
// null if it's STOP
if (line != null)
{
try
{
result = Double.parseDouble(line);
}
catch (NumberFormatException e)
{
// not a valid number, but not STOP either!
}
}
return result;
}
There are a lot of concepts in there, but they should help as you progress. I'll let you put the pieces together.
Also, you did need to fix the brackets, but that's not the only issue. Because Money is a double, you must read the value as a String. I suspect that Input is a Scanner object, so you can check Input.hasNextDouble() if it's not, then you can conditionally check the String value to see if it's "stop" (note: you are checking for "Stop" and "stop", which are not equal). Your last, no-chances check compares the Scanner to "stop", which will never be true. Check
System.out.print("Unit Cost:\t");
if (Input.hasNextDouble())
{
Money = Input.nextDouble();
// you can now set your object
// ...
}
// it's not a double; look for "stop"
else if (Input.nextLine().equalsIgnoreCase("stop"))
{
// exit loop
break;
}
// NOTE: if it's NOT a double or stop, then you have NOT exited
// and you have not set money
breaker = true;
while(breaker){
Name = readInput("Name");
Details = readInput("Details");
Money = Double.parseDouble(readInput("Money"));
if(Name.equals("stop") || Details.equals("stop"))
breaker = false;
else {
// set ArrayItem
}
}
private static String readInput(String title){
System.out.println(title+":");
//... read input
// return value
}

Categories

Resources