Cannot Store Data into ArrayLists? - java

thanks for all the help guys but now the nature of the question has changed using Patrick's suggestion below loop is running but it dise not seem to be storing the input to respective arrays data keeps hetting replaced into the ArrayLists rather than going to the next position into the ArrayList any suggestions?
import java.util.ArrayList;
import java.util.Scanner;
public class Arrray {
public static void main(String [] args){
ArrayList<String> names;
ArrayList<String> addr;
do {
names = new ArrayList<String>();
addr = new ArrayList<String>();
Scanner userInput = new Scanner(System.in);
System.out.println("Name and Adreess are: " + names.size() + "**"
+ addr.size());
System.out.println("please Enter Your Name :");
names.add(userInput.next());
System.out.println("please enter your Address :");
addr.add(userInput.next());
System.out.println("Do you want to add another entry? :(y/n)" );
String ans =userInput.next(); // get the value from the user using scanner class
if(ans.equals("n") || ans.equals("N"))
break;
} while (true);
int n = names.size();
int a = addr.size();
for(int i =0; i<n && i<a; i++ )
System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i));
}
}

Use a while(true) in conjunction with a break statement:
do {
if(input.next() == 'n'){
break;
}
} while(true);

get value from the user and if user enter n then break otherwise nothing
System.out.println("Do you want to add another entry? :(y/n)" );
String ans = .... // get the value from the user using scanner class
if(ans.equalsIgnoreCase("n"))
break;

Try to capture this user's input
System.out.println("Do you want to add another entry? :(y/n)");
and use that info in the while.

You have to do something like this:
String choice = "";
do {
.
.
.
.
System.out.println("Do you want to add another entry? :(y/n)" );
choice = userInput.next();
} while (!(choice.equals("n") || choice.equals("N")));
The line
choice = userInput.next();
will read user input, and the String classes equals method for comparing the input. The loop will continue until the choice is either N or n.

import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> phone = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Please enter your name: ");
name.add(scanner.next());
System.out.println("Please enter your number: ");
phone.add(scanner.nextInt());
System.out.println("Do you want to add a directory y/n?");
answer = scanner.next();
} while (answer.equals("y") || answer.equals("Y"));
if (answer.equals("y") || answer.equals("Y")); //want it to go back to start another direcotry here
else {
System.out.println("Thanks for adding to the directory");
for (int i = 0; i < name.size(); i++) {
System.out.print(name.get(i) + "\t");
System.out.print(phone.get(i));
System.out.println("");
}
}
}
}

Related

Check if characters in a firstname String contain at least 1 digit

I try to check if characters in a firstname String contain at least 1 digit, if yes ask to the user to input it again and then going back to the loop and check again but with a GoTo break it only works the first time and won't loop it again. Oh and I do this from a method with a String array of more than only a first name in it. Isn't the break GoTo supposed to bring me back to my label and then do the loop over again looking for a digit?
public static void main(String[] args) {
infoInputGathering();
}
public static String[] infoInputGathering(){
String[] infos = new String[3]; // Declaration of the infos String array
boolean isStringOnly;
char[] characterChecker;
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
// Asking the user to input their first name and stores it in a String Array info[0]
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
firstname:
for (int c = 0 ; c<=characterChecker.length ; ++c ) {
if (Character.isDigit(characterChecker[c])) {
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
Break firstname;
}
}
Final Full Code I came up with with Ali's help on this part
import java.util.Scanner;
import java.util.ArrayList;
public class InfiniteInfoGatheringUntilStop {
public static void main(String[] args) {
int iterationsCounter = 0; // Declares/Initiate a counter for the loops
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
ArrayList<String> names = new ArrayList<String>(); // Creates an ArrayList for the names inputs
ArrayList<String> birth = new ArrayList<String>(); // Creates an ArrayList for the date of birth inputs
ArrayList<String> gpa = new ArrayList<String>(); // Creates an ArrayList for the GPA inputs
while(true){ // Always true loop unless break out on if conditions
System.out.print("Enter your name: ");
names.add(input.next());
//Code to check if there are numerical character in the String of the listArray inputted
char[] characterChecker = names.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
int c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as numerical
if(Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
names.set(iterationsCounter,input.next());
characterChecker = names.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){
break;
}
}
if(names.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
break;
}
System.out.print("Enter your date of birth in this format AAAAmmdd: ");
birth.add(input.next());
characterChecker = birth.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 8){ // Checks for a maximum length of 8 characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checkes if there are letters in the characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(birth.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
break;
}
System.out.print("Enter your GPA in 0.0 format: ");
gpa.add(input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 3){ // Checkes for a maximum length of 8 characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA please: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checks if there are digits in the characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(gpa.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
gpa.remove(iterationsCounter);
break;
}
iterationsCounter++; // Incrementes the counter if a full loop is done
}
// Prints the results
System.out.println("Number of valid inputs before you got exhausted: " + iterationsCounter);
System.out.println("====================================================================================");
//A loop to print the content of the 3 ListArrays
for(int arrayLoc = 0; arrayLoc < iterationsCounter; arrayLoc++){
System.out.println((arrayLoc+1) + "-\t" + names.get(arrayLoc) +
"\t\t" + birth.get(arrayLoc) +
"\t\t" + gpa.get(arrayLoc));
}
}
}
You can write your code with while loop like this:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] infos = new String[3];
char[] characterChecker;
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
int c = 0;
while(true){
if (Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
c = 0;
}
else
c++;
if(c == characterChecker.length)
break;
}
System.out.println("Correct Name");
}
}
If c is equal to characterChecker.length, ie in the name, there is no number, then it is correct and we break loop and print Correct Name.

How to get the user to input data until they enter quit then the system displays all the inputted data

Does anybody know why there in an error with this piece of code?
for ( int i=0; i<99; i++)
{
Scanner scan = new Scanner(System.in);
System.out.print ("Please Enter Game Name: Achievement Score: Minutes Played ");
Input1=scan.nextLine();
if (Input1.compareTo("quit"))
break;
compareTo() is used to compare numbers.
To compare text, you want to use equals().
e.g.
if (Input1.equals("quit"))
Use .equals() to compare the two strings. If you would like to compare the two strings regardless of the case you could use .equalsIgnoreCase(). The code below will take in values and store them in an ArrayList, when the user types quit the results that are stored in the ArrayList are presented to the user.
Scanner scan = new Scanner(System.in);
String input;
ArrayList<String> inputValues = new ArrayList<String>();
for (int i = 0; i < 99; i++) {
System.out.print("Please Enter Game Name... ");
input = scan.nextLine();
if(input.equals("quit")) {
if(inputValues.size() == 0) {
System.out.println("\nNo values have been entered");
} else {
System.out.println("\n******* Inputted Data *******");
for (String anInputText : inputValues) {
System.out.println("Game Name " + anInputText);
}
}
break;
} else {
inputValues.add(input);
}
}
}

allow only chars as user input and assign them to variables?

I have this task where I have to handle some user input. The user should only be able to enter a,b,c,d,e,f,g,h,i,j,k,l and after the user input I want to assign a,b,c..l to variables 0,1,2,3,4..,11. Every other input, except for capital letters should give an error - but how can I do this?
I got as far as this:
int number;
public String playerInput;
public void start()
{
Scanner scn = new Scanner( System.in );
System.out.println("please enter input:");
playerInput = scn.nextLine();
System.out.println("scn.nextLine() = " +playerInput);
}
I really don't know how I would be able to just store mentioned letters and assign them to variables, can someone help?
Since it unclear what you meant by Assiging it to variable from number.
so here i'm giving you idea how to just input char between a-l and then you can do the things with you input
public class CharInput {
public static void main(String... str) throws IOException {
// open Scanner for input
Scanner keyboard = new Scanner(System.in);
System.out.println("Input");
//since you want only lowercase as input so converting at front is an better option
String playerInput = keyboard.next().toLowerCase();
// to make sure we have only char input nothing else
char input = playerInput.charAt(0);
// Check if the inputted char is between a and l only
if (input >= 'a' && input <='l' ){
// Do the stuff you want to do if the input is in between
// with the char variable input
}
else{
System.out.println("Error Raised");
}
}
}
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Prog {
int[] array = new int[12];
Set<String> list = new HashSet<String>();
String alphabet = "a,b,c,d,e,f,g,h,i,j,k,l,A,B,C,D,E,F,G,H,I,J,K,L";
int count = 0 ;
public String playerInput;
public void start() throws Exception
{
String[] val = alphabet.split(",");
while(count<24){
list.add(val[count]);
count++;
}
Scanner scn = new Scanner( System.in );
while(count < 12){
System.out.println("please enter input:");
playerInput = scn.nextLine();
System.out.println("scn.nextLine() = " + playerInput);
if(list.contains(playerInput)){
//assign your desired value to that letter
}
else{
//throw exception here ;
}
}
}
}
I didnt understand your problem clearly but i guess may be you want to do something like this(not sure though) -
Scanner scn = new Scanner( System.in );
System.out.println("please enter input:");
playerInput = scn.nextLine();
int i=0;
Map<String,Integer> map=new TreeMap<String,Integer>();
Set<String> set= new TreeSet<String>();
while(playerInput.matches("[a-lA-L]")){
set.add(playerInput.toLowerCase());
playerInput=scn.nextLine();
if(!playerInput.matches("[a-lA-L]")){
System.out.println("Error!!! Wrong Input");
break;
}
}
for(String s:set){
map.put(s, i);
i++;
}
System.out.println(map);

Need help making loop work [duplicate]

This question already has answers here:
Breaks from loop
(3 answers)
Closed 8 years ago.
I have looped my code so it keeps repeating until a "yes" or a "no" is given when being asked "Continue?". But my code breaks from the loop after entering a random value and then yes.
for example:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
It should say:
Add or delete another name? Add
Please enter a name you want to add: Matt
Continue? f
Continue? yes
Add or delete another name?
actual code
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AddOrDeleteNames {
public static void main(String[] args) throws Exception {
ArrayList<String> names = new ArrayList<String>();
Scanner scan = new Scanner(new File("names.txt"));
Scanner myScan = new Scanner(System.in);
Scanner scanRedo = new Scanner(System.in);
String userRedo;
String userResponse;
while (scan.hasNext())
names.add(scan.next());
do {
System.out.print("Add or delete another name? ");
userResponse = myScan.next();
if (userResponse.equalsIgnoreCase("add")) {
System.out.print("Please enter a name you want to add: ");
names.add(myScan.next());
} else if (userResponse.equalsIgnoreCase("delete")) {
System.out.print("Please enter a name you want to delete: ");
names.remove(myScan.next());
} else {
System.out.print("Invalid Choice");
}
PrintWriter writer = new PrintWriter("namesupdated.txt");
for (int i = 0; i < names.size(); i++)
writer.println(names.get(i));
writer.close();
System.out.print("Continue? ");
userRedo = scanRedo.next();
} while (userRedo.equalsIgnoreCase("yes"));
do { // THIS LOOP IS HERE BECAUSE IF THE USER ENTERS A VALUE OTHER THAN CONTINUE, YES OR NO, THE QUESTION REPEATS
if(userRedo.equalsIgnoreCase("no")) {
System.out.print("Thank You.");
userRedo = scanRedo.next();
} else if (!userRedo.equalsIgnoreCase("yes")) {
System.out.print("Continue? "); // LOOP ENDS EARLY HERE
userRedo = scanRedo.next();
}
} while (!userRedo.equalsIgnoreCase("yes")); // NOT SURE HOW TO RESTART PREVIOUS LOOP
scan.close();
myScan.close();
scanRedo.close();
}
}
The way you do this is always with a while loop with some sort of changable condition:
Scanner scan = new Scanner(System.in);
boolean stop = false;
while(!stop) {
//do whatever
...
System.out.println("Continue? Yes or No");
String s = Scan.nextLine();
if(s.equals("No")) {
stop = true;
}
}

My program won't stop when I enter "done"

I asked a question earlier and since then i've edited my code a bit but now my code won't stop when i reads in done it does not stop.
public class Done {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
ArrayList<String> sal = new ArrayList<String>();
int count = 0;
while (true){
sal.add(kb.next());
if (sal.equals("done"))
break;
count++;
}
display(sal);
displayb(sal);
}
public static void display(ArrayList<String> sal){
for (int i=0; i<sal.size(); i++)
System.out.print(sal.get(i)+ " ");
System.out.println();
}
public static void displayb(ArrayList<String> sal){
for (int z = sal.size(); z >= 1; z--)
System.out.print(sal.get(z-1) + " ");
System.out.println();
}
}
My code won't stop when I enter the phrase "done." Anyone know what I might be doing wrong?
You're checking if the ArrayList sal is equal to the string "done" -- this will never be true. Perhaps you want to check if the latest input is equal to that string:
while (true)
{
String input = kb.next();
if (input.equals("done"))
break;
sal.add(input);
count++;
}
kb.next() is the string you want to compare. You'll need to save that in a variable:
String inputString = kb.next();
if (inputString.equals("done"))
break;
sal.add(inputString);
That will also solve the problem of not adding "done" to the array.

Categories