How to exit loop with ENTER - java

How do I exit this loop when user presses ENTER. This is part of the codes I have done. I am having problems in how to code when user presses ENTER.
static String[] itemList = new String[10];
do {
System.out.print("Enter item (press ENTER to exit) " + (count + 1) + ": ");
String item = input.next();
itemList[count] = item;
if (item == "")
count = itemList.length;

You are comparing Strings using == not .equals().
This compares the pointer to the String, not the contents of the String.

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();
while(readString!=null)
{
System.out.println(readString);
if(readString.equals(""))
System.out.println("Read Enter Key.");
if(scanner.hasNextLine())
readString = scanner.nextLine();
else
readString = null;
}

Check the condition before entering into loop. For example:
boolean statusIsNotReady = true;
while(statusIsNotReady) {
// do your fty;
if(someCondition) {
statusIsNotReady = false; // If the status changed
}
}

public class SampleInputReader{
public static void main(String args[]){
String[] itemList = new String[10];
int count = 0;
Scanner keyboard = new Scanner(System.in);
String data = "";
do{
System.out.print("Enter item (press ENTER to exit) " + (count + 1)+ ": ");
data = keyboard.nextLine();
if(data.isEmpty())
break;
itemList[count] = data;
count++;
}while(true);
for(int i = 0; i< itemList.length; i++)
System.out.println(itemList[i]);
}
}
But instead of Array i suggest you to use Arraylist.

Related

comparing user inputs in array to make sure they dont have the same name in java

What am I missing it keeps, coming back false on the first try. What do I need to change to make sure it scans to get rid of duplicates.
final int numPassengers = 4;
final int numShips = 2;
boolean input = false;
String[] travelerNames = new String[4];
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < numPassengers; ++i) {
System.out.println("Enter traveler name ");
do {
travelerNames[i] = scanner.nextLine();
if(travelerNames[i].equals(travelerNames[i])) {
System.out.println("Names cannot match enter new name!");
input = false;
scanner.next();
}
else {
input = true;
}
} while(!input);
System.out.println(travelerNames[i]);
A simple solution would be to use an arraylist.
Arraylist has a method called contains.
List<String> names = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if(names.contains(input)){
System.out.println("Name is duplicated");
}
else {
names.add(input);
}
I hope i could help you with your Problem
travelerNames[i] = scanner.nextLine(); Whoops... too late, it's already within the Array and it's in there before you get to check and see if it has been previously entered. Don't save a step here by popping the name into the Array right away, put the name into a String variable first then traverse the Array to see if that name already exists, for example:
for (int i = 0; i < numPassengers; ++i) {
String name = "";
while(name.isEmpty()) {
System.out.print("Enter traveler name #" + (i + 1) + ": -> ");
name = scanner.nextLine().trim();
if (name.isEmpty() || name.matches("\\d+")) {
System.out.println("Invalid Name Supplied! ("
+ name + ") Try again...\n");
name = "";
continue;
}
// Is the name already within the travelerNames[] Array?
for (String nme : travelerNames) {
if (nme != null && nme.equalsIgnoreCase(name)) {
System.out.println("Invalid Entry! The name '" + name
+ "' already exists! Try again...\n");
name = "";
break;
}
}
}
// Everything seems OK so add the name to the Array.
travelerNames[i] = name;
}
System.out.println();
System.out.println("The names contained within the Array:");
System.out.println(Arrays.toString(travelerNames));

java.util.LinkedHashMap$LinkedKeyIterator infinite loop in LinkedHashSet

System.out.print("Enter the size of linked hash set: ");
Scanner s = new Scanner(System.in); // Create a Scanner object
int size = s.nextInt();
HashSet<String> lhashset = new HashSet<>(size);
for(int i=0; i<size; i++)
{
System.out.print("Enter the name: ");
String name = s.next();
lhashset.add(name);
}
System.out.println("\nEnter the name you want to find: ");
String find = s.next();
if(lhashset.contains(find))
{
System.out.println("\nYes the Linked Hash Set contains " +find);
System.out.print("Do you want to remove the name? ");
String ch = s.next();
String choice = "yes";
if(ch.equals(choice))
{
lhashset.remove(find);
System.out.println("\nElement removed.");
}
else
{
System.out.println("\nGoodbye");
}
}
else
{
System.out.println("Does not contain name.");
}
The first if statement works fine, but when I try to go to else statement(print"does not contain"), I get an infinite loop as per the heading. The same happens for the nested if statement.
ch.equals(choice) will not work. Updating the code with correct syntax.
public class Soln {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); // Create a Scanner object
HashSet<String> lhashset = new HashSet<>();
lhashset.add("TEST");
System.out.println("\nEnter the name you want to find: ");
String find = s.next();
if(lhashset.contains(find))
{
System.out.println("\nYes the Linked Hash Set contains " +find);
System.out.print("Do you want to remove the name? ");
int ch = s.nextInt();
if(ch == 1)
{
lhashset.remove(find);
System.out.println("\nElement removed.");
}
else
{
System.out.println("\nGoodbye");
}
}
else
{
System.out.println("Does not contain name.");
}
}
}

removing null values for an array

The code takes input for a user for a name and a second input for a birthday. It can store up to 10 entries both name + birthday and can be terminated early by entering "ZZZ". I figured out most of the code but the part I can't figure out is if the entries are terminated before 10 then there is a text that says something along the lines of [adam, john, dave, null, null, null,....]
import java.util.*;
public class BirthdayReminderRedo {
public static void main(String[] args) {
String[] name = new String[10];
String[] birthday = new String[10];
String[] selectName = new String[100];
String inputName;
Scanner userInput = new Scanner(System.in);
int count;
for(count=0; count < 10; count++){
System.out.println("Please enter a name or type ZZZ to end name inputs>>");
inputName = userInput.nextLine();
if(inputName.equals("ZZZ")){
while(name.remove(null)){}
System.out.println(count);
System.out.println(name);
//System.out.println(Arrays.toString(name));
break;
}
else{
name[count] = inputName;
}
if(count == 10){
for(int secondCount = 0; secondCount > 0; secondCount++);
break;
}
else{
System.out.println("Please enter birthday in the format DD/MM/YYYY>>");
birthday[count] = userInput.nextLine();
}
}
String dataCheck = null;
do{
for(int secondCount = 0; secondCount < 10; secondCount++){
System.out.println("Please enter a name to get the birthday or enter ZZZ to end program>>");
userInput = new Scanner(System.in);
dataCheck = userInput.nextLine();
selectName[secondCount] = dataCheck;
boolean valid = false;
if(selectName[secondCount].equals("ZZZ")){
System.out.println("Thank you for using this program");
break;
}
for(int thirdCount = 0; thirdCount < 10; thirdCount++){
if(selectName[secondCount].equals(name[thirdCount])){
System.out.println(birthday[thirdCount]);
valid = true;
}
else if (thirdCount == 9 && !valid){
System.out.println("Not a valid name");
}
}
}
} while(!"ZZZ".equals(dataCheck));
}
}
Any tips on how I can remove the nulls from this println?
Instead of using arrays. Why not utilize Lists and instantiate an ArrayList so that you don't have to worry about extra/undefined elements in your collection?
List<String> name = new ArrayList<String>();
List<String> birthday = new ArrayList<String>();
String[] selectName = new String[100];
String inputName;
Scanner userInput = new Scanner(System.in);
int count;
for(count=0; count < 10; count++){
System.out.println("Please enter a name or type ZZZ to end name inputs>>");
inputName = userInput.nextLine();
if(inputName.equals("ZZZ")){
break;
}
else{
name.add(inputName);
}
if(count == 10){ //Sunny - Count will never be 10
for(int secondCount = 0; secondCount > 0; secondCount++);
break;
}
else{
System.out.println("Please enter birthday in the format DD/MM/YYYY>>");
birthday.add(userInput.nextLine());
}
}
If you insist on using arrays than you either:
Copy the values to a new array initialized to the number of inputs, if you want to use Arrays.toString.
If you don’t care for using that method, you can also print them as follows:
for(String n: name)
{
if(n!=null)
System.out.print(n + " ");
}
If using arrays is not important, do as the other answer suggests; use ArrayList.

User validation input under forloop

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String regex = "[a-zA-Z ]+$";
String regex1 = "\\d[0-9]|[1-9]";
String regex2 = "^[a-zA-Z0-9 ]+$";
String petName;
StringBuilder output = new StringBuilder();
do {
System.out.print("\nHow Many Pet do you have? Give from 1-3:");
petName = input.nextLine();
if (petName.isEmpty()) {
System.out.println("Number field should not be Empty.");
} else if (!petName.matches(regex1)) {
System.out.println("Please Enter A Valid Number!");
}
} while (!petName.matches(regex1));
do {
Integer.parseInt(petName);
String[] pets = new String[Integer.parseInt(petName)];
System.out.print("\nList Down All Your Pet Names:\n");
for (int i = 0; i < pets.length; i++) {
System.out.print("\nPET" + (i + 1) + ":");
pets[i] = input.nextLine();
if (pets[i].isEmpty()) {
System.out.print("String field should not be Empty.");
} else if (!pets[i].matches(regex)) {
System.out.print("Please input a valid String.");
}
}
output.append("\nThese Are The List Of The Pets You Have:");
for (int i = 0; i < pets.length; i++) {
output.append("\nPET:").append(i + 1).append(" ").append(pets);
}
} while (!petName.matches(regex));
System.out.println(output);
}
I'm having a little problem with the above codes.
What I want is if I input an integer then it will prompt me this message "Please input a valid String" or if I didn't type anything in the field then it will prompt me this another message "String field should not be Empty". But what happen is even if I type a string value in the field then it's still prompting the message "Please input a valid String" and the loop is still keep doing the same over and over again every time I press enter.
You have some issues with your second while loop. First of all, your loop condition is checking petName, which isn't changed after leaving the first while loop. Second, the for loop seems to be nested incorrectly. Since you want to loop for a valid input of each pet name, you should put the second while loop in the for loop and not the other way around.
It's probably easier to see with the following modified code. Also note that calling append(pets) outputs the toString result of the pets array and not the individual pet name. For this you should use append(pets[i]).
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String regex = "[a-zA-Z ]+$";
String regex1 = "\\d[0-9]|[1-9]";
String regex2 = "^[a-zA-Z0-9 ]+$";
String petName;
StringBuilder output = new StringBuilder();
do
{
System.out.print("\nHow Many Pet do you have? Give from 1-3:");
petName = input.nextLine();
if (petName.isEmpty())
{
System.out.println("Number field should not be Empty.");
}
else if (!petName.matches(regex1))
{
System.out.println("Please Enter A Valid Number!");
}
} while (!petName.matches(regex1));
String[] pets = new String[Integer.parseInt(petName)];
System.out.print("\nList Down All Your Pet Names:\n");
for (int i = 0; i < pets.length; i++)
{
do
{
System.out.print("\nPET" + (i + 1) + ":");
pets[i] = input.nextLine();
if (pets[i].isEmpty())
{
System.out.print("String field should not be Empty.");
}
else if (!pets[i].matches(regex))
{
System.out.print("Please input a valid String.");
}
} while (!pets[i].matches(regex));
}
output.append("\nThese Are The List Of The Pets You Have:");
for (int i = 0; i < pets.length; i++)
{
output.append("\nPET:").append(i + 1).append(" ").append(pets[i]);
}
System.out.println(output);
}

Storing strings in list with loop, then printing the list

My goal is to ask the user to enter a bunch of strings in a loop, and when they enter "stop", the loop breaks and prints all those strings with a comma at the end of each word. For example, if the user enters "first", "second", "third", and "fourth", then the program would print the following:
first, second, third, fourth
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int i;
String s;
String[] listOfStrings = new String[1000];
String last = "";
System.out.println("Please enter some Strings: ");
for (i = 1; i>0; i++) {
listOfStrings[i] = kb.next();
last = listOfStrings[i] + ",";
if (listOfStrings[i].equalsIgnoreCase("stop")) {
break;
}
}
System.out.print(last);
There is a problem because it always just winds up printing the last word and nothing else. Any help would be greatly appreciated.
I would use an ArrayList:
Scanner sc = new Scanner(System.in);
List<String> list = new ArrayList<String>();
while (sc.hasNext()) {
String s = sc.next();
if (s.equalsIgnoreCase("stop")) {
break;
} else {
list.add(s);
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i) + ",");
}
If you want everything in one line, you can do this:
Scanner sc = new Scanner(System.in);
String line = "";
while (sc.hasNext()) {
String s = sc.next();
if (s.equalsIgnoreCase("stop")) {
break;
} else {
line += s + ", ";
}
}
System.out.println(line.substring(0, line.length()-2));

Categories

Resources