Assign multiple values of objects using a loop - java

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 :)

Related

How to avoid using the dummy lines?

I'm fairly new to programming so I'm currently stuck on figuring out how to make my code work cleaner. As of right now there are some random dummy lines in my code to make sure i dont skip part certain part of the loops. I was wondering if there are any ways to avoid it.
public static void main(String arg[]) {
String CandidateID;
String Name;
String Option1;
int Test1;
int Test2;
String dummy;
Scanner sc = new Scanner(System.in);
ArrayList<TestResult> StudentResults = new ArrayList<TestResult>();
do {
dummy = sc.nextLine();
System.out.println("Enter student data? y/n");
Option1 = sc.nextLine();
if (Option1.equals("y")) {
System.out.println("Enter Candidate ID:");
CandidateID = sc.nextLine();
System.out.println("Enter Name:");
Name = sc.nextLine();
System.out.println("Enter Test 1:");
Test1 = sc.nextInt();
System.out.println("Enter Test 2:");
Test2 = sc.nextInt();
TestResult TestResult = new TestResult(CandidateID, Name, Test1, Test2);
StudentResults.add(TestResult);
}
}
while (!Option1.equals("n"));
If you don't use the value inside the dummy variable, you can just execute sc.nextLine(); without assigning its return value to a variable.
It'll have the same effect, because the function is still being called.

Java-Returning an Array from an Array Method to the Main Function

public static public static void main(String[] args) {
System.out.print("Enter the number of student names to input: ");
int studentNum = new Scanner(System.in).nextInt();
String students[ ] = new String[studentNum];
for(int i = 0; i<studentNum; i++){
students[ i ] = inputStudent(i+1);
}
}
public static String[] inputStudent(int i) {
String studentNum[] = new String[i];
for(int a=0; a<i; a++) {
System.out.print("Enter student name"+(a+1)+": ");
studentNum[a]=new Scanner(System.in).nextLine();
}
return studentNum;
}
ERROR:
students[ i ] = inputStudent(i+1);
IT SAYS:
incompatible types: String[] cannot be converted to String
PS:
The main function should not be modified.
You are trying to assign String array to String
i.e
inputStudent(int i)
returns Array, but you are trying to assign Array to students[ i ] = inputStudent(i+1);
As
String[i] is the element String array which will accept String only
Change your method to this. You cannot assign a String array to a String. Also, why do you loop in your method? If I understand correctly you want to add n students to a student array? You loop in your main and method runs for each student.
public static String inputStudent(int i) {
System.out.print("Enter student name");
String studentName = new Scanner(System.in).nextLine();
return studentName;
}
Modify your input student method in such a way that it returns a single student only.
public static String inputStudent(int i) {
String studentNam = null;
System.out.print("Enter student name"+i+": ");
studentNum=new Scanner(System.in).nextLine();
return studentNum;
}
Since you stipulate that the main function can not be modified you are going to have to change the return type of your inputStudent function from String[] to String. This will mean you have to change how you are storing the data inside that function.
So, change the String studentNum[] to String studentNum and instead of asking for a new user input for every index of the array, ask for all inputs at once comma separated and store them in studentNum.
This is one possible approach according to your criteria.
I understand what you want to implement, the code below will solve your problem, every line of code has the explanation.
public static void main(String[] args) throws Exception {
System.out.print("Enter the number of student names to input: ");
Scanner scanner = new Scanner(System.in); // get the scanner
int numOfStudents = scanner.nextInt(); // get the number of students from user
String [] students = new String [numOfStudents]; // create an array of string
int studentAdded = 0; // counter
scanner = new Scanner(System.in); // recreate the scanner, if not it will skip the first student.
do {
System.out.println("Enter student name "+(studentAdded+1)+": ");
String studentName = scanner.nextLine(); // ask for student name
students[studentAdded] = studentName; // add student name to array
studentAdded++; // add 1 to the counter
} while (studentAdded < numOfStudents); // loop until the counter become the same size as students number
System.out.println("students = " + Arrays.toString(students)); // and show the result
}
What you can do to do is change:
students[ i ] = inputStudent(i+1);
to
students[ i ] = Arrays.toString(inputStudent(i + 1));
As students is a String you are unable to assign an array directly to a String. By using Array.toString() it will return a representation of the contents of the array as a String value.
Looking at your question again you are unable to modify the main. In this case we can set inputStudent to return a String type.
public static String inputStudent( int i )
{
String studentNum[] = new String[i];
for( int a = 0; a < i; a++ )
{
System.out.print( "Enter student name" + (a + 1) + ": " );
studentNum[a] = new Scanner( System.in ).nextLine();
}
return Arrays.toString(studentNum);
}
Or short and sweet.
public static String inputStudent( final int id )
{
System.out.print("Enter student name at ID: "+id+": ");
return new Scanner( System.in ).next();
}
You have an error in your code. For loop is not needed in main
public static public static void main(String[] args) {
System.out.print("Enter the number of student names to input: ");
int studentNum = new Scanner(System.in).nextInt();
String students[ ] = inputStudent(studentNum);
}
public static String[] inputStudent(int i) {
String studentNum[] = new String[i];
for(int a=0; a<i; a++) {
System.out.print("Enter student name"+(a+1)+": ");
studentNum[a]=new Scanner(System.in).nextLine();
}
return studentNum;
}

Printing specific user input in java

I have to design a program that gets 3 user-inputs in the form:
Name1 (any number of spaces) age1
Name2 (any number of spaces) age3
Name3 (any number of spaces) age3
Then print line which has the highest age (suppose Name3 age3 had the highest age I'd print his line).
My Code:
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String n2 = sc.nextLine();
String n3 = sc.nextLine();
}
}
I know how to scan the user-inputs, but i don't know how to do a comparison of the number within the acquired string to print a specific one (also since there can be any number of spaces it seems even more complicated to me).
You can use split to get the person's age:
String age = "Jon 57".split("\\s+")[1]; // contains "57"
You can then use Integer.parseInt(age) to get the person's age, as a number.
If you need to allow the user to input a name with spaces, you can adjust the number in square brackets ([]). For example, [2] would require the user to input a first name and last name.
Managed to do it with frenchDolphin's suggestion. This is the code i used (it's quite beginner friendly):
import java.util.*;
public class RankAge{
public static void main(String[] args){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n1 = sc.nextLine();
String a1 = n1.split("\\s+")[1];
String n2 = sc.nextLine();
String a2 = n2.split("\\s+")[1];
String n3 = sc.nextLine();
String a3 = n3.split("\\s+")[1];
if(Integer.parseInt(a1) > Integer.parseInt(a2)){
} if(Integer.parseInt(a1) > Integer.parseInt(a3)){
System.out.println(n1);
}else if(Integer.parseInt(a2) > Integer.parseInt(a3)){
System.out.println(n2);
}else{
System.out.println(n3);
}
}
}
+1 because at first look it seemed very simple but when I started implementing the complexities started showing up. Here is the complete solution for your problem,
import java.util.*;
public class RankAge {
public static void main(String s[]){
System.out.println("Enter 3 different names and the age of each person respectively:");
Scanner sc = new Scanner(System.in);
String n[] = new String[3];
for(int i=0;i<3;i++){
n[i] = sc.nextLine();
}
int age[] = new int[3];
age[0] = Integer.parseInt(n[0].split("\\s+")[1]);
age[1] = Integer.parseInt(n[1].split("\\s+")[1]);
age[2] = Integer.parseInt(n[2].split("\\s+")[1]);
int ageTemp[] = age;
for(int i=0;i<age.length;i++){
for(int j=i+1;j<age.length;j++){
int tempAge = 0;
String tempN = "";
if(age[i]<ageTemp[j]){
tempAge = age[i];
tempN = n[i];
age[i] = age[j];
n[i] = n[j];
age[j] = tempAge;
n[j] = tempN;
}
}
}
for(int i=0;i<3;i++){
System.out.println(n[i]);
}
}
}

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.

I need to create a program that will add, remove, list, save, and sort students in a created Student, Undergrad, and Graduate classes

I have three different classes, one for grad students, undergrads, and then a general student class, I need to figure out how to add students to an array list, from the main method. I can't figure out how to add a first name because it is private, and it needs to stay private.
package enrollmentdatabase;
import java.util.ArrayList;
import java.util.Scanner;
public class EnrollmentDataBase {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String option = optionChoise(input);
String option1 = "ADD";//ADD option
String option2 = "REMOVE";//REMOVE OPTION
String option3 = "LIST";//LIST OPTION
String option4 = "SAVE";//SAVE OPTION
String option5 = "SORT";//SORT OPTION
ArrayList studentList = new ArrayList();
}//end of main method
public static String optionChoise(Scanner input){
String opt1 = "ADD";//ADD option
String opt2 = "REMOVE";//REMOVE OPTION
String opt3 = "LIST";//LIST OPTION
String opt4 = "SAVE";//SAVE OPTION
String opt5 = "SORT";//SORT OPTION
System.out.println("Enter what you want to do(ADD, REMOVE, LIST, SAVE, or SORT): ");
String opt = input.nextLine();
if((opt.compareToIgnoreCase(opt1)) !=0 || (opt.compareToIgnoreCase(opt1)) != 0 || (opt.compareToIgnoreCase(opt1)) !=0
|| (opt.compareToIgnoreCase(opt1)) !=0 || (opt.compareToIgnoreCase(opt1)) !=0){//enter this if conditional in order to establish that the input is valid
System.out.println("This is not a valid input, please enter in what you want to do: ");
opt = input.nextLine();
}//end of if conditional
return opt;
}//end of option method
public static ArrayList addList(ArrayList studentList, Scanner input){
System.out.println("Enter the Student's first name: ");
String nameFirst= input.nextLine();
Student student1 = new Student();
student1.firstName = nameFirst;
System.out.println("Enter the Student's last name: ");
System.out.println("Enter the Student's UID: ");
System.out.println("Enter the Student's status: ");
System.out.println("Enter YES for having a thesis option, else NO: ");
System.out.println("Enter Masters for Master Studies of PHD for PHD studies: ");
System.out.println("Enter the name of the major professor: ");
System.out.println("Enter the student class standing: ");
System.out.println("Enter the Student's major: ");
System.out.println("Enter the student's overall GPA: ");
System.out.println("Enter the student's major GPA: ");
}//end of addList method
}//end of class
I can't figure out how to add a first name because it is private,
have public getter and public setter methods for that private data and access it through them.
For instance:
class Student {
private String fName;
public void setFname(String fName){
this.fName = fName;
}
public String getFName(){
return fname;
}
}
class AnotherClass {
public static void main(String...args){
student s = new Student();
System.out.println(s.getFName());//to access fName(which is private) in class Student.
}
}

Categories

Resources