是否可以在方法中不创建其他扫描仪的情况下执行此操作? [已解决]

问题描述 投票:0回答:2

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

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;
    }
    }
    }
}

谢谢!

java
2个回答
0
投票

您可以在main方法之外但在类内部创建对象,然后根据需要在类内多次使用相同的scn对象。


0
投票

喜欢这样

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;
© www.soinside.com 2019 - 2024. All rights reserved.