how to get a scanner to read a pre-set variable - java

i am trying to use a scanner to get user input to add a new item to a stock list i have created, the item must possess the attributes itemID, itemDesc, price, quantity, and reorderlevel.
How would i go about reading the user input, and recognising it as one of those variables i've created, and then adding it to my list?
I've had a go, but it doesnt appear to recognise them as my variables
Any help would be much appreciated.
Thanks
MY ATTEMPT:
else if (i==1)
{
StockListInterface.doAddItem(item);
System.out.println("Add New Item");
System.out.println("****************");
System.out.println("Enter ID :>");
Scanner scanner1 = new Scanner(System.in);
String itemID = scanner1.nextLine();
System.out.println("Enter Description :>");
Scanner scanner2 = new Scanner(System.in);
String itemDesc = scanner2.nextLine();
System.out.println("Enter Price :>");
Scanner scanner3 = new Scanner(System.in);
String price = scanner3.nextLine();
System.out.println("Enter Quantity :>");
Scanner scanner4 = new Scanner(System.in);
String quantity = scanner4.nextLine();
System.out.println("Enter Re-Order Level :>");
Scanner scanner5 = new Scanner(System.in);
String reOrderLevel = scanner5.nextLine();
System.out.println("Enter another? (Y/N) :>");
}

You don't need to create a new Scanner every time you take an input. You can use the previously defined scanner as follows:
else if (i==1)
{
StockListInterface.doAddItem(item);
System.out.println("Add New Item");
System.out.println("****************");
System.out.println("Enter ID :>");
Scanner scanner1 = new Scanner(System.in);
String itemID = scanner1.nextLine();
System.out.println("Enter Description :>");
String itemDesc = scanner1.nextLine();
System.out.println("Enter Price :>");
String price = scanner1.nextLine();
System.out.println("Enter Quantity :>");
String quantity = scanner1.nextLine();
System.out.println("Enter Re-Order Level :>");
String reOrderLevel = scanner1.nextLine();
System.out.println("Enter another? (Y/N) :>");
}
Also you should consider adding one more line at the end, to get the input of 'Y' or 'N' as follows:
String addAnother = scanner1.nextLine();

One problem in your code i can see is you are creating Object of scanner every time when you get input.
I Suggest you to use class BufferedReader like this. It works perfectly.
BufferedReader br = null
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String tmp = br.readLine();
} catch(IOException ie){
System.out.println(e)
}
br.readLine() : always returns String
You need to convert String into related to datatype. Let's say i want to convert that string to integer, Then i can use wrapper class like this
Integer num = Integer.parseInt(tmp);

You don't need to create a new scanner every time you want to read input, just use
Scanner scanner = new Scanner(System.in);
and then every time you want to read input use
scanner.nextLine()
but if you know you're reading in an int etc you can use specific methods like
scanner.getInt()
see here for more information

Related

How to read a number and a sentence using Java Scanner

I want to understand why using Scanner.nextInt() to read a number and then using Scanner.nextLine() to read a sentence does not work as expected. I have the following code where I input a number but it skips listening to the sentence and my program terminates. Could someone explain why this is and what are alternate solutions?
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
System.out.println("Enter a sentence");
System.out.println(x);
String line = scanner.nextLine();
System.out.println(line);
In your code, you have to write scanner.nextLine() after int x = scanner.nextInt();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter a sentence");
System.out.println(x);/*be careful,
here you write the result of x and below you are going to write the sentence.
I think you better write
System.out.println(x);
above
System.out.println("Enter a sentence");*/
String line = scanner.nextLine();
System.out.println(line);
You need a different Scanner instance for String receiving and another for Integer
Scanner scanNumbers = new Scanner(System.in);
Scanner scanString = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanNumbers.nextInt();
System.out.println(x);
System.out.println("Enter a sentence");
String line = scanString.nextLine();
System.out.println(line);
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = scanner.nextInt();
System.out.println(x);
scanner.nextLine(); // skip the newline character
System.out.println("Enter name");
String name1 = scanner.nextLine();
System.out.println(name1);

Java giving error when trying to use multiple inputs in while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 1 year ago.
The following java code gives the following error: Exception in thread "main" java.util.NoSuchElementException: No line found.
boolean running = true;
while (running) {
Scanner sc2 = new Scanner(System.in);
System.out.println("Enter an item to order:");
String name = sc2.nextLine();
System.out.println("Enter the price:");
String price = sc2.nextLine();
System.out.println("Enter the quantity:");
String quantity = sc2.nextLine();
orderItems.add(name);
orderItems.add(price);
orderItems.add(quantity);
orderItems.add(";");
System.out.println("Would you like to add another item?: (y/n)");
if (sc2.nextLine() != "y") {
running = false;
}
}
Any suggestions? I've gotten a similar error before, which was caused by using a new scanner for each input instead of using the same one for each input, but this error seems to be caused by a different issue. Thanks in advance.
A similar issue is here, but you create a new instance every iteration of the while loop.
Create a single Scanner in the first line of the method.
Declare your scanner object only once. Your while loop was creating multiple scanners (see Multiple scanner objects)
You were not performing the String comparison in the right way (see How do I compare strings in Java?)
boolean running = true;
Scanner sc2 = new Scanner(System.in);
while (running) {
System.out.println("Enter an item to order:");
String name = sc2.nextLine();
System.out.println("Enter the price:");
String price = sc2.nextLine();
System.out.println("Enter the quantity:");
String quantity = sc2.nextLine();
orderItems.add(name);
orderItems.add(price);
orderItems.add(quantity);
orderItems.add(";");
System.out.println("Would you like to add another item?: (y/n)");
if (sc2.nextLine().equals("y")) {
running = false;
}
}
Create only a single instance for the Scanner by providing it before the while loop.
And also a suggestion, use !sc2.nextLine().equals("y") instead of sc2.nextLine() != "y"
boolean running = true;
Scanner sc2 = new Scanner(System.in);
while (running) {
System.out.println("Enter an item to order:");
String name = sc2.nextLine();
System.out.println("Enter the price:");
String price = sc2.nextLine();
System.out.println("Enter the quantity:");
String quantity = sc2.nextLine();
orderItems.add(name);
orderItems.add(price);
orderItems.add(quantity);
orderItems.add(";");
System.out.println("Would you like to add another item?: (y/n)");
if (!sc2.nextLine().equals("y")) {
running = false;
}
}

Store in an ArrayList

How could i store the below code in an array list using Java? Im stuck. Your help will be greatly appreciated.
System.out.println("Please enter Officer's First Name");
firstName = input.next();
officerObject.setOfficerFirstName(firstName);
System.out.println("Enter Officer's Last Name");
lastName = input.next();
officerObject.setOfficerLastName(lastName);
System.out.println("Enter Officer's Badge Number");
badgeNum = input.next();
officerObject.setOfficerBadgeNum(badgeNum);
System.out.println("Enter Officer's Precint");
precint = input.next();
officerObject.setOfficerPrecint(precint);
Create an array list with List<YOUR OBJECT TYPE> array = new ArrayList<>(); and then use array.add(officerObject); to add it to the array list.
Well as he said use a List look
First it could be use like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Officer officerObject = new Officer();
System.out.println("Please enter Officer's First Name");
officerObject.setOfficerFirstName(input.next());
System.out.println("Enter Officer's Last Name");
officerObject.setOfficerLastName(input.next());
System.out.println("Enter Officer's Badge Number");
officerObject.setOfficerBadgeNum(input.next());
System.out.println("Enter Officer's Precint");
officerObject.setOfficerPrecint(input.next());
List<Officer> officer = new ArrayList<Officer>();
officer.add(officerObject);
for(Officer of: officer){
System.out.println(of.getOfficerFirstName());
System.out.println(of.getOfficerLastName());
System.out.println(of.getOfficerBadgeNum());
System.out.println(of.getOfficerPrecint());
}

Why string inputs after integer input gets skipped in Java? [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I am trying to input values of certain string and integer variables in Java.
But if I am taking the input of string after the integer, in the console the string input is just skipped and moves to the next input.
Here is the code
String name1;
int id1,age1;
Scanner in = new Scanner(System.in);
//I can input name if input is before all integers
System.out.println("Enter id");
id1 = in.nextInt();
System.out.println("Enter name"); //Problem here, name input gets skipped
name1 = in.nextLine();
System.out.println("Enter age");
age1 = in.nextInt();
This is a common problem, and it happens because the nextInt method doesn't read the newline character of your input, so when you issue the command nextLine, the Scanner finds the newline character and gives you that as a line.
A workaround could be this one:
System.out.println("Enter id");
id1 = in.nextInt();
in.nextLine(); // skip the newline character
System.out.println("Enter name");
name1 = in.nextLine();
Another way would be to always use nextLine wrapped into a Integer.parseInt:
int id1;
try {
System.out.println("Enter id");
id1 = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
e.printStackTrace();
}
System.out.println("Enter name");
name1 = in.nextLine();
Why not just Scanner.next() ?
I would not use Scanner.next() because this will read only the next token and not the full line. For example the following code:
System.out("Enter name: ");
String name = in.next();
System.out(name);
will produce:
Enter name: Mad Scientist
Mad
It will not process Scientist because Mad is already a completed token per se.
So maybe this is the expected behavior for your application, but it has a different semantic from the code you posted in the question.
This is your updated working code.
package myPackage;
import java.util.Scanner;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
String name1;
int id1,age1;
Scanner in = new Scanner(System.in);
//I can input name if input is before all integers
System.out.println("Enter id");
id1 = in.nextInt();
System.out.println("Enter name"); //Problem here, name input gets skipped
name1 = in.next();
System.out.println("Enter age");
age1 = in.nextInt();
}
}
May be you try this way..
Instead of this code
System.out.println("Enter name"); //Problem here, name input gets skipped
name1 = in.nextLine();
try this
System.out.println("Enter name");
name1 = in.next();

"error: variable keyboard is already defined in method main(String [])"

I'm getting several error messages when I try to run my program, the main one which bothers me being "error: variable keyboard is already defined in method main(String [])"
Am I supposed to but main(String []) more than once in my program, or just in the beginning as I have it? What else could be wrong here?
Here is the beginning of my program:
public static void main(String[]args)
{
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard = new Scanner(System.in);
firstName = keyboard.nextString();
System.out.println("Enter your last name:");
Scanner keyboard = new Scanner(System.in);
lastName = keyboard.nextString();
System.out.println("Enter the number of movies downloaded:");
Scanner keyboard = new Scanner(System.in);
moviesDownloaded = keyboard.nextInt();
System.out.println("Enter the cost per movie:");
Scanner keyboard = new Scanner(System.in);
movieCost = keyboard.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
Scanner keyboard = new Scanner(System.in);
stateResidency = keyboard.nextInt();
You should only declare and initialize keyboard once and then use it. So remove all lines of the type: Scanner keyboard = new Scanner(System.in); apart from the first one.
Otherwise you try to declare the same variable multiple times and thus java complains.
I'm guessing this has been long solved by this point but I came across it and I really like closure, because Ivaylo Strandjev answer was not chosen. Also in case anyone else stumbles across this.
The error is saying you defined the variable keyboard in this scope already and you are trying to define it again.
like Ivaylo Strandjev was saying.
You can try the following:
1 remove the declaration portion
public static void main(String[]args) {
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard = new Scanner(System.in);
firstName = keyboard.nextString();
System.out.println("Enter your last name:");
keyboard = new Scanner(System.in); //-----changed
lastName = keyboard.nextString();
System.out.println("Enter the number of movies downloaded:");
keyboard = new Scanner(System.in); //-----changed
moviesDownloaded = keyboard.nextInt();
System.out.println("Enter the cost per movie:");
keyboard = new Scanner(System.in);//-----changed
movieCost = keyboard.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
keyboard = new Scanner(System.in);//-----changed
stateResidency = keyboard.nextInt();`
or this, change the new variable names
public static void main(String[]args){
String firstName, lastName;
int moviesDownloaded, stateResidency;
double movieCost, netPayment, tax, discount, totalCharge, payment, taxRate;
System.out.println("Enter your first name:");
Scanner keyboard1 = new Scanner(System.in);
firstName = keyboard1.nextString();
System.out.println("Enter your last name:");
Scanner keyboard2 = new Scanner(System.in);//-----changed
lastName = keyboard2.nextString();
System.out.println("Enter the number of movies downloaded:");
Scanner keyboard3 = new Scanner(System.in);//-----changed
moviesDownloaded = keyboard3.nextInt();
System.out.println("Enter the cost per movie:");
Scanner keyboard4 = new Scanner(System.in);//-----changed
movieCost = keyboard4.nextDouble();
System.out.println("Indicate your state of residency. Enter 1 for Mississippi or 2 for any other state.");
Scanner keyboard5 = new Scanner(System.in);//-----changed
stateResidency = keyboard5.nextInt();`
You don't need to initialize Keyboard every time you use it. You can declare it once at the top of the program, and just call keyboard.next() each time you want to get something from it.

Categories

Resources