java.util.LinkedHashMap$LinkedKeyIterator infinite loop in LinkedHashSet - java

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

Related

Scan a number of names, print names (number==amount of names) and print Hello to each of them

I am new to Java and have a task: Scanner a number of "strangers' " names, then read these names and print "Hello+name" to the console. If number of strangers is zero, then print "Looks empty", if the number is negative, then print "Looks negative to me".
So the input and output to console should look like this:
3
Den
Ken
Mel
Hello, Den
Hello, Ken
Hello, Mel
So I have this code edited from someone with some related task, but it seems I miss something as I am new to Java...
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
while (num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
} while (num<0) {
System.out.println("Seriously? Why so negative?");
break;
}
String[] numbers = new String[num];
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +input.nextLine());
}
With using do while loop you can ask the number to the user again and again if it is negative number.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int num;
String name;
Scanner scan = new Scanner(System.in);
//The loop asks a number till the number is nonnegative
do{
System.out.print("Please enter the number of strangers: ");
num = scan.nextInt();
if(num<0) {
System.out.println("It cannot be a negative number try again.");
}else if(num==0) {
System.out.println("Oh, it looks like there is no one here");
break;
}else{
String[] strangers = new String[num];
//Takes the names and puts them to the strangers array
for(int i=0;i<num;i++) {
System.out.print("Name " + (i+1) + " : ");
name = scan.next();
strangers[i] = name;
}
//Printing the array
for(int j=0; j<num; j++) {
System.out.println("Hello, " + strangers[j]);
}
break;
}
}while(num<0);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of an Array");
int num = input.nextInt();
if(num==0) {
System.out.println("Oh, it looks like there is no one here");
}
else if(num<0) {
System.out.println("Seriously? Why so negative?");
}
else {
String numbers[] = new String[num];
input.nextLine();
for (int i=0; i< num;i++) {
numbers[i]=input.nextLine();
}
for (int i=0; i< numbers.length;i++) {
System.out.println("Hello, " +numbers[i]);
}
}
}
}
This is how your code will look and you'll need to add member function input.nextLine(); to read newline character, so there can't be problem regarding input

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

Removing a user defined element from a user defined string array [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have an assignment due in about 6 hours and I really need help. I stayed up all night working on this but I can't seem to figure it out.
Basically what I need to do is, I have a user defined array. I'm supposed to take that array and manipulate that string into a variety of things. I've gotten most of it but I can't seem to remove a user defined element in the user defined string. I've tried using a for loop to try and find the specific character that the user wants to remove but I can't seem to get it to compile or write properly. This is my code so far:
import java.util.Scanner;
import java.util.Arrays;
public class StringManipulator {
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equals("Print Reverse") || choice.equals("print reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equals("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equals("Replace Single") || choice.equals("replace single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
else if (choice.equals("Remove") || choice.equals("remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
char charRemove = ridOf2.charAt(0);
for (int i = 0; i < array.length; i++) {
if(userStr.charAt(i) != ridOf2) {
userStr += userStr.charAt(i);
}
}
}
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
The only section that i'm actually worried about at this moment is the
else if(choice.equals("Remove")
section of the code.
Give this a shot explanation further down
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
String userStr;
Scanner input = new Scanner(System.in);
System.out.println("Enter the string to be manipulated");
userStr = input.nextLine();
while (true) {
System.out.println("Enter your command");
System.out.println("Print Reverse");
System.out.println("Replace All");
System.out.println("Replace Single");
System.out.println("Remove");
System.out.println("Quit");
String choice = input.nextLine();
String[] array = userStr.split("");
if (choice.equalsIgnoreCase("Print Reverse")) { //reverses the string
for(int i = array.length - 1;i >= 0; i --) {
System.out.print(array[i]);
}
System.out.println();
}
else if (choice.equalsIgnoreCase("Replace All")) { //Replaces all input letters with new letters that user inputs
System.out.println("What letter would you like to replace?");
String ridOf = input.nextLine();
System.out.println("What letter do you want to replace it as?");
String replace = input.nextLine();
String[] newArray = array;
for (int i = 0; i < array.length; i++) {
if(array[i].equals(ridOf)) {
array[i] = replace;
}
}
System.out.println("");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println("");
}
else if (choice.equalsIgnoreCase("Replace Single")) {
System.out.println("Enter the character to replace?");
String ridOf1 = input.nextLine();
System.out.println("Enter the new character");
String replace1 = input.nextLine();
System.out.println("Which " + ridOf1 + " would you like to replace?");
int choice1 = input.nextInt();
}
This is the section I changed .equalsIgnoreCase compares them ignoring case as expected. Then I made sure the user only entered one char and if more ignore them. Then changed the char remove to be a string of only the first char(because you cannot replace with a char it needs to be a string) then I replaced the char to be removed in the string with nothing essentially removing it and set the user string to the new user string
else if (choice.equalsIgnoreCase("Remove")) {
System.out.println("Enter the character to remove");
String ridOf2 = input.nextLine();
String charRemove = String.valueOf(ridOf2.charAt(0));
userStr = userStr.replaceAll(charRemove, "");//This will replace the first char the enter with nothing
}
End of section
else if (choice.equals("Quit") || choice.equals("quit")) {
System.exit(0);
}
}
}
}
String's replace should do it -
public class Test
{
public static void main(String [] args) {
String s = "Hello World";
s = s.replace(" ", "");
System.out.println(s);
}
}

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

How to exit loop with ENTER

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.

Categories

Resources