Reputation: 7
I just started learning how to write programs. I heard it is a bad habit to create multiple scanners in one file. How do I change this code so that I don't have to put a scanner inside the "adding" method?
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;
}
}
}
}
Thanks!
Upvotes: 0
Views: 147
Reputation: 900
like this
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;
}
}
}
}
also you have a small problem it should be
if(enter !=-1)
price += enter;
Upvotes: 1
Reputation: 1
You can create the object outside the main method but inside the class and then use the same scn object inside the class as many times you want.
Upvotes: 0