Hello guys I wrote program to add a name to array list but if you wrote 2nd times the same word the loop stop and write You gave the word twice. but I don't know where is the problem, Can you help me somebody?
package recurring.word;
import java.util.ArrayList;
import java.util.Scanner;
public class RecurringWord {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
while(true){
System.out.print("Type a word: ");
String name = reader.nextLine();
words.add(name);
if (words.contains(name)) {
break;
}
System.out.println("You gave the word " + name + "twice");
}
}
}
You have a logic error here:
words.add(name);
if (words.contains(name)) {
break;
}
You add the word to the ArrayList and then immediately after, if it is in the ArrayList you break out of the loop. You need to switch it to:
if (words.contains(name)) {
break;
}
words.add(name);
This will check to see if you already typed in the word before you add it to the list.
Also you have the print statement inside the while loop which is not what you want. Move it outside:
ArrayList<String> words = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
String name;
while(true){
System.out.print("Type a word: ");
name = reader.nextLine();
if (words.contains(name)) {
break;
}
words.add(name);
}
System.out.println("You gave the word " + name + " twice");
Related
I have the following code, which continues to ask the user to enter a letter as long as the letter is either "a" or "b":
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter;
System.out.print("Enter a letter: ");
letter = scan.nextLine();
while(letter.equals("a") || letter.equals("b"))
{
System.out.println("You entered: " + letter);
System.out.print("Enter a letter: ");
letter = scan.nextLine();
}
}
}
But the following code is repeated twice:
System.out.print("Enter a letter: ");
letter = scan.nextLine();
Is there a way to make the above code only appear one time?
while (true) {
System.out.print("Enter a letter: ");
String letter = scan.nextLine();
if (!letter.equals("a") && !letter.equals("b"))
break;
System.out.println("You entered: " + letter);
}
This is the classic example of a loop that is neither naturally while-do nor do-while — it needs to exit from the middle, if you want the same behavior and also to reduce code duplication.
(Notice also that the variable declaration letter has been moved to an inner scope since it is no longer needed in the outer scope. This is a small positive indication.)
As an alternative to while (true) some languages allow degenerate for-loop as in for(;;).
The below reverses the logic of the conditional loop exit test, at the expense of more control flow logic.
while (true) {
System.out.print("Enter a letter: ");
String letter = scan.nextLine();
if (letter.equals("a") || letter.equals("b")) {
System.out.println("You entered: " + letter);
continue;
}
break;
}
(There is no difference between these in efficiency terms — these are equivalent at the level of machine code.)
do while loop
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter;
do{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
System.out.println("You entered: " + letter);
}while(letter.equals("a") || letter.equals("b"));
}
}
It will loop once first, and then continue again if the statment is true.
You need to perform three sequential actions in a loop:
read the input entered by the user;
validate the input;
print the input, but only if it is valid.
That means that conditional logic must reside inside the loop before the statement that prints the input. And that makes the condition of the loop redundant. Instead, we can create an infinite loop with a break statement wrapped by a condition, that validates the input.
While loop
That's how it can be done using a while loop:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String letter;
while (true) {
System.out.print("Enter a letter: ");
letter = scan.nextLine();
if (!letter.matches("[ab]")) break;
System.out.println("You entered: " + letter);
}
}
Method matches() that expects a regular expression as argument is used in the code above to simplify the termination condition.
For more information on regular expressions, take a look at this tutorial
For loop
Regarding the advice of utilizing a for loop - that's doable, but by its nature the task of reading the user input fits better in the concept of while loop because we don't know the amount of data in advance, and the iteration can terminate at any point in time.
Also note syntax of the for statement consists of three parts separated with a semicolon:
initialization expression - allow to define and initialize variables that would be used in the loop;
termination expression - condition which terminates the execution of the loop;
increment expression - defines how variables would change at each iteration step.
All these parts are optional, but the two semicolons ; inside the parentheses always have to be present.
Because as I've said earlier, the input needs to be validated inside the loop, we can't take advantage from the termination expression and increment expression.
For the sake of completeness, below I've provided the version of how it can be achieved using a for loop:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for (String letter = "a"; ;) {
System.out.print("Enter a letter: ");
letter = scan.nextLine();
if (!letter.matches("[ab]")) break;
System.out.println("You entered: " + letter);
}
}
The only advantage is that the scope of the variable letter was reduced. But approach of utilizing while loop is more readable and expressive.
Alternative approach
Another option is to preserve your initial structure of the code:
initialize the variable letter before the loop, at the same line where it is defined;
enter the loop if letter holds a valid input;
print the input and reassign the variable.
But in order to avoid duplication of the code line responsible for printing the prompt and reading the input will be extracted into a separate method.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String letter = readInput(scan);
while (letter.matches("[ab]")) {
System.out.println("You entered: " + letter);
letter = readInput(scan);
}
}
public static String readInput(Scanner scan) {
System.out.print("Enter a letter: ");
return scan.nextLine();
}
As Bobulous mentioned, a do-while loop is another simple solution. If duplicating the conditional is still a deal-breaker for you, though, you can also create a function that returns a boolean, and, when true, prints the extra text.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter;
do
{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
} while(inputIsAOrB(letter));
}
public static boolean inputIsAOrB(String input) {
if (input.equals("a") || input.equals("b"))
{
System.out.println("You entered: " + input);
return true;
}
else
{
return false;
}
}
A while loop with a break after executing your second print command will limit the code to only asking for a single input.
Scanner ct = new Scanner(System.in);
String input;
System.out.print("Please enter either 'a' or 'b': ");
input = ct.nextLine();
while(input.equals("a") || input.equals("b")){
System.out.println("You entered: " + input);
break;
}
You can also view the problem as generating and processing a stream of strings. The side effects in the generator may trigger some philosophical discussions, otherwise I think it is quite clean:
Stream.generate(() -> {
System.out.print("Enter a letter: ");
return scan.nextLine();
})
.takeWhile(str -> str.equals("a") || str.equals("b"))
.forEach(str -> System.out.println("You entered: " + str));
... which will run like this:
Enter a letter: a
You entered: a
Enter a letter: b
You entered: b
Enter a letter: c
Process finished with exit code 0
Simply
List<Character> expectedChars = new ArrayList<>();
expectedChars.add('a');
expectedChars.add('b');
while(!expectedChars.contains(line = scan.nextLine())) {
System.out.println("Not expected");
}
// Now has a expected char. Proceed.
I without using any break or if-else externally (I am using ternary operator though) within control loop, you can also use below :
Scanner scanner = new Scanner(System.in);
boolean flag=true;
while (flag) {
System.out.println("enter letter");
String bv = scanner.nextLine();
flag=bv.matches("a|b");
System.out.println(flag?"you entered"+bv:' ');
}
with for loop, it can be even simpler :
Scanner scanner = new Scanner(System.in);
for (boolean flag = true; flag;) {
System.out.println("enter letter");
String bv = scanner.nextLine();
flag = bv.matches("a|b");
System.out.println(flag ? "you entered" + bv : ' ');
}
Or if you ok for having whitspace for first run:
Scanner scanner = new Scanner(System.in);
String aa=" ";
String bv=null;
for (boolean flag = true; flag;aa=(flag?"you entered: "+bv:" ")) {
System.out.println(aa);
System.out.println("enter letter");
bv = scanner.nextLine();
flag = bv.matches("a|b");
}
You can easily run a while loop until letter = "a" or letter = "b". Code will start the while loop with intial "" value of the letter and get the new value by scanner. Then it check the new value of the letter before starting the next round of the loop.
package com.company;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter = "";
while(!(letter.equals("a") || letter.equals("b")))
{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
System.out.println("You entered: " + letter);
}
}
}
Similar as previous answer, but from a code readability perspective i would create an array of valid characters instead and use in condition. That results in the more "text like" condition below reading "if not validCharacters contains letter":
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<String> validCharacters = List.of("a", "b");
while (true) {
System.out.print("Enter a letter: ");
String letter = scan.nextLine();
if (!validCharacters.contains(letter)) {
break;
}
System.out.println("You entered: " + letter);
}
}
Your code just needed a little tweak to make it work, although you can use many more efficient approaches but here it is:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String letter = "a";
while(letter.equals("a") || letter.equals("b"))
{
System.out.print("Enter a letter: ");
letter = scan.nextLine();
System.out.println("You entered: " + letter);
}
}
}
I am trying to tell whether that string was found in the list or not.
For instance, if I put Max in my list and search for Max, it should say "Max was found" If not, then it should say "Max was not found"
I do not know how to approach to getting the answer from here.
import java.util.ArrayList;
import java.util.Scanner;
public class OnTheList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
list.add(input);
}
System.out.print("Search for? ");
System.out.print(scanner.nextLine());
if (list.contains(list)) ----> I think this is the part where I am not getting it
System.out.println(" was found!");
else
System.out.println(" was not found");
}
}
You may store the word to search, here you ask for it with scanner.nextLine() and print it but didn't save it. Then use the variable you saved the word in, to check into the List
System.out.print("Search for? ");
String toSearch = scanner.nextLine();
if (list.contains(toSearch))
System.out.println(toSearch + " was found!");
else
System.out.println(toSearch + " was not found");
Here you didn't store the user input that you are getting from Search for ,and you are trying to search an element of the list but passing list as the argument for the contains() method ,So first store the user input for a variable the search that input by passing it as the argument to contains() method and make sure to close the scanner variable at the end of the program to avoid memory leaks like below.
import java.util.ArrayList;
import java.util.Scanner;
public class OnTheList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
break;
}
list.add(input);
}
System.out.print("Search for? ");
String toSearch = scanner.nextLine();
if (list.contains(toSearch))
System.out.println(" was found!");
else
System.out.println(" was not found");
scanner.close();
}
}
I have been trying to write this code where a user enters two words with or without a comma and if it does not have a comma print the an error saying so and then loop back to ask for another set of words. Yes this is homework and I have searched the internet for help and it just has not clicked with me so far. I am needing help with the loop in my code which is java. These are the set of requirements for my warm up program followed by my code. Thank you for any help anyone can give.
1) Prompt the user for a string that contains two strings separated by a comma.
2) Report an error if the input string does not contain a comma.
3) Extract the two words from the input string and remove any spaces. Store the
strings in two separate variables and output the strings.
4) Using a loop, extend the program to handle multiple lines of input. Continue
until the user enters q to quit.
Here is my code:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner inSS = null;
String lineString = "";
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
System.out.println("Enter input string: ");
while (!inputDone) {
lineString = scnr.nextLine();
inSS = new Scanner(lineString);
if (firstWord.equals("q")) {
System.out.println("Exiting.");
inputDone = true;
}
if (lineString.contains(",")) {
String[] parts = lineString.trim().split("\\s*,\\s*");
firstWord = parts[0];
secondWord = parts[1];
System.out.println("First word: " + firstWord);
System.out.println("Second word: " + secondWord);
} else {
System.out.println("Error: No comma in string");
}
break;
}
return;
}
}
1) You do not need the return statement for a main method of type void
2) The break at the end of your loop is what is terminating it after the first run.
Writing break; within your loop is the same thing as telling your loop to stop looping. If you want to define another condition to terminate your loop, but dont want to put it in your while, then put your break inside of some sort of condition, that way it doesn't happen every single time.
I am trying to figure out when the user enters q the program quits here is my code so far.
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
String s = sc.nextLine();
System.out.println("Enter input string: ");
if (s.indexOf(",") == -1) //checks if there is a comma in the string
{
System.out.println("Error: No comma in string");
} else {
//there is a comma in the string
String s1 = s.substring(0, s.indexOf(","));
String s2 = s.substring(s.indexOf(",") + 1);
s1 = s1.replace(" ", "");
s2 = s2.replace(" ", "");
//store both the strings in s1 and s2
System.out.println("First word: " + s1);
System.out.println("Second word: " + s2);
s1 = s1.trim();
s2 = s2.trim(); //remove extra spaces
System.out.println(s1 + " " + s2);
break;
}
}
}
}
I need to incorporate an IF statement to break the script when the user enters the letter Q.
I also need to display their input backwards to them - I am unsure on how I would do this, here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
list.add(name);
}
Scan.close();
}
}
To check against Q:
while(Scan.hasNext())
{
name = Scan.nextLine();
if(name.equals("Q") || name.equals("q"))
{
break;
}
list.add(name);
}
To show list in the reverse order:
for(int i = list.size() - 1; i >= 0; i--)
{
System.out.println(list[i]);
}
How about this.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListOfNames {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> list = new ArrayList<String>();
Scanner Scan = new Scanner (System.in);
String name;
System.out.println("Please enter some words (You may press Q to finish): ");
while (Scan.hasNext())
{
name = Scan.nextLine();
if( name.equals("Q") ) {
break;
}
list.add(name);
}
Scan.close();
}
}
To display input backward put this code after loop that scans input.
for(int i = list.size()-1; i>=0; i--)
System.out.println(list.get(i));
while (Scan.hasNext())
{
name = Scan.nextLine();
//Input is stored to name, so you need to compare input with Q
if("Q".equals(name)
{
//You need to exit the loop
break;
}
list.add(name);
}
//You have what ever user entered in list. So use iterator (or) for-each to print them out again.
As I suspect this is homework, there are probably extra marks for using the Stack class.
Get the data in the loop and push it onto the Stack. Then when you need to print it pop results from the Stack.
From a Software Engineering standpoint, we try to stay away from using break; statements in loops. Instead, it's recommended to use a terminator
final String TERMINATOR = "Q";
boolean terminated = false;
while (scanner.hasNext() && !terminated)
{
String line = scanner.next();
if (!line.equals(TERMINATOR))
{
list.add(line);
}
else
{
terminated = true;
}
}
Also note how we do !line.equals(TERMINATOR) instead of line.equals(TERMINATOR) and do the normal list appending. This is because list appending is the nominal case and as such we want to do the least amount of checks and jumping to get to it.
As for printing out your list in reverse, you can do a simple backwards iterative for-loop
for (int i = list.size()-1; i >= 0; i--)
{
System.out.print(list.get(i) + " ");
}
thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}
Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);
get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;
Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.
You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.
import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}