java - 解决了无论如何要在不创建另一个扫描仪的方法中执行此操作吗?

标签 java

我刚刚开始学习如何编写程序。我听说在一个文件中创建多个扫描仪是一个坏习惯。如何更改此代码,以便不必将扫描仪放入“添加”方法中?

import java.util.Scanner;

public class Note1014{
    public static void main (String[]args){

    Scanner scn = new Scanner(System.in);   
    int choice = 0;
    do{
        System.out.println("Please select from the following options:");
        System.out.println("1. Compare two values");
        System.out.println("2. Add a list of values");
        System.out.println("3. Create a shopping list");
        choice = scn.nextInt();

        if(choice == 2){
            adding(1);
        }

    }while(choice <4);  
    }

    public static void adding (int enter){
    Scanner scn = new Scanner(System.in);
    int price =0;
    int i = 0;
    while(i==0){
    System.out.println("enter price, press -1 when done");
    enter = scn.nextInt(); 
    price += enter;

    if(enter == -1){
        System.out.println("Your total is " + price);
        break;
    }
    }
    }
}

谢谢!

最佳答案

像这样

import java.util.Scanner;

public class Note1014 {
static Scanner scn = new Scanner(System.in);
    public static void main(String[] args) {


        int choice = 0;
        do {
            System.out.println("Please select from the following options:");
            System.out.println("1. Compare two values");
            System.out.println("2. Add a list of values");
            System.out.println("3. Create a shopping list");
            choice = scn.nextInt();

            if (choice == 2) {
                adding(1);
            }

        } while (choice < 4);

    }

    public static void adding(int enter) {

        int price = 0;
        int i = 0;
        while (i == 0) {
            System.out.println("enter price, press -1 when done");
            enter = scn.nextInt();
            price += enter;

            if (enter == -1) {
                System.out.println("Your total is " + price);
                break;
            }
        }
    }
}

还有一个小问题 应该是

if(enter !=-1)
price += enter;

关于java - 解决了无论如何要在不创建另一个扫描仪的方法中执行此操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58386134/

相关文章:

java - ThreadPoolExecutor 的 maximumPoolSize 是如何工作的?

java - 如何在 java 中替换字符串中的 '|' 字符?

java - 修改 double 中的最低有效位(Java 和 C++)

java - 尝试加载 url

Java 鼠标事件未在 OSX 上注册

java - Gmail 应用程序如何获取有关新电子邮件的信息?

java - AES Java加密后exe文件未释放

java - JAX-RS json (java.util.Date) 序列化的不同行为

java:如何获得我的带宽

java - 对于 Java EE 6 使用 ControllerServlet 是一个好的实践吗?