removing null values for an array - java

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.

Related

Java While loop condition isn't being exicuted

I'm working on a project for school but I can't figure out why my code isn't exiting when I type "zzz". it's probably simple and I'll likely feel dumb when I know what the problem is. here's my code:
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[0] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (input.equals("zzz")){
System.out.println("bleh");
}
counter++;
} while (!input.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
Replace
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
}
counter++;
with
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
and
while (!input.equals("zzz") && counter <= 14)
with
while (!arr[counter].equals("zzz") && counter <= 14)
Explanation: zzz is a string which you have to compare with the input string stored in arr[counter].
Also, in order to avoid NullPointerException, you should perform sort operation on the copy of the array without any null element. Given below is the complete program:
import java.util.Arrays;
import java.util.Scanner;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
do {
System.out.print("Enter item or type 'zzz' to quit: ");
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")) {
System.out.println("bleh");
} else {
counter++;
}
} while (!"zzz".equals(arr[counter]) && counter <= 14);
arr = Arrays.copyOf(arr, counter);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
A sample run:
Enter item or type 'zzz' to quit: a
Enter item or type 'zzz' to quit: b
Enter item or type 'zzz' to quit: c
Enter item or type 'zzz' to quit: zzz
bleh
Array is [a, b, c]
import java.util.*;
public class StringSort2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
arr[counter] = input.nextLine();
counter++;
do{
arr[counter] = input.nextLine();
if (arr[counter].equals("zzz")){System.out.println("bleh");}
counter++;
}while (!arr[counter].equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
You meant to compare the input String, not the Scanner object. I also removed your magic number "0" index that you had , since you already set your counter to 0.
The reason your code isn't working is that input is the scanner object, and the equals method on the scanner object doesn't refer to the data being read by it. A way of doing this so that it works would be:
import java.util.*;
public class Help {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
String[] arr = new String[15];
String inputString = null;
System.out.println("Enter item or type 'zzz' to quit");
do{
inputString = input.nextLine();
arr[counter] = inputString;
if (inputString.equals("zzz")){System.out.println("bleh");}
counter++;
}while (!inputString.equals("zzz") && counter <= 14);
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));
}
}
input is a Scanner. It will never equal a String.
Try this
Scanner sc = new Scanner(System.in);
String input; // this is now a proper string to compare
String[] arr = new String[15];
System.out.println("Enter item or type 'zzz' to quit");
input = sc.nextLine();
int counter = 0;
while (counter < arr.length) {
if (input.equals("zzz")) return; // check most recently entered input
arr[counter++] = input; // if not returned, store in the list and increase counter
input = sc.nextLine(); // prompt next line
}
Arrays.sort(arr);
System.out.println("Array is " + Arrays.toString(arr));

How to iterate through array just if the userinput is chronological in Java

I need a little bit of help please, I have the following code:
Scanner s = new Scanner(System.in);
String userinput= s.nextLine();
String[] books = new String[10];
books[0] = "book1”;
books[1] = "book2";
if (Arrays.asList(userinput).contains(books[0])) {
System.out.println("right, what is the next book?");
}
else {
System.out.println("false");
}
My goal is to iterate through the array and ask the user the next input, so if he writes “book1” I would like to automatically ask “what is the next book?” and I would wait for his answer to be “book2” and so on with book3,4,5.... in chronologic order. If he writes "book5" when I expect "book2", everything starts again until he gets it right, in chronological order
Try this for 3 books.
String[] books = new String[3];
books[0] = "book1";
books[1] = "book2";
books[2] = "book3";
boolean flag = true;
while(flag){ //outer loop
int counter = 0; //check for total right answers
for(int i=0;i<books.length;i++){ //iterate over all books
System.out.print("Choose book " + (i+1) +" name: ");
String userinput= s.nextLine();
if (Arrays.asList(userinput).contains(books[i])) {
counter++;
System.out.println("right, what is the next book?");
if(counter == books.length){ //in case all choices are correct
flag = false;
}
} else {
System.out.println("Wrong");
break;//terminate inner loop
}
}
}
The easiest way is to ensure that the books are entered in logical order in an array or list. Then just compare userInput to the next entry.
int nbooks = 5; // number of books to generate
Scanner s = new Scanner(System.in);
// create some books
String[] books = IntStream.rangeClosed(1,nbooks)
.mapToObj(i->"book"+i).toArray(String[]::new);
int i = 0;
String currentBook = books[i++];
while (i < books.length) {
System.out.println("The current book is " + currentBook);
System.out.print("What is the next book? ");
String userInput= s.next();
if (userInput.equals(books[i++])) {
if (i != books.length) {
// don't prompt at last book
System.out.println("right, what is the next book?");
}
continue;
}
// reset everything.
System.out.println("False");
i = 1;
currentBook = books[0];
}
System.out.println("Congratulations! You got them all.");

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

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