如何让用户能够无限地使用Scanner功能通过键盘输入内容?

huangapple go评论75阅读模式
英文:

How can I allow the user to be able to input something by typing in the keyboard infinitely using the Scanner feature?

问题

import java.util.Scanner;
import java.lang.String;

public class TicketMachine
{
    
    private int price;
    
    private int balance;
    
    private int total;
    /**
     * Create a machine that issues tickets of the given price.
     */
    public TicketMachine(int cost)
    {
        price = cost;
        balance = 0;
        total = 0;
    }

    /**
     * @Return The price of a ticket.
     */
    public int getPrice()
    {
        return price;
    }

    /**
     * Return The amount of money already inserted for the
     * next ticket.
     */
    public int getBalance()
    {
        return balance;
    }

    /**
     * Receive an amount of money from a customer.
     * Check that the amount is sensible.
     */
    public void insertMoney(int amount)
    {
        if(amount > 0) {
            balance = balance + amount;
        }
        else {
            System.out.println("Use a positive amount rather than: " +
                amount);
        }
    }

    /**
     * Print a ticket if enough money has been inserted, and
     * reduce the current balance by the ticket price. Print
     * an error message if more money is required.
     */
    public void printTicket()
    {
        if(balance >= price) {
            // Simulate the printing of a ticket.
            System.out.println("HERE IS YOUR TICKET");

            System.out.println("# Ticket");
            System.out.println("# " + price + " cents.");
            System.out.println("You have " + balance + " left");

            // Update the total collected with the price.
            total = total + price;
            // Reduce the balance by the price.
            balance = balance - price;
        }
        else {
            System.out.println("You must insert at least: " +
                (price - balance) + " more cents.");

        }
    }

    /**
     * Return the money in the balance.
     * The balance is cleared.
     */
    public int refundBalance()
    {
        int amountToRefund;
        amountToRefund = balance;
        balance = 0;
        return amountToRefund;
    }

    public static void main(String [] args)
    {


        Scanner myScanner = new Scanner(System.in);
        String answer;

        while (true) {
            answer = myScanner.nextLine();

            if( answer.equals("London") )
            {
                System.out.println("£15");
            }
            if( answer.equals("Manchester") )
            {
                System.out.println("£20");
            }

            // Continue with other city checks...

            if (answer.equals("exit")) {
                break;
            }
        }
    }
}

This modified version of your code includes a while loop that allows the user to type cities continuously without having to close and reopen the terminal. It will keep prompting the user for input until they type "exit." Note that I've included comments for the "Continue with other city checks..." part, indicating where you should add the other city checks and their corresponding prices.

英文:

In my code, I was able to use the scanner feature to prompt the user to type a piece of text, however, I was only able to make it so the user can type once. To type again I would have to close the terminal, and open it again, how can I make it so that I can just type infinitely so that I wouldn't have to close it and reopen it every time in order to type again?
For context, this is my code, it is about a ticket machine which displays certain data, like the name of the person, the price, the total balance, etc. Currently I am doing the places. This means that I want the user to type any city in England, and a price would appear. But as I said, the user can only jarringly type one thing at a time, when they should be able to type without any limit.

import java.util.Scanner;
import java.lang.String;
public class TicketMachine
{
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost)
{
price = cost;
balance = 0;
total = 0;
}
/**
* @Return The price of a ticket.
*/
public int getPrice()
{
return price;
}
/**
* Return The amount of money already inserted for the
* next ticket.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
* Check that the amount is sensible.
*/
public void insertMoney(int amount)
{
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount rather than: " +
amount);
}
}
/**
* Print a ticket if enough money has been inserted, and
* reduce the current balance by the ticket price. Print
* an error message if more money is required.
*/
public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");
}
}
/**
* Return the money in the balance.
* The balance is cleared.
*/
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String [] args)
{
Scanner myScanner = new Scanner(System.in);
String answer = myScanner.nextLine();
if( answer.equals("London") )
{
System.out.println("£15");
}
if( answer.equals("Manchester") )
{
System.out.println("£20");
}
if( answer.equals("Brighton") )
{
System.out.println("£25");
}
if( answer.equals("Cornwall") )
{
System.out.println("£30");
}
if( answer.equals("Crystal Palace") )
{
System.out.println("£35");
}
if( answer.equals("Chealsea") )
{
System.out.println("£40");
}
if( answer.equals("Birmingham") )
{
System.out.println("£45");
}
if( answer.equals("Liverpool") )
{
System.out.println("£50");
}
if( answer.equals("Bristol") )
{
System.out.println("£55");
}
if( answer.equals("Leister") )
{
System.out.println("£60");
}
if( answer.equals("Newcastle") )
{
System.out.println("£65");
}
if( answer.equals("Cambridge") )
{
System.out.println("£70");
}
if( answer.equals("Bradford") )
{
System.out.println("£75");
}
if( answer.equals("Leeds") )
{
System.out.println("£80");
}
if( answer.equals("Oxford") )
{
System.out.println("£85");
}
if( answer.equals("Nottingham") )
{
System.out.println("£90");
}
if( answer.equals("Peterborough") )
{
System.out.println("£95");
}
if( answer.equals("Sheffield") )
{
System.out.println("£100");
}
}
}

答案1

得分: 1

使用while true或无限循环并不是一个好的实践。您可以使用do-while循环,并检查一个标志(例如"exit")来关闭程序,例如:

import java.util.Scanner;
import java.lang.String;

public class TicketMachine {

     private int price;

     private int balance;

     private int total;

     /**
      * Create a machine that issues tickets of the given price.
      */
     public TicketMachine(int cost) {
          price = cost;
          balance = 0;
          total = 0;
     }

     /**
      * @Return The price of a ticket.
      */
     public int getPrice() {
          return price;
     }

     /**
      * Return The amount of money already inserted for the next ticket.
      */
     public int getBalance() {
          return balance;
     }

     /**
      * Receive an amount of money from a customer. Check that the amount is sensible.
      */
     public void insertMoney(int amount) {
          if (amount > 0) {
               balance = balance + amount;
          } else {
               System.out.println("Use a positive amount rather than: " + amount);
          }
     }

     /**
      * Print a ticket if enough money has been inserted, and reduce the current balance by the
      * ticket price. Print an error message if more money is required.
      */
     public void printTicket() {
          if (balance >= price) {
               // Simulate the printing of a ticket.
               System.out.println("HERE IS YOUR TICKET");

               System.out.println("# Ticket");
               System.out.println("# " + price + " cents.");
               System.out.println("You have " + balance + " left");

               // Update the total collected with the price.
               total = total + price;
               // Reduce the balance by the price.
               balance = balance - price;
          } else {
               System.out.println("You must insert at least: " + (price - balance) + " more cents.");
          }
     }

     /**
      * Return the money in the balance. The balance is cleared.
      */
     public int refundBalance() {
          int amountToRefund;
          amountToRefund = balance;
          balance = 0;
          return amountToRefund;
     }

     public static void main(String[] args) {

          Scanner myScanner = new Scanner(System.in);

          String answer = "";

          do {

               System.out.println("Enter your city, please:");
               answer = myScanner.nextLine();

               if (answer.equals("London")) {
                    System.out.println("£15");
               }
               else if (answer.equals("Manchester")) {
                    System.out.println("£20");
               }
               // ... (other city cases)

               else if (answer.equals("exit")) {
                    break; // Exit the loop
               }
               else {
                    System.out.println("ERROR: INVALID INPUT");
               }

          } while (true); // Infinite loop

     }
}

请注意,以上代码已经将while true循环改为了do-while循环,并在用户输入"exit"时退出循环。另外,代码中的城市处理部分已经改为使用switch case结构,增强了代码的可读性和维护性。

英文:

Using a while true or a infinite loop isn't a good practice. You can use a do-while and check a flag (e.g. "exit") to close the program e.g.

import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* @Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
if (answer.equals("London")) {
System.out.println("£15");
}
else if (answer.equals("Manchester")) {
System.out.println("£20");
}
else if (answer.equals("Brighton")) {
System.out.println("£25");
}
else if (answer.equals("Cornwall")) {
System.out.println("£30");
}
else if (answer.equals("Crystal Palace")) {
System.out.println("£35");
}
else if (answer.equals("Chealsea")) {
System.out.println("£40");
}
else if (answer.equals("Birmingham")) {
System.out.println("£45");
}
else if (answer.equals("Liverpool")) {
System.out.println("£50");
}
else if (answer.equals("Bristol")) {
System.out.println("£55");
}
else if (answer.equals("Leister")) {
System.out.println("£60");
}
else if (answer.equals("Newcastle")) {
System.out.println("£65");
}
else if (answer.equals("Cambridge")) {
System.out.println("£70");
}
else if (answer.equals("Bradford")) {
System.out.println("£75");
}
else if (answer.equals("Leeds")) {
System.out.println("£80");
}
else if (answer.equals("Oxford")) {
System.out.println("£85");
}
else if (answer.equals("Nottingham")) {
System.out.println("£90");
}
else if (answer.equals("Peterborough")) {
System.out.println("£95");
}
else if (answer.equals("Sheffield")) {
System.out.println("£100");
}else { 
System.out.println("ERROR: INVALID INPUT");
}
} while (answer != "exit");
}
}

PS use a switch case instead of if(){} e.g

import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* @Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
switch (answer) {
case "London":
System.out.println("£15");
break;
case "Manchester":
System.out.println("£20");
break;
case "Brighton":
System.out.println("£25");
break;
case "Cornwall":
System.out.println("£30");
break;
case "Crystal Palace":
System.out.println("£35");
break;
case "Chealsea":
System.out.println("£40");
break;
case "Birmingham":
System.out.println("£45");
break;
case "Liverpool":
System.out.println("£50");
break;
case "Bristol":
System.out.println("£55");
break;
case "Leister":
System.out.println("£20");
break;
case "Newcastle":
System.out.println("£65");
break;
case "Cambridge":
System.out.println("£70");
break;
case "Bradford":
System.out.println("£75");
break;
case "Leeds":
System.out.println("£80");
break;
case "Oxford":
System.out.println("£85");
break;
case "Nottingham":
System.out.println("£90");
break;
case "Peterborough":
System.out.println("£95");
break;
case "Sheffield":
System.out.println("£100");
break;
default:
System.out.println("ERROR: INVALID INPUT");
break;
}
} while (answer != "exit");
}
}

huangapple
  • 本文由 发表于 2020年8月20日 03:29:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63493757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定