do-while loop not working as it should - java

Ok so basically I am having trouble finding out why this is not working as I think it should, and need help getting to the right output. I have tried messing with this format a few ways, but nothing works, and I really don't understand why. Here are the instructions, followed by my source for it:
INSTRUCTIONS
Write a loop that reads strings from standard input where the string is either "land", "air", or "water". The loop terminates when "xxxxx" (five x characters) is read in. Other strings are ignored. After the loop, your code should print out 3 lines: the first consisting of the string "land:" followed by the number of "land" strings read in, the second consisting of the string "air:" followed by the number of "air" strings read in, and the third consisting of the string "water:" followed by the number of "water" strings read in. Each of these should be printed on a separate line.
ASSUME the availability of a variable, stdin , that references a Scanner object associated with standard input.
SOURCE:
int land = 0;
int air = 0;
int water = 0;
do
{
String stdInput = stdin.next();
if (stdInput.equalsIgnoreCase("land"))
{
land++;
}else if (stdInput.equalsIgnoreCase("air"))
{
air++;
}else if (stdInput.equalsIgnoreCase("water"))
{
water++;
}
}while (stdin.equalsIgnoreCase("xxxxx") == false); // I think the issue is here, I just dont't know why it doesn't work this way
System.out.println("land: " + land);
System.out.println("air: " + air);
System.out.println("water: " + water);

You are storing user info in stdInput but your while checks stdin. Try this way
String stdInput = null;
do {
stdInput = stdin.next();
//your ifs....
} while (!stdInput.equalsIgnoreCase("xxxxx"));

This Works:)
I just submitted this code to codelab and it works just fine.
Write a loop that reads strings from standard input where the string is either "land", "air", or "water". The loop terminates when "xxxxx" (five x characters ) is read in. Other strings are ignored. After the loop, your code should print out 3 lines: the first consisting of the string "land:" followed by the number of "land" strings read in, the second consisting of the string "air:" followed by the number of "air" strings read in, and the third consisting of the string "water:" followed by the number of "water" strings read in. Each of these should be printed on a separate line.
int land = 0;
int air = 0;
int water = 0;
String word = "";
while(!(word.equals("xxxxx"))) {
word = stdin.next();
if(word.equals("land")) {
land++;
}else if(word.equals("air")) {
air++;
}else if(word.equals("water")) {
water++;
}
}
System.out.println("land:" + land);
System.out.println("air:" + air);
System.out.println("water:" + water);

I think you want stdInput.equalsIgnoreCase("xxxxx") == false instead of stdin.equalsIgnoreCase("xxxxx") == false.

You are right - the problem is where you indicated. The solution is to not read again from stdin:
Also, you must declare the stdInput before the loop so its scope reaches the while condition:
String stdInput = null;
do {
stdInput = stdin.next();
// rest of code the same
} while (!stdInput.equalsIgnoreCase("xxxxx"));
An alternate way would be a for loop:
for (String stdInput = stdin.next(); !stdInput.equalsIgnoreCase("xxxxx"); stdInput = stdin.next()) {
// rest of code the same
}

Related

Input multiple lines using hasNextLine() is not working in the way that I expected it to

I'm trying to input multiple lines in java by using hasNextline() in the while loop.
Scanner sc = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
System.out.println(lines)
}
The code is inside the main method. But the print method in thewhile loop doesn't print the last line of my input. Also, while loop doesn't seem to break.
What should I do to print whole lines of input and finally break the while loop and end the program?
Since an answer that explains why hasNextLine() might be giving "unexpected" result has been linked / given in a comment, instead of repeating the answer, I'm giving you two examples that might give you "expected" result. Whether any of them suits your needs really depends on what kind of input you need the program to deal with.
Assuming you want the loop to be broken by an empty line:
while (true) {
String curLine = sc.nextLine();
if (curLine.isEmpty())
break;
lines.add(curLine);
System.out.println(curLine);
}
Assuming you want the loop to be broken by two consecutive empty lines:
while (true) {
String curLine = sc.nextLine();
int curSize = lines.size();
String LastLine = curSize > 0 ? lines.get(curSize-1) : "";
if (curLine.isEmpty() && LastLine.isEmpty())
break;
lines.add(curLine);
System.out.println(curLine);
}
// lines.removeIf(e -> e.isEmpty());

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.

Paragraphs being miscounted

So I want my program to count the number of paragraphs from a text file but unfortunately I end being 1 number off. I need the answer of 4 when I keep getting 5. Here is the text:
Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in
Liberty, and dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so
dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a
portion of that field, as a final resting place for those who here gave their lives that that nation might
live. It is altogether fitting and proper that we should do this.
But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground.
The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add
or detract. The world will little note, nor long remember what we say here, but it can never forget
what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which
they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great
task remaining before us -- that from these honored dead we take increased devotion to that cause for which
they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have
died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of
the people, by the people, for the people, shall not perish from the earth.
Abraham Lincoln
November 19, 1863
And here is my code:
public static void main(String[] args) {
String input;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
input = kbd.nextLine();
try
{
// Set up connection to the input file
Scanner input1 = new Scanner(new FileReader(input));
// Set up connection to an output file
PrintWriter output=newPrintWriter(newFileOutputStream(input".txt"));
// initialize the counter for the line numbers
int lineNum = 0;
int words = 0;
int characters = 0;
int paragraphs = 0;
// as long as there are more lines left in the input file
// read from the input file, and copy to the output file
while (input1.hasNextLine())
{
// read a line from the input file
String line;
line = input1.nextLine();
// copy the line to the output file, adding a
// line number at the front of the line
output.println(line + "\n");
// increment the line counter
lineNum++;
//Section for counting the words
boolean word = false;
for (int i = 0; i < line.length(); i++) {
//checks for letters and counts as word till it finds a space then checks for a letter again.
if (!Character.isWhitespace(line.charAt(i)) && !word) {
words++;
word = true;
}
else if (Character.isWhitespace(line.charAt(i)) && word){
word = false;
}
}
characters += line.length();
paragraphs += getPara(line);
}
// close the files
input1.close();
output.close();
System.out.println("Lines: " + lineNum);
System.out.println("Words: " + words);
System.out.println("Characters: " + ((characters)));
System.out.println("Paragraphs: " + paragraphs);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error opening one of the files.");
}
}
public static int getPara(String line){
int count = 0;
boolean p = false;
if (line.isEmpty() && !p){
count++;
p = true;
}
else if (!line.isEmpty() && p){
p = false;
}
return count;
}
}
Your code counts empty lines rather than paragraphs. Stray empty lines in your input file will add to your paragraph count.
Assumptions and definitions are key in cases like this. How is a paragraph defined in your requirements documentation? Can you assume that paragraphs will be a single line terminated by a newline or will you need to account for newlines within paragraphs? If it's the former, all nonempty lines returned by nextLine() will be paragraphs. If it's the latter, then you will need to add to your paragraph count only if an empty line or EOF follows a nonempty line.
In any case, you will be better served using language utilities like String.split() to count your words, unless you're required to do it manually.

I'm having a hard time terminating a java loop

I'm sure if you read the snippet you'll understand what I'm trying to do. However, I tried it first with null and "". I think .eoln() won't work because I'm asking for multiple lines of input, of which all have an end of line. I would preferably have the loop terminate when the user returns an empty line. For some more background, I've used the ==/!= and .equals() operators/method to experiment. I also just tried a do/while to no avail.
The asterisks were added to test if the empty string was an issue for the while statement.
Can anyone explain what I clearly don't understand about Java/TextIO yet?
EDIT - Revised Code Snippet:
while(write){
pl("Begin writing content to fill file.");
pl("");
pl("Return a line with a single SPACE or");
pl("\"\\n\" to represent line breaks in your");
pl("");
pl("Return two asterisks ** when done writing,");
pl("and you will be then prompted to select a file");
pl("to save your writing to.");
String input = TextIO.getln();;
String value = new String();
while(!(input.equals(""))) {
if (input == " " || input == "\\n") {
value += "\\n" + "\\n";
} else {
value += input + " ";
} // end if/else //
input = TextIO.getln();
} // end while(input) //
TextIO.writeUserSelectedFile();
p(value);
TextIO.writeStandardOutput();
pl("Would you like to write to another file?");
Boolean cont = TextIO.getBoolean();
write = cont;
}
}

While loops aren't repeating

This program will read each phone number from the telephones.txt file and will check if it can be translated into one or more words of words.txt file. The output of the program will contain the telephone numbers and their word representatives. (assuming there are words and phones in the file)
public static void main(String[] args) throws IOException
{
Scanner phones = new Scanner(new File("phones.txt"));
Scanner words = new Scanner(new File("words.txt"));
PrintWriter outfile = new PrintWriter(new FileWriter("outfile.txt"));
String number = "", output = "", code = "" ;
//Scans for next phone string
while(phones.hasNext())
{
number = phones.next();
number = number.replace("-","");
//Scans for next word string
while(words.hasNext())
{
code = words.next();
char[] wordChars = null;
wordChars = code.toCharArray();
output = "";
//converts word to digits
for(char wordChar : wordChars)
{
output = output.concat(new String(convert(wordChar)));
}
if(number.equals(output));
{
System.out.println(number + " " + code);
}
break;
}
}
}
This is what I have done so far, except I can't figure out something
if(number.equals(output));
{
System.out.println(number + " " + code);
}
For this line Im trying to see if the output has the same value as the number and if it does have the same value I want to print it out however this is what happens in my program.
I tried tracing my program and this is what i think is happening but its not...
Enter first while loop while theres a phone string continue
Set number to next phone string
Enter 2nd while loop while theres a word string continue
Set code to the CURRENT word string and convert it to a digit value (assume the conversion is correct)
If converted string isn't equal to number I want to continue the loop and search for the next word. And if it is I want to display number + code and continue searching for more words.
After i search through the list of words I want to continue to the next number and repeat the search for words for that number until the first while loop has no more numbers
Answering your second issue:
After i search through the list of words I want to continue to the
next number and repeat the search for words for that number until the
first while loop has no more numbers
Answer:
You should create a new instance if scanner in each iteration, i.e. move the line:
Scanner words = new Scanner(new File("words.txt"));
into the body of the outer loop.
while(phones.hasNext())
{
Scanner words = new Scanner(new File("words.txt"));
number = phones.next();
number = number.replace("-","");
//Scans for next word string
while(words.hasNext())
{
...
}
}
Your inner loop always ends on a break. So the loop body will only ever get executed once. Just put your break into the block that describes the handling of a successful phone number match.

Categories

Resources