How to allow for user input java - 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.

Related

How do I categorize a list of user inputs into different orders?

I am supposed to make a program that asks users for a list of input. Then, from that list, my program is supposed to pick out the third answer and then print it out. It sounds really simple, but how do I assign numbers to each of the user inputs? Do I even do that? I am a beginner, and thank you so much for your help!
This is the code I have so far:
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if(ans.equals(""))
{
break;
}
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}
You can strore the third input in a variable you initialized bevor the loop.
if there is no third input it prints: ""
import java.util.*;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int index = 0;
String input3 = "";
while(true) {
System.out.println("What do you appreciate in your life or school?");
String ans = scan.nextLine();
if (index == 2) {
input3 = ans;
}
if(ans.equals("")){
break;
}
index++;
}
System.out.println("You said \"" + input3 + "\" as your third answer.");
}
}

Having direct user input in java

I apologize for how I asked my previous question but hope that I can make this question clearer. I am trying to write a code where a user can place information under the columns of firstname, lastname and marks but I have failed.
With this code I have written the values under num are supposed to be automatic.
Please help me out and thank you.
package school;
import java.util.Scanner;
class Assign1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("NUM\t FIRSTNAME \t LASTNAME \t MARKS \t GRADE");
int i=1;
String f = sc.nextLine();
while(i<=2) {
System.out.print(i+ "\t");
System.out.print("\t" + f);
i++;
}
}
}
I think I understood your question. Correct me if I'm wrong.
You want the mentioned columns to be printed and the user to input data under each column. You also want the number column to print numbers automatically. Here is the code for that program:
import java.util.Scanner;
class Assign1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("NUM\t FIRSTNAME\t LASTNAME\t MARKS\t GRADE");
int i=1;
String firstName = "";
String lastName = "";
int marks = 0;
String grade = "";
while(i<=2) {
System.out.print(i+ "\t ");
firstName = sc.next();
lastName = sc.next();
marks = sc.nextInt();
grade = sc.next();
i++;
}
}
}
To store each kind of column data, we need different variables of the proper type. Next, we are inputting data from the user while staying inside the loop. Since i=1, the while condition is true 2 times and the user is able to enter 2 different records.
The output will be like this:

Java program cannot find symbol nextInt() or nextLine()

Here is my code that I've written so far....basically I want to enter a first name (eventually a last name and a GPA) and have it saved in a 2D array. I'm having trouble with adding the user input into the array. Under public static void addstudent is this a correct method for adding to an array? If so, why do I keep getting the error that nextInt is not found? I also get that if I change it to nextLine or just next(). Thanks for the help!
import static java.lang.System.in;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
public class Project1 {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
String [][] students = new String [50][3];
System.out.println("Menu");
System.out.println("A) Add Student");
System.out.println("D) Delete Student");
System.out.println("L) List Students");
String opt = input.nextLine();
char optc = opt.charAt(0);
switch(optc) {
case 'A': addStudent(students);
case 'D': deleteStudent(students);
case 'L': listStudent(students);
}
}
public static void addStudent(String students[][]) {
Scanner input = new Scanner(System.in); {
}
for (int i = 0; i < students.length; i++) {
System.out.println("Please Enter first name");
students[i] = in.nextInt();
}
Sooner or later, you're going to want to refactor your 2d array into an array of objects like so:
public class Student{
public String firstName;
public String lastName;
public float GPA;
public Student(String fn, String ln, float g){
firstName = fn;
lastName = ln;
GPA = g;
}
}
public class project1{
//note that the variables are class-scope, not function-scope
Student stus[50];
.
.
.
}
In the meantime, you're trying to access a 2d array, not a 1d array, and you need to accept as input a string, not an int, so this line:
students[i] = in.nextInt();
should look like this:
students[i][0] = input.nextLine();

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.

Can someone help me figure out why one of my methods is not running at all?

Why when I run my program and enter 5, it allows me to enter my records, but when the main menu runs again and I enter 6, the changePhoneNumber method is not run and it goes back to the main menu. Is the while(true) loop somehow messing things up?
I have a class called Record that looks like:
public static void main(String[] args) {
BankMethods method = new BankMethods();
Scanner input = new Scanner(System.in);
int optionSelected = 0;
while(true){
System.out.println("5. Add a New Record");
System.out.println("6. Change the Phone Number in the Current Record");
optionSelected = input.nextInt();
if (optionSelected == 5){
Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = getRecord.nextLine();
System.out.println("Enter Last Name: ");
String lastName = getRecord.nextLine();
System.out.println("Enter Phone Number: ");
String phoneNumber = getRecord.nextLine();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6){
System.out.println("What would you like to change your phone "
+ "number to? ");
String newNumber = input.nextLine();
method.changePhoneNumber(newNumber);
}
and the other class...BankMethods:
public class BankMethods {
LinkedList recordInformation = new LinkedList();
Bankdata mainMenu = new Bankdata();
public void addNewRecord(String firstName, String lastName,
String phoneNumber){
recordInformation.add(firstName); recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber){
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
The problem is that you are using 2 Scanners to read the one InputStream. When you open the second Scanner you will not be able to read using the original one as the second will have exclusive access to it.
For this application you could easily use a single Scanner.
See: Do not create multiple buffered wrappers on a single InputStream
The correct way is to use one read(scanner) for a input stream. Edited the previous answer to use single read option
Complete program that works is given below
package com.stackoverflow.framework;
import java.util.LinkedList;
import java.util.Scanner;
public class Record {
static Scanner input = new Scanner(System.in);
public static String readData() {
return (input.nextLine());
}
public static void main(String[] args) {
BankMethods method = new BankMethods();
int optionSelected = 0;
while (true) {
System.out.println("5. Add a New Record");
System.out
.println("6. Change the Phone Number in the Current Record");
optionSelected = Integer.parseInt(readData());
if (optionSelected == 5) {
// Scanner getRecord = new Scanner(System.in);
System.out.println("Enter First Name: ");
String firstName = readData();
System.out.println("Enter Last Name: ");
String lastName = readData();
System.out.println("Enter Phone Number: ");
String phoneNumber = readData();
method.addNewRecord(firstName, lastName, phoneNumber);
}
if (optionSelected == 6) {
System.out.println("What would you like to change your phone "
+ "number to? ");
// Scanner getRecord = new Scanner(System.in);
String newNumber = readData();
method.changePhoneNumber(newNumber);
}
}
}
}
class BankMethods {
LinkedList recordInformation = new LinkedList();
public void addNewRecord(String firstName, String lastName,
String phoneNumber) {
recordInformation.add(firstName);
recordInformation.add(lastName);
recordInformation.add(phoneNumber);
}
public void changePhoneNumber(String newNumber) {
recordInformation.set(2, newNumber);
System.out.println(recordInformation);
}
}

Categories

Resources