Scanner input and array duplicates verification causes an infinite loop - java

I code a program that lists entered names. But if the entered name is already in the array, the user has to reenter a different name.
I left a picture below that shows what is happening when I run the code
import java.util.Scanner;
public class list {
public static void main(String[] args) {
int numberofhumans;
Scanner al = new Scanner(System.in);
System.out.print("Enter the number of person: ");
numberofhumans = al.nextInt();
String[] list = new String[numberofhumans];
for (int i = 0; i < numberofhumans; i++) {
System.out.print("Enter the name:");
list[i] = al.nextLine();
for (int j = 0; j < i; j++) {
if (list[i] == list[j]) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
i--;
}
}
}
for (String string : list) {
System.out.println(string);
}
al.close();
}
}

Your issue is this line:
if (list[i] == list[j])
This checks if the 2 objects are equal, which they are not even if their content is the same. You need to use .equals method of String object to compare 2 strings. That should fix the problem:
if (list[i].equals(list[j]))
I would rather use a Set of String instead of an array for a better performance since you won't have to iterate over and over again for each new input. Something like:
Set<String> set = new HashSet<>();
for (int i = 0; i < numberofhumans; i++) {
System.out.print("Enter the name: ");
String name = al.nextLine();
while (set.contains(name)) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
System.out.print("Enter the name: ");
name = al.nextLine();
}
set.add(name);
}

Looking into your code, i found that you are using al.nextLine() which can return an empty String if the previous element the Scanner gave you was not a whole line. This is why you get prompted twice to enter a name when you run your program. See this post for further details.
Solution: use al.next() instead.
You are also comparing two String with the == operator which is comparing their adresses in memory. This comparison will always return false
Here is as working program:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
int numberofhumans;
Scanner al = new Scanner(System.in);
System.out.print("Enter the number of person: ");
numberofhumans = al.nextInt();
String[] list = new String[numberofhumans];
for (int i = 0; i < numberofhumans; i++) {
System.out.print("Enter the name:");
list[i] = al.next();
for (int j = 0; j < i ; j++) {
if (list[i].equals(list[j])) {
System.out.println("Name you just typed is already in your list. Enter a different name.");
i--;
}
}
}
for (String string : list) {
System.out.println(string);
}
al.close();
}

Related

Can I search for values in two different type of arrays with just one type of variable?

I'm quite new to Java and I've been asked to create a program in which the user is able to input two values and store them in separate arrays. The two values I'm asking the user are name and cell number, then I must allow the user to search by typing either a name or a cell number and return the corresponding name or cell number. I made it possible to input the values and search within them by number but when I try searching by name I get this error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "B"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
This is my code:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int i, x = 2;
static String names[] = new String[x];
static int numbers[] = new int[x];
public static void main(String[] args) {
Input();
Compare();
}
public static void Input() {
System.out.println("Enter a name followed by the persons number");
while (i < x) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.nextInt();
i++;
}
}
public static void Compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
var temp = sc.next();
System.out.println("NAME\tNUMBER");
for (i = 0; i < numbers.length; i++)
if ((names[i].equals(temp)) || (numbers[i] == Integer.parseInt(temp.trim()))) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
}
Thanks! :)
Looking at your problem statement it doesn't seem like you need to do any additional processing on numbers. Hence, even if you store the number as a string it should be fine in this case.
Hence after getting a user search criteria, you could do a simple string search within both arrays.
Hope this helps :)
First of all, the highest number that can be represented as an int in Java is 2147483647 (214-748-3647). This clearly will not be able to hold a high enough number to accommodate any phone number. To address this issue and also fix your main error, I would suggest storing the numbers as a string instead. Here's my solution:
import java.util.Scanner;
public class HW {
static Scanner sc = new Scanner(System.in);
private static int x = 2;
static String names[] = new String[x];
static String numbers[] = new String[x];
public static void main(String[] args) {
input();
compare();
}
public static void input() {
System.out.println("Enter a name followed by the persons number");
for (int i = 0; i < x; i++) {
System.out.println("NAME: ");
names[i] = sc.next();
System.out.println("NUMBER: ");
numbers[i] = sc.next();
i++;
}
}
public static void compare() {
System.out.println("=======SEARCH=======\nSEARCH CRITERIA: ");
String temp = sc.next();
System.out.println("NAME\tNUMBER");
for (int i = 0; i < numbers.length; i++) {
if ((names[i].equals(temp)) || numbers[i].equals(temp)) {
System.out.println(names[i] + "\t" + numbers[i]);
}
}
System.out.println("===END OF SEARCH====")
}
}
Please also note that I un-defined your variable i. As far as I can see there's no reason for you to be defining it. Hope this helps, good luck!

How do i exit a loop when user enters null

I need to write a program that prompts the user to to enter up to 5 movie titles. User to hit enter to exit input and partially fill array.
I've tried many solutions suggested in these pages. Either the loop continues or i get boolean/string conversion errors.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String [] Movie = new String[5];
String title;
int count = 0;
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
if(sc.equals("")) {
break;
}
title = sc.nextLine();
Movie[i] = title;
count++;
}
}
for(int i=0; i < Movie.length; i++) {
System.out.println(Movie[i]);
}
}
I expect the program to input code until user hits enter then see output of what was entered.
The problem is you are comparing Scanner object with empty String which is wrong sc.equals(""). First read the input into String and them check empty or not
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
title = sc.nextLine();
if(title.equals("")) {
break;
}
Movie[i] = title;
count++;
}
}
To just print an array use Arrays.toString
System.out.println(Arrays.toString(Movie));
You should not nest two loops for reading the input, you need one loop with two conditions; the count must be less than the Movies array length (which should be named movies to follow Java naming conventions) and there needs to be another line for the Scanner. I would prefer String.isEmpty() to String.equals(""). And your second loop should stop at count (since entries after that are potentially blank). Something like,
Scanner sc = new Scanner(System.in);
String[] movies = new String[5];
int count = 0;
for (int i = 0; i < movies.length && sc.hasNextLine(); i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
String title = sc.nextLine();
if (title.isEmpty()) {
break;
}
movies[count] = title;
count++;
}
for (int i = 0; i < count; i++) {
System.out.println(movies[i]);
}
import java.util.*;
public class MovieTitles
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String Movie[] = new String [10];
for(int i = 0 ; i < Movie.length; i++) {
System.out.println("Enter up to 10 Movie titles (enter null to exit). Title " + (i + 1));
String title = sc.nextLine();
if(title.matches("")) {
break;
}else {
Movie[i] = title;
}
}
System.out.println(Arrays.toString(Movie));
}
}
import java.util.*;
public class MovieTitles
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String Movie[] = new String [10];
int count = 0;
for(int i = 0 ; i < Movie.length; i++) {
System.out.println("Enter up to 10 Movie titles (enter null to exit). Title " + (i + 1));
String title = sc.nextLine();
if(title.matches("")) {
break;
}else {
Movie[i] = title;
count++;
}
}
System.out.println("Movie Titles:\n");
for(int j = 0 ; j < count; j++)
System.out.printf("%s\n", Movie[j]);
}
}

Why do I always get to enter a-1 strings in this string array?

Why do I always get to enter a-1 strings in this string array?
public class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Declare the variable
int a;
// Read the variable from STDIN
a = in.nextInt();
String strs[]=new String[a];
for(int i=0;i<a;i++)
strs[i]=in.nextInt();
}
}
You can change condition in your loop, like this :
for (int i = 0; i < a - 1; i++) {
strs[i] = in.nextInt();
}
You are iterating correctly a number of times equal to a. Not a-1. So the question appears to be invalid:
public class Source {
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
// Declare the variable
int a;
System.out.print("How many Strings would you like to enter? ");
// Read the variable from STDIN
a = in.nextInt();
String[] strs = new String[a]; // this will fail for certain values of `a`
for(int i=0; i<a; i++) {
System.out.format("Enter String number %d: ", i+1);
strs[i]= in.next();
}
System.out.println("Result: " + Arrays.toString(strs));
}
}
}
run:
How many Strings would you like to enter? 2
Enter String number 1: Apple
Enter String number 2: Pen
Result: [Apple, Pen]

NULL Array - how to link it in while loop

Basically I have to prompt a user to enter 10 string values, and then in another loop print them in ascending order, then in a final loop, print them in descending order. My array is bringing back null, obviously because I am not prompting users to enter actual information into the array object. I am really stuck on this. I know I need to somehow reference the "userStrings[]" array in my first while loop. I keep researching and keep getting integer loops questions and For loops. This has to be a while loop. I just can no figure out how to get the userStrings[] to actually fill up when the user enters the values. How do I get it linked in the loop?
public class HomeWork10
{
public static void main(String[] args)
{
String[] userStrings = new String[10];
int count = 0;
int count2 = 0;
while (count < 10)
{
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
count++;
}
while (count2 < 1)
{
System.out.println(Arrays.asList(userStrings));
count2++;
}
}
}
You are not putting the values in the String[]
Do it like this:
while (count < 10) {
System.out.println("Please enter a string value ");
Scanner input = new Scanner(System.in);
String userInput = input.next();
userStrings[count] = userInput;
count++;
}
Also, declare Scanner input = new Scanner(System.in) outside your while() {...}
See below code snippet may solve your problem.
package com.suresh;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class HomeWork10 {
public static void main(String[] args) {
String[] userStrings = new String[10];
int count = 0;
System.out.println("\t Reading Array Elements ");
while (count < 10) {
System.out.print("\t Please enter a string value : ");
Scanner input = new Scanner(System.in);
userStrings[count] = input.next();
count++;
}
System.out.println("\t PRINTING ORIGINAL ARRAY OF ELEMENTS ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
Collections.sort(Arrays.asList(userStrings), new StringAscComparator());
System.out.println("\t ASCENDING ORDER ");
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
System.out.println("\t DESCENDING ORDER ");
Collections.sort(Arrays.asList(userStrings), new StringDescComparator());
count = 0;
while (count < userStrings.length) {
System.out.println("\t " + userStrings[count]);
count++;
}
}
static class StringAscComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
static class StringDescComparator implements Comparator<String> {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
}
You created the array with 'String[] userStrings = new String[10];' and inside your while loop to access it you need to do something like this 'userStrings[0] = input.next()' This says the first item in the array userStrings will be set to input.next(). I'm not great at java so I'm not sure what input.next() will do though.

Reading multiple strings in java

I have to read strings from the user based on a number n and store n strings in n different variables. I'm stuck with how to put them into different strings. Please help me out.
This is my code:
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
for (int i=0; i<=b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}
So if b = 5, i have to input 5 strings from the user and store them in 5 different string variables. I'm able to take it from the user but not able to assign them into different variables. Can u please help me out?
Thanks.
If you know exactly the number of input then use an Array, if not use a ArrayList
With Arrays
String []inpupts = new String[b];
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs[i] = in.nextLine();
}
With ArrayList
List<String> inpupts = new ArrayList<String>();
for (int i=0; i< b; i++) {
System.out.println("Enter a string: ");
inputs.add(in.nextLine());
}
From your code (<= b) I am assuming you just started learning Java. Therefore, I edited your solution and am proposing the following, if this is okay?
public static void main(String[] args) {
int b;
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
//necessary to do due to Enter key pressed by user
in.nextLine();
String s[] = new String[b];
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s[i] = in.nextLine();
// You can check at the same time if this is what you entered
System.out.println("I have received this sring: "+s[i]+"\n");
}
Create an array and store it in an array like below:
String s[] = new String[b];//use b+1 if you need b+1 entries
for (int i=0; i<b; i++) {//use <=b is you need b+1 entries
System.out.println("Enter a string: ");
s[i] = in.nextLine();
}
You can then access your values as:
for (int i=0; i<b; i++) //use <=b is you need b+1 entries
System.out.println("Entered string was : " + s[i]);
}
Solution :
You can use something like this.
You can change your code as :
public static void main(String[] args) {
int b;
String s="";
Scanner in = new Scanner(System.in);
System.out.println("Enter verifying number: ");
b = in.nextInt();
in.nextLine(); // To get a new line
for (int i=0; i<b; i++) {
System.out.println("Enter a string: ");
s = in.nextLine();
}

Categories