User validation input under forloop - java

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

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

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.

Searching String trouble in single array for java

I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.

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

Scanning different types of variables in one line

As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}

Categories

Resources