Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I want to input date and months with java. If my input was incorrect, the program will ask the user to input again. Example, If I input 32th April, the program will say "Invalid" and ask the user to input with correct date. This is what I made, but can't Looping. Thx.

What I have tried:

Java
import java.util.*;
public class tanggal
{
 public static void main(String [] args)
 {
  Scanner scan=new Scanner(System.in);
  int tanggal=0;
  String bulan="";
   System.out.print("Tanggal:");
   tanggal=scan.nextInt();scan.nextLine();
   System.out.print("Bulan:");
   bulan=scan.nextLine();
   if(bulan.equals("Feb")&&tanggal>28)
   {
    System.out.println("Input invalid");
    tanggal=0;
   }
   else if(bulan.equals("Jan")&&bulan.equals("Maret")&&bulan.equals("Mey")&&bulan.equals("Juli")&&bulan.equals("Agustus")&&bulan.equals("Oktober")&&bulan.equals("Desember")||tanggal>31)
   {
    System.out.println("Input invalid");
    tanggal=0;
   }
   else if(bulan.equals("April")&&bulan.equals("Juni")&&bulan.equals("September")&&bulan.equals("November")||tanggal>30)
   {
    System.out.println("Input invalid");
    tanggal=0;
   }
   else
   {
    System.out.println("Input invalid");
    tanggal=0;
   }
 }
}
Posted
Updated 31-Oct-18 19:49pm
v2
Comments
Bryian Tan 31-Oct-18 23:11pm    
When will the input be valid?

1 solution

Just wrap the required portion in a loop and use a variable to control looping:
Java
bool valid = false;
while (!valid) {
   valid = true;
   //Do your stuff here and set 'valid' to false when it becomes invalid,
   //probably starting with your "String bulan="";" line
   //...
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900