I've got a strange issue (or at least strange to me). I've got a couple if-else-if statements that are causing strange behavior. For context, I'm essentially taking a char input using the Scanner class and using Scanner.nextInt().charAt(0). This appears to work fine if I check for the required characters and input a totally random character (it returns text to the terminal, breaks out, and exits). However, if I just hit enter at the char prompt, it creates what appears to be an infinite loop (maybe a memory leak?). Attached is the code I'm working on, as well as screenshots of it running in Coderunner2.
Thanks in advance!
import java.util.*;
import java.io.*;
public class phonebill
{
public static void main(String[] arg)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please input the account number: ");
int acct = sc.nextInt(); // reads arbitrary account number
System.out.print("Please input service code: ");
char svc_code = sc.next().charAt(0); // reads service code
character
/* the following blocks check for the appropriate service codes.
* valid codes include p or P for 'Premium' service, and
* r or R for regular service. if no valid code is read,
* the program exits, informing the user to input a valid code.
*/
if (svc_code == 'p' || svc_code == 'P')
{
System.out.print("Please input daytime minutes: ");
int day_min = sc.nextInt();
System.out.print("Please input nighttime minutes: ");
int night_min = sc.nextInt();
System.out.println("Service code is " + svc_code + " and this condition works.");
}
else if (svc_code == 'r' || svc_code == 'R')
{
System.out.print("Please input used minutes: ");
int mins = sc.nextInt();
System.out.println("Service code is " + svc_code + " and this condition works.");
}
else
{
System.out.println("Please input a valid service code.");
}
System.out.print("That's all for now folks");
}
}
Aucun commentaire:
Enregistrer un commentaire