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();
Related
The question requires us to create two objects of the Student class and have 5 variables. The variables will be assigned a value each through user input.
Is there a way to use a loop or anything else to take the user inputs from there instead of writing each variable individually using the dot operator?
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student();
Student student2 = new Student();
//Input for student 1
student1.name = input.nextLine();
student1.gender = input.next().charAt(0);
student1.cgpa = input.nextDouble();
student1.roll[0] = input.nextInt();
student1.age = input.nextInt();
//Input for student 2
student2.name = input.nextLine();
student2.gender = input.next().charAt(0);
student2.cgpa = input.nextDouble();
student2.roll[0] = input.nextInt();
student2.age = input.nextInt();
}
}
class Student {
String name;
char gender;
double cgpa;
int[] roll;
int age;
}
We can create a constructor for the class Student that takes in the parameters and defines them as so:
class Student {
String name;
char gender;
double cgpa;
int[] roll = new int[10];
int age;
public Student(String n,char g,double c,int r,int a){
name = n;
gender = g;
cgpa = c;
roll[0] = r;
age = a;
}
public String toString(){
return name;
}
}
Note that we must give roll a specified length before assigning it any elements. Alternatively, we could use an ArrayList instead of an array for roll if we are not given the length (I used 10 as a placeholder).
As for the main method, we can now define student1 and student2 in one line each:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student(input.nextLine(), input.next().charAt(0), input.nextDouble(), input.nextInt(), input.nextInt());
input.nextLine();
Student student2 = new Student(input.nextLine(), input.next().charAt(0), input.nextDouble(), input.nextInt(), input.nextInt());
System.out.println(student1);
System.out.println(student2);
}
}
Notice how between the declarations of student1 and student2 there is a input.nextLine(). This is because after we take the final parameter, an integer, for student1, the input will leave a trailing newline which will mess with the user input for student2. To fix this, we can scan the line to get rid of the whitespace.
I hope this helped! Please let me know if you need any further clarification or details :)
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:
I'm trying to store input in the array indoor_games and output it to the screen, but when I'm executing the code, it abruptly ends the execution after accepting 1 value.
package games;
import java.util.*;
import java.lang.*;
class Indoor{
String name;
Indoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Outdoor{
String name;
Outdoor(String name){
this.name = name;
}
public void display(){
System.out.println(this.name);
}
}
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
for(int i=0;i<size;i++){
name = sc.next();
indoor_games[i] = new Indoor(name);
}
for(int i=0;i<size;i++)
indoor_games[i].display();
}
}
Updated code with nextLine added but still the same problem:
class Slip20{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
sc.nextLine(); //To consume the newline character
Indoor[] indoor_games = new Indoor[size];
for(int i = 0 ; i < size ; i++){
name = sc.nextLine();
indoor_games[i] = new Indoor(name);
}
for(int i = 0 ; i < size; i++)
indoor_games[i].display();
}
}
Output(Command Line)
D:\Docs Dump\School stuff\JAVA\Java slips>java games.Slip20
Enter number of Players in Indoor Games:
3
Neeraj
D:\Docs Dump\School stuff\JAVA\Java slips>
As you can see, the scanner only accepts "Neeraj" and the program ends
execution.
just replace sc.next() by sc.nextLine()
This is because nextLine() required. But be aware use it, documentation say that:
Advances this scanner past the current line and returns the input
* that was skipped.
This method returns the rest of the current line, excluding any line
* separator at the end. The position is set to the beginning of the next
* line.
Known that you should use before loop and problem will be solved.
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of Players in Indoor Games: ");
int size = sc.nextInt();
Indoor[] indoor_games = new Indoor[size];
sc.nextLine();
for (int i = 0; i < size; i++) {
System.out.println("Please write a name:");
indoor_games[i] = new Indoor(sc.nextLine());
}
Hey thanks for the answers and help. It was actually a compilation problem, I was compiling the package in a wrong way. It's working now.
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.
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.