How to input an integer just after a string? - java

This is my code for printing a shopping list. It works fine when I put the data manually at runtime through keyboard. But when I direct an input.txt file as an argument in command line it throws NoSuchElementException after 1st iteration.
I think it might have to do with the sequence of using Scanner.next() and Scanner.nextInt() but not sure.
How do I fix this?
import java.io.*;
import java.util.*;
class Product
{
Scanner sc = new Scanner(System.in);
int productID;
String productName;
String productType;
float productPrice;
Product()
{
// Do Nothing.
}
void createProduct()
{
System.out.println("Enter the Product ID: ");
productID = sc.nextInt();
System.out.println("Enter the Product Name: ");
productName = sc.next();
System.out.println("Enter the Product Type: ");
productType = sc.next();
System.out.println("Enter the Product Price: ");
productPrice = sc.nextFloat();
}
Product(int pID, String pName, String pType, float pPrice)
{
productID = pID;
productName = pName;
productType = pType;
productPrice = pPrice;
}
void showIdentification()
{
System.out.println(productID + " " + productName);
}
void showDetail()
{
System.out.println(productID + " " + productName + " " + productType + " " + productPrice);
}
}
class Shop
{
int n = 10;
Product list[] = new Product[n];
void createList()
{
for(int i=0; i<n; i++)
{
System.out.println("Product No. " + (i+1));
Product o = new Product();
o.createProduct();
o.showDetail();
list[i] = o;
}
}
void viewAllProducts()
{
for(int i=0; i<n; i++)
{
list[i].showIdentification();
}
}
}
class ShopList
{
public static void main(String[] args)
{
Shop sList = new Shop();
sList.createList();
sList.viewAllProducts();
}
}
Here is the input file :-
1001 CadburyA ChocolateA 15.00
1002 CadburyB ChocolateB 16.00
1003 CadburyC ChocolateC 17.00
1004 CadburyD ChocolateD 18.00
1005 CadburyE ChocolateE 19.00
1006 CadburyF ChocolateF 20.00
1007 CadburyG ChocolateG 21.00
1008 CadburyH ChocolateH 22.00
1009 CadburyI ChocolateI 23.00
1010 CadburyJ ChocolateJ 24.00
and here is the exception I got:-
java ShopList < input.txt
Product No. 1
Enter the Product ID:
Enter the Product Name:
Enter the Product Type:
Enter the Product Price:
1001 CadburyA Chocolate 15.0
Product No. 2
Enter the Product ID:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Product.createProduct(ShopList.java:19)
at Shop.createList(ShopList.java:59)
at ShopList.main(ShopList.java:95)

You have to make Scanner static:
class Product
{
// There is only one System.in - the Scanner can be shared between
// all instances
static Scanner sc = new Scanner(System.in);
int productID;
String productName;
String productType;
float productPrice;
Product ()
{
// Do Nothing.
}
void createProduct()
{
System.out.println(" Enter the Product ID: ");
productID = sc.nextInt ();
// for debugging, I inserted the last value in the printlns:
System.out.println (productID + " Enter the Product Name: ");
productName = sc.next ();
System.out.println (productName + " Enter the Product Type: ");
productType = sc.next ();
System.out.println (productType + " Enter the Product Price: ");
productPrice = sc.nextFloat ();
System.out.println (productPrice + " ");
/* Helpless attemps to find out, if we need to consume the line break :)
String s = "dummy";
while (s != "\n") {
s = sc.next ();
System.out.println ("<" + s + ">");
}
*/
}
No other modifications were made.
Well, not exactly. As continental European, I had to tell the system, that my numbers are dot delimited or better, pass in comma delimited ones.
cat choco.lst | sed 's/\./,/' | java ShopList
That might not be the case on your system.
Well, and the Scanner in ShopList, which is not used, shall vanish too.

Related

How to calculate sum from user input inside while loop

I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation

How to put scanner inside a method and its output on a different method

I want to ask the user through a scanner class but I want this scanner to be in a method named readInput() and the output on a different method named writeOutput() using gett-setter
this is my code below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LaboratoryExercise2 gro = new LaboratoryExercise2();
String[] SecondQuestion;
System.out.println("Select the item your purchasing.");
String Product1 = sc.nextLine();
System.out.println("Enter the Quantity and price separated by SPACE.");
SecondQuestion = sc.nextLine().split(" ");
int Quantity1 = Integer.parseInt(SecondQuestion[0]);
double Price1 = Double.parseDouble(SecondQuestion[1]);
double Amount1 = 0;
Amount1 = Quantity1 * Price1;
int Quantity = 0 + Quantity1;
double Amount = 0 + Amount1;
double Price = 0 + Price1;
I want the output of this to show on a different method
gro.setGrocery(Price, Quantity, Amount);
System.out.println("You've selected " + gro.getitemQuantity() + " " + Product1 + " " + "at " + " " +
gro.getitemPrice() + " each");
System.out.println("Amount due is " + gro.getamountDue());
This is my whole code:
import java.util.Scanner;
public class LaboratoryExercise2 {
private double itemPrice;
private int itemQuantity;
private double amountDue;
public void setGrocery(double newitemPrice, int newitemQuantity, double newamountDue) {
itemPrice = newitemPrice;
itemQuantity = newitemQuantity;
amountDue = newamountDue;
}
public double getitemPrice() {
return itemPrice;
}
public int getitemQuantity() {
return itemQuantity;
}
public double getamountDue() {
return amountDue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LaboratoryExercise2 gro = new LaboratoryExercise2();
String[] SecondQuestion;
System.out.println("Select the item your purchasing.");
String Product1 = sc.nextLine();
System.out.println("Enter the Quantity and price separated by SPACE.");
SecondQuestion = sc.nextLine().split(" ");
int Quantity1 = Integer.parseInt(SecondQuestion[0]);
double Price1 = Double.parseDouble(SecondQuestion[1]);
double Amount1 = 0;
Amount1 = Quantity1 * Price1;
int Quantity = 0 + Quantity1;
double Amount = 0 + Amount1;
double Price = 0 + Price1;
gro.setGrocery(Price, Quantity, Amount);
System.out.println("You've selected " + gro.getitemQuantity() + " " + Product1 + " " + "at " + " " +
gro.getitemPrice() + " each");
System.out.println("Amount due is " + gro.getamountDue());
}
}
Piling all your code into main is a bad idea. Java is object oriented, and main, being static, isn't.
The solution for sharing data between methods is usually to make a field.
class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
private Scanner scanner;
void go() throws Exception {
scanner = new Scanner(System.in);
scanner.useDelimiter("\\R");
int quantity = askInt("Enter the quantity: ");
}
private int askInt(String prompt) {
while (true) {
System.out.print(prompt);
if (scanner.hasNextInt()) return scanner.nextInt();
scanner.next(); // eat the non-int token
System.out.println("ERROR: Please enter an integer number.");
}
}
}
That's what virtually all command line java apps should look like: a one-liner main method, no use of static anywhere except main, a scanner field, set with the proper delimiter (\\R, which means .nextX() always reads one line worth of input; use .next() to read an entire line. Don't call .nextLine(), ever. nextLine() and all the other next methods interact in nasty ways that make scanner useless or at least unwieldy and bugprone for command line 'prompting', which why you do it this way.

Getting Null Output while using my Program Logic

I am getting null output along when i am getting to string method in my program output.
//Main Method
package studentDatabaseApp;
import java.util.Scanner;
public class StudentDatabaseApp {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of Students: ");
int numOfStudents = scan.nextInt();
Student[] students = new Student[numOfStudents];
for(int n =0; n < numOfStudents; n++) {
students[n] = new Student();
students[n].enroll();
students[n].payTution();
}
for(int n =0; n < numOfStudents; n++) {
System.out.println(students[n].toString());
}
}
}
//Student Class Code
package studentDatabaseApp;
import java.util.Scanner;
public class Student {
private String firstName;
private String lastName;
private int gradeYear = 0;
private String studentID;
private String courses;
private static int courseCost = 600;
private int tutionBalance = 0;
private static int id = 1000;
//Constructor to enter student name and year for each student
public Student() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Student First Name: ");
this.firstName = scan.nextLine();
System.out.print("Enter Student Last Name: ");
this.lastName = scan.nextLine();
System.out.print("1 - Freshmen\n2 - Sophmore\n3 - Junior\n4 - Senior\nEnter Student Grade Year: ");
this.gradeYear = scan.nextInt();
//Setting student id
setStudentID();
}
//Unique id and student grade level
private void setStudentID() {
id++;
this.studentID = gradeYear + "" + id;
}
//Create courses so student can enroll
public void enroll() {
do {
System.out.print("Enter course to enroll (Q to Quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if(!course.equals("Q")) {
courses = courses + ", " + course;
tutionBalance = tutionBalance + courseCost;
}
else {
break;
}
}while(1 != 0);
}
//Student should able to view their balance and pay the tution
public void viewBalance() {
System.out.println("BALANCE TOTAL: " + tutionBalance);
}
//Total balance
public void payTution() {
viewBalance();
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter your payment: ");
int tutionPaid = scan.nextInt();
tutionBalance = tutionBalance - tutionPaid;
viewBalance();
}
//Student status with their name, ID, course enrolled and balance
#Override
public String toString() {
return "\nSTUDENT NAME: " + firstName + " " + lastName +
"\nGRADE LEVEL: " + gradeYear + " " + "\nSTUDENT ID: " + studentID +
"\nCOURSES ENROLLED: " + courses +
"\nTUTION BALANCE: " + tutionBalance;
}
}
//Console Output
Enter number of Students: 1
Enter Student First Name: bilal
Enter Student Last Name: mujahid
1 - Freshmen
2 - Sophmore
3 - Junior
4 - Senior
Enter Student Grade Year: 4
Enter course to enroll (Q to Quit): Eng 101
Enter course to enroll (Q to Quit): Math 101
Enter course to enroll (Q to Quit): Q
BALANCE TOTAL: 1200
Enter your payment: 1000
BALANCE TOTAL: 200
STUDENT NAME: bilal mujahid
GRADE LEVEL: 4
STUDENT ID: 41001
COURSES ENROLLED: null, Eng 101, Math 101
TUTION BALANCE: 200
The problem is with
private String courses;
You use
courses = courses + course;
Courses is null since it is never initialized. Try changing it to
private String courses = “”;
(This will cause it to have a extra comma in the beginning which you can easily just substring off)
Initialise it with course the first time
if(!course.equals("Q")) {
courses = coursers == null ? course : courses + ", " + course;
...

Create multiple students and check if any are repeated java

In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
public class Registrar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1 = " ";
while(string1 != "1")
{
System.out.println("Please input full name name of student: ");
string1 = input.next(); // user input of name
if (string1 != "0"){
break;
}
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student first = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
}
}
}
This is my Student Class
public class Student {
private String name;
private String idnum;
private int credits;
private double gradePoints;
public Student(String n, String id, int c, double gp){
name = n;
idnum = id;
credits = c;
gradePoints = gp;
}
public String getName(){
return name;
}
public String getId(){
return idnum;
}
public int getCredits(){
return credits;
}
public double getGradePoints(){
return gradePoints;
}
}
Try this code. better implementation with collection.
Scanner input = new Scanner(System.in);
String string1 = " ";
System.out.println("Number of students to be entered");
int s = input.nextInt();
List<Student> studentList = new ArrayList<Student>();
for(int i = 0; i<s; i++) {
System.out.println("Please input full name of student: ");
string1 = input.next(); // user input of name
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student student = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
studentList.add(student);
}
You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
//Code for take details of user
}
//Then you can print the details of student in similar way.

how to check the int range in java and limit it only 5digits

Please help with my assignment. Here is the question:
Create a separate test driver class
called TestEmployeePayroll that will
test the EmployeePayroll class by
performing the following:
Prompt the user to enter the
employees’ ID number, First name, Last
name, Pay Category and Hours worked
(one at a time).
The user entry for employees ID
number must be exactly 5 digits long.
The user entry for Category must only
be accepted if it is in the range 1
to 4.
The user entry for Hours worked
must only be accepted if it is the
range 1 to 80.
This is what I did till now:
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
EmployeePayRoll obj1 = new EmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: "+ " ");
String EmployeeID = input.nextLine();
//How to check the range here if int is 5 digits long or not ?
System.out.println("Enter the first Name: "+ " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: "+ " ");
double PayCategory = input.nextDouble();
System.out.println("Enter the number of hours worked: "+ " ");
double HoursWorked = input.nextDouble();
}
}
You will probably want to use Integer.parseInt().
You can count the length of a String and then convert it to number, Oli Charlesworth told you how to convert it, or you can measure the number. It depends on what you want. Is 012345 a valid ID? It's a 6 char String but it is less than the biggest 5 digits number.
I think you almost got it...
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
// ... get the values, as you are doing already
// validate input
int employeeIdAsInteger = validateAndConvertEmployeeId(EmployeeId);
int payCategoryAsInteger = validateAndConvertPayCategory(PayCategory);
// ... and so on
}
private int validateAndConvertEmployeeId(String employeeId) {
// The user entry for employees ID number must be exactly 5 digits long.
if (employeeId == null || employeeId.trim().length() != 5) {
throw new IllegalArgumentException("employee id must be exactly 5 digits long");
}
// will throw an exception if not a number...
return Integer.parseInt(employeeId);
}
// ...
}
Depending on your objectives & constraints, you could look into the Pattern class and use a regular expression.
You can check for conditions like this.
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args) {
TestEmployeePayRoll obj1 = new TestEmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: " + " ");
String EmployeeID = input.nextLine();
if (EmployeeID.trim().length() != 5) {
System.out.println("--- Enter valid Employee ID number ---");
}
System.out.println("Enter the first Name: " + " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: " + " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: " + " ");
double PayCategory = input.nextDouble();
Double pay = new Double(PayCategory);
if (pay.isNaN()) {
System.out.println("***** Enter a valid Pay Category *****");
}
if (!(PayCategory >= 0 && PayCategory <= 5)) {
System.out.println(" --- PayCategory must be between 0 and 5");
}
System.out.println("Enter the number of hours worked: " + " ");
double HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if (hours.isNaN()) {
System.out.println("--- Enter a valid hours value ----");
} else {
if (!(HoursWorked >= 1 && HoursWorked <= 80)) {
System.out.println("--- Enter value between 1 and 80 ---");
}
}
}
}

Categories

Resources