I write 2 ArrayList type String contains the days and possible times , and I want the user to enter input , then check if the input is not from the array it will show a message that the input is invalid and the user enter again . but the result to my code give me the opposite :( when I enter something outside the array it will accept it
what's wrong with my code??
and please show me the right code :(
package javaapplication19;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> dayArray = new ArrayList<>();
ArrayList<String> timeArray = new ArrayList<>();
dayArray.add("sunday");
dayArray.add("monday");
dayArray.add("tuesday");
dayArray.add("wednesday");
dayArray.add("thursday");
timeArray.add("8am");
timeArray.add("9am");
timeArray.add("10am");
timeArray.add("11am");
timeArray.add("12pm");
timeArray.add("1pm");
timeArray.add("2pm");
timeArray.add("3pm");
timeArray.add("4pm");
System.out.println("please enter day :");
String a1 = input.nextLine();
for (int g = 0; g < dayArray.size(); g++){
if (dayArray.get(g).equals(a1))
System.out.println("invalid day , please enter another day : ");
a1 = input.nextLine();
}
System.out.println("please enter time : ");
String a2 = input.nextLine();
for (int s = 0; s < timeArray.size(); s++) {
if (timeArray.get(s).equals(a2))
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
}
}
You can use below code and find change in if condition.
System.out.println("please enter time : ");
String a2 = input.nextLine();
for (int s = 0; s < timeArray.size(); s++) {
if (!timeArray.get(s).equals(a2))
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
You can do it like this :
String a1 = input.nextLine();
if (!dayArray.contains(a1))
System.out.println("invalid day , please enter another day : ");
else {
System.out.println("day really nice day");
}
There is no need to iterate over the array. The method contains() does it for you
your code should be like this.
System.out.println("please enter day :");
boolean validDate = false;
while(!validDate){
String a1 = input.nextLine();
if(dayArray.contains(a1)){
System.out.println("invalid day , please enter another day : ");
}else{
validDate=true;
}
}
boolean validHour = false;
System.out.println("please enter a time : ");
while(!validHour){
String a2 = input.nextLine();
if(timeArray.contains(a2)){
System.out.println("invalid time , please enter another time : ");
}else{
validHour=true;
}
}
I did refactor your code and put some comments to easier to follow
Scanner input = new Scanner(System.in);
List<String> dayArray = Arrays.asList("sunday","monday","tuesday","wednesday","thursday");
List<String> timeArray = Arrays.asList("8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm");
String a1 = "";
String a2 = ""; //Store user input
boolean nextInput = false; // flag indicate we continue or we force user re-enter information
//try to read the day input
while (!nextInput) {
System.out.println("please enter day :");
a1 = input.nextLine();
nextInput = dayArray.contains(a1);
}
//try to read the time input
nextInput = false; //<= reset flag
while(!nextInput) {
System.out.println("please enter time : ");
a2 = input.nextLine();
nextInput = timeArray.contains(a2);
}
System.out.println("day :" + a1);
System.out.println("time :" + a2);
System.out.println("program finished");
input.close(); //close scanner
write like this
System.out.println("please enter day :");
String a1 = input.nextLine();
while (!dayArray.contains(a1)){
System.out.println("invalid day , please enter another day : ");
a1 = input.nextLine();
}
System.out.println("please enter time : ");
String a2 = input.nextLine();
while (!timeArray.contains(a2)){
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
Related
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.
I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException
I'm trying to create a program computes and prints how many real solutions for the given equation.
the User enter the values for A,B and C.
And I want the program to exit if the user entered a value for A = 0 and not to continue asking for the others value.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a vlaue for A : ");
int coA = s.nextInt();
if (coA==0){
System.out.println("Error ! Enter a vlaue larger than 0 ");
};
System.out.println("Enter a vlaue for B : ");
int coB = s.nextInt();
System.out.println("Enter a vlaue for C : ");
int coC = s.nextInt();
double coTotal = (Math.pow(coB, 2))-4*coA*coC;
if(coTotal>0){
System.out.println(" The System has two solutions ");
}
if (coTotal==0){
System.out.println(" The System has one solutions ");
}
if(coTotal<0){
System.out.println(" The System has ZERO solutions ");
}
}
If this code is in main you can use System.exit, like this. I used -1 to indicate there was an issue with the input. You could use a different error code:
Scanner s = new Scanner(System.in);
System.out.println("Enter a vlaue for A : ");
int coA = s.nextInt();
if (coA==0){
System.out.println("Error ! Enter a vlaue larger than 0 ");
System.exit(-1);
};
System.out.println("Enter a vlaue for B : ");
int coB = s.nextInt();
System.out.println("Enter a vlaue for C : ");
int coC = s.nextInt();
double coTotal = (Math.pow(coB, 2))-4*coA*coC;
if(coTotal>0){
System.out.println(" The System has two solutions ");
}
if (coTotal==0){
System.out.println(" The System has one solutions ");
}
if(coTotal<0){
System.out.println(" The System has ZERO solutions ");
}
I'm making a program where a user enters how many inputs the user wants. Example if the user enter's 3, then 3 user inputs will appear. The output of this program goes something like this:
----------------------------------
Enter How Many Inputs: 3
enter name:
rendell //value to be outputted
enter age:
20 //value to be outputted
enter gender:
male //value to be outputted
-----------------------------------
Now, I want to store those entered values somewhere to be outputted separately after but I have no idea how to do it. I tried to use the ctr1 variable but it only outputs the value of the last user input.
Here is my code:
Object stud1 [][] = {{1,2,3},{"enter name:","enter age:","enter gender:"}};
String ctr1;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(in.readLine());
for (int i = 0; i<num1;i++){
System.out.println(pers[1][i]);
ctr1 = in.readLine();
}
The problem is that you are only assigning all the input in one reference to the String thus you can print all the input the user just gave.
solution:
You can use an array of String to put all the values from the inputted data if the user
sample:
String [] choices = { "enter name:","enter age:","enter gender:"};
String ctr1[];
Scanner scan = new Scanner(System.in);
System.out.print("Enter How Many Inputs: ");
int num1 = Integer.parseInt(scan.nextLine());
ctr1 = new String[num1];
for (int i = 0; i < num1; i++) {
System.out.println(choices[i]);
ctr1[i] = scan.nextLine();
}
for(int i = 0; i < ctr1.length; i++)
{
if(i == 0)
System.out.println("Name: "+ ctr1[i]);
else if( i == 1)
System.out.println("Age: "+ ctr1[i]);
else if( i == 2)
System.out.println("Gender: "+ ctr1[i]);
}
result:
Enter How Many Inputs: 3
enter name:
Rod_algonquin
enter age:
12
enter gender:
male
Name: Rod_algonquin
Age: 12
Gender: male
I am writing an appointment program in Java and am coming across an error which is
Exception in thread "main" java.lang.NumberFormatException: For input string : ""
for the following lines :
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at AppointmentNew.main(AppointmentNew.java:24)
The program is going through once, but once it gets to the end of its first run it gives me those errors.... For instance when I run the program as follows : I make the choice of "1" to make a new appointment, I then enter the date of my new appointment "mm/dd/yyyy", then I add an appointment description, and lastly I enter the type "Once, Daily, or Monthly". After that finishes it should start back over with the very first line of "Make Choice (1: New, 2: Print Range, 3: Print All, quit):" But instead it gives me the errors I described above...
Here is my code I have.
import java.util.*;
public class AppointmentNew
{
public static void main (String[] args)
{
ArrayList<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
String choice = "";
int choiceNum = 0;
String date = "";
String descrip = "";
int type = 0;
String typeChose = "";
System.out.println("Welcome to Appointment App!\n");
System.out.println("\t============================\n");
do
{
System.out.print("\tMake Choice ( 1: New, 2: Print Range, 3: Print All, quit): ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
if (choiceNum == 1)
{
System.out.print("\n\n\tEnter New Appointment Date in mm/dd/yyyy format: ");
date = stdin.nextLine();
System.out.print("\n\n\tEnter New Appointment Description: ");
descrip = stdin.nextLine();
System.out.print("\n\n\tEnter Type (1 = Once, 2 = Daily, 3 = Monthly): ");
type = stdin.nextInt();
if (type == 1)
{
Once once = new Once(date, descrip);
typeChose = "One-Time";
}
else if (type == 2)
{
Daily daily = new Daily(date, descrip);
typeChose = "Daily";
}
else
{
Monthly monthly = new Monthly(date, descrip);
typeChose = "Monthly";
}
String stringToAdd = "";
stringToAdd = ("\n\n\tNew " + typeChose + " Appointment Added for " + date + "\n");
list.add(stringToAdd);
System.out.println(stringToAdd);
System.out.println("\t============================\n");
}
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
String lowDate = stdin.nextLine();
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
String highDate = stdin.nextLine();
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
if (list.get(i).compareTo(lowDate) <= 0 && list.get(i).compareTo(highDate) >= 0)
{
System.out.println(list.get(i));
}}
}
if (choiceNum == 3)
{
for(int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
}
}while (choice != "quit");
}
}
Any help would be great!
You need to add another call to nextLine() after this statement here:
type = stdin.nextInt();
// ED: stdin.nextLine();
This is because, when you grab an int from the Scanner, it doesn't consume the '\n' character that gets put on the input stream when the user hits enter.
Thus, when stdin.nextLine() is called again, the String "" is returned (everything not yet processed up to the next '\n' character), and Integer.parseInt doesn't know how to handle that, so you get an error.
Surround the code with an if statement to check if the value is not quit before trying to Parse it.