Using a scanner-method for multiple set methods within class - java

I am trying to create scanner methods within my class Address so I do not have to repeat the scanner code in every single method where I want user input. What I'm having problem with is that this method only seems to return my instance variable values and not the scanner inputs from the user when I run these two set methods in a test program of an instance of my Address class.
How can I do this? I do not want to repeat the scr.nextInt() etc in every single method.
//Scanner method for integer inputs from user.
public int scanInt(){
int userInt = scr.nextInt();
scr.nextLine();
return userInt;
}
//Scanner method for string inputs from user
public String scanLine(){
String userString = scr.nextLine();
return userString;
}
//in these methods below (and others) I want to use the above scanner methods so I don't have to repeat the code for scanner inputs in every single method.
public void setStreet(){
System.out.println("Skriv in gata: ");
scanLine();
}
public void setStreetNr(){
System.out.println("Skriv in gatunummer: ");
scanInt();
}

public void setStreet(){
System.out.println("Skriv in gata: ");
street = scanLine();
}

Sounds like you are testing your class with BlueJ or some other program. If that's the case, try this class.
import java.util.Scanner;
public class Address
{
String street;
int streetNr;
Scanner scr = new Scanner(System.in);
//Scanner method for integer inputs from user.
public int scanInt()
{
int userInt = scr.nextInt();
scr.nextLine();
return userInt;
}
//Scanner method for string inputs from user
public String scanLine()
{
String userString = scr.nextLine();
return userString;
}
public void setStreet()
{
System.out.println("Skriv in gata: ");
street = scanLine();
}
public void setStreetNr()
{
System.out.println("Skriv in gatunummer: ");
streetNr = scanInt();
}
}
This should work as you describe. Create an instance of the class, call both methods and inspect your object's parameters. This code assigns your inputs to a variable for each method.

Related

System.out.print() reads Scanner incorrectly

I was trying to code this program for one of my classes and I ran into a problem with my output. It is supposed to read whatever I have typed in for the Scanner input. However, the output skips the first word and I'm not really sure why. You can ignore most of the declarations of variables in the main method. Those are useful just for the rest of the program.
public static void main(String[] args) {
String fullName;
int anniversaryM;
int anniversaryY;
int periodHours;
String jobTitle;
double payRate;
int monthsWorked;
double vacationHours;
double grossPay;
double retirement;
double taxWithholding;
double netPay;
Scanner in = new Scanner(System.in);
fullName = inputLine(in, "Enter your full name:");
System.out.print(fullName);
}
public static double inputNumber(Scanner input, String prompt) {
Scanner in = new Scanner(System.in);
in.nextDouble();
return in.nextDouble();
}
public static String inputLine(Scanner input, String prompt) {
Scanner in = new Scanner(System.in);
System.out.println(prompt);
in.next();
return in.next();
}
public static double calcPercentage(double grossPay, double retirement) {
Scanner in = new Scanner(System.in);
in.nextDouble();
return in.nextDouble();
}
Output:
Enter your full name:
John Doe
Doe
You have a double call to in.next(). Just remove it and you should be OK. Additionally, note that you're passing the Scanner to the method, so you shouldn't create a new inside the method:
public static String inputLine(Scanner input, String prompt) {
System.out.println(prompt);
return input.nextLine();
}
I think your problem is the in.next(); return in.next();. in which case it will call the reader two times, if you want to return the value of the in.next(); you should put it in a container and return that container or just go straight return in.next();

How to get an user input and use the value inside method?

How to get an user input using scanner class and use it inside method to process, and obtain output?
Example : You get two numbers from the user and pass it to 4 methods to get its value after addition, subtraction, multiplication, division.
The scanner should be in main class and not inside every method.
Here is my code, it's in basic form. I want to get input from the user and process it inside the methods and get the result:
class Calc{
public static void main(String[] args){
add();
sub();
mul();
div();
{
void Add() {
int a=5,b=10;
sum=a+b;
System.out.println(sum);
}
void sub() {
int a=5,b=10;
sub=a=b;
System.out.println(sub);
}
void mul() {
int a=5,b=10;
mul=a*b;
System.out.println(mul);
}
void div() {
int a=5,b=10;
div=a/b;
System.out.println(div);
}
}
}
}
Simply use the array or nextInt() method to get the number of input and passed it to your method.
For e.g. If you are supposed two take two input at time
Scanner sc = new Scanner(System.in);
int[] integers = new int[2];
for(int i = 0; i < 2; i++)
{
integers[i] = sc.nextInt();
}
Now use the integers array to get the value from index and passed it to your method
You can get input by using new Scanner(System.in), as follows:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
add(a,b);
sub(a,b);
multiply(a,b);
divide(a,b);

How to pass or retrieve linked list from one method to another method?

First i want to retrieve patient linked list from AddPatient() method and show it on ListPatient() Method.
I try to retrieve by changing public static void ListPatient(); method to public static void ListPatient(ListInterface<PatientDetails> patient) but it doesn't work
package dsa;
import dsa.LList;
import dsa.ListInterface;
import java.sql.Time;
import java.util.Date;
import java.util.Scanner;
public class EmergencyClinic {
public static void main(String[] args){
MainMenu();
}
public static void MainMenu(){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Emergency Clinic!");
System.out.println("1. Add Patient");
System.out.println("2. Serve Patient");
System.out.println("3. List Patient");
System.out.print("Please choose your option :");
n = scan.nextInt();
switch(n){
case 1: AddPatient();
break;
case 2: ServePatient();
break;
case 3: ListPatient();
break;
default : System.out.println("Sorry! Invalid Input. Returning to main menu...\n"); MainMenu();
break;
}
}
public static void AddPatient(){
ListInterface<PatientDetails> patient = new LList<PatientDetails>();
Scanner scan = new Scanner(System.in);
int num=0;
System.out.print("Please Enter Name :");
String name = scan.nextLine();
System.out.print("Please Enter IC No :");
String ic = scan.nextLine();
System.out.print("Please Enter Contact Number :");
String contactNum = scan.nextLine();
System.out.print("Please Enter Gender :");
String gender = scan.nextLine();
Date date = new Date();
Long time = date.getTime();
System.out.print("Please Enter Reason :");
String reason = scan.nextLine();
System.out.print("Please Enter Seriousness :");
String seriousness = scan.nextLine();
if(patient.isEmpty())
{
patient.add(new PatientDetails(name, ic, contactNum, gender,date ,time ,reason,seriousness ));
}
MainMenu();
}
public static void ServePatient(){
}
public static void ListPatient(){
ListInterface<PatientDetails> patient = new LList<PatientDetails>();
System.out.println(patient.getLength());
if (!patient.isEmpty())
{
for(int i=0;i<patient.getLength();i++){
patient.getEntry(i);
}
}
else
{
System.out.println("Error in list patients!");
}
}
}
It seems that the add, list and serve are three functions. All your methods are static, then you need a static PatientList variable. That is, when user picked add, he added elements in the list, when he chose list, the same list objects would be displayed.
In codes just in your class declare:
private static ListInterface<PatientDetails> patient = new LList<PatientDetails>();
In your add and list method, use this variable directly.
All your methods are marked as void. That means the have no return value. One might say, they are procedures, not functions.
If you want to return a List, you have to change the signature:
public static List AddPatient()
Then you can return your list from the method using keyword return.
return patient;
The parameters in brackets () are all input parameters.
This is a very basic concept of methods/functions. I suggest reading a book for begginers to understand the fundamentals of Java.
Also Java has it's own general-purpose implementation of linked list. You should use it, if you don't have any special requirements for it's implementation.

System.out.print(" "); syntax error on token ".", # expected after this token

I'm getting this error on this piece of code and I can't figure out what's wrong.
public class enc {
//The Look-Up Table with the position of all the available characters
public static final String LUT="*, .abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Scanner sc=new Scanner(System.in);
System.out.print("Input the sentence you want to encode.");
String s= sc.nextLine();
}
You need to put the code inside a method:
public class enc {
//The Look-Up Table with the position of all the available characters
public static final String LUT="*, .abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Input the sentence you want to encode.");
String s= sc.nextLine();
}
}
The lines
Scanner sc = new Scanner(System.in);
System.out.print("Input the sentence you want to encode.");
String s = sc.nextLine();
should be in a code block such as a method rather than the class block
Try:
public class enc {
//The Look-Up Table with the position of all the available characters
public static final String LUT="*, .abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main (String args[]) {
Scanner sc=new Scanner(System.in);
System.out.print("Input the sentence you want to encode.");
String s= sc.nextLine();
}
}
Your lines:
System.out.print("Input the sentence you want to encode.");
String s = sc.nextLine();
Must be inside a method or a system initialiser block. Actually these are function calls which do not return anything. So cannot be in the class directly.
// In a method
public class enc {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Input the sentence you want to encode.");
String s = sc.nextLine();
}
}
OR
// In a system initializer block
public class Test {
Scanner sc = new Scanner(System.in);
{
System.out.println("yoyo");
String s = sc.nextLine();
}
}
Actually those methods can be called directly in a class which actually return something. And must also be initialised to a variable of the respective type.

How to allow for user input java

I'm not sure how to make my code so that it allows the user to input the information, I know how to create an arraylist database but not how to make it so that once the user enters the information and presses 'enter' the database is complete...can anyone help me out? (in java)
thanks for the start tips for the user input!! They were so helpful!
okay so now I have:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BestStudent
{
private String studentName;
private String studentGPA;
public BestStudent()
{
}
public BestStudent(String nName, String nGPA)
{
this.studentName = nName;
this.studentGPA = nGPA;
}
public void setStudentName(String newStudentName)
{
studentName = newStudentName;
}
public void setStudentGpa(String newStudentGPA)
{
studentGPA = newStudentGPA;
}
public String getStudentName()
{
return studentName;
}
public String getStudentGPA()
{
return studentGPA;
}
public static void main(String[] args)
{
List<BestStudent> students = new ArrayList<BestStudent>();
Scanner input = new Scanner(System.in);
System.out.println("Enter number of students");
int countStudents = input.nextInt();
for(int i = 0; i < countStudents; i++)
{
BestStudent student = new BestStudent();
System.out.println("Enter student details" + i);
System.out.println("Enter student name");
student.setStudentName(input.next());
System.out.println("Enter student GPA");
student.setStudentGpa(input.next());
students.add(student);
}
}
}
Is there a way to make it so the program calculates the highest GPA entered? I'm not looking for anyone to just give me answers, just a push in the right direction would be great, thanks so much!!
Since you know how to create an ArrayList I don't need to go over that.
Look in the Scanner class. It makes getting input easy.
Here is a short example:
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
String str = input.nextLine();
System.out.print(str);
Don't forget to import java.util.Scanner.
The code will basically instantiate a new Scanner object, then Print out "Input: " and wait for input. Once you press enter after trying what you have it will print out what you typed.

Categories

Resources