The initial output of the texfile is this. NO ARRAYLIST OR COMPARATOR IS ALLOWED:
Steve Jobs 9 f 91
Bill Gates 6 m 90
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Steve Jobs 9 m 95
Dennis Ritchie 5 f 100
Jeff Dean 7 m 100
Bill Gates 6 f 96
Jeff Dean 7 f 100
Sergey Brin 27 f 97
Sergey Brin 22 m 98
The collateExams method collates/sorts exam objects starting with the first 'm' (midterm) of the first object and immediately followed by the same person's 'f'(final). Only a SINGLE loop construct is allowed. The output from collateExams() should be the one below but my code is not working, i.e. collateExams method is not working. Could smb help me with that? The output from collateExams() should be
Bill Gates 6 m 90
Bill Gates 6 f 96
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Dennis Ritchie 5 f 100
Steve Jobs 9 m 95
Steve Jobs 9 f 91
Jeff Dean 7 m 100
Jeff Dean 7 f 100
Sergey Brin 22 m 98
Sergey Brin 27 f 97
Im getting NullExceptions at
r[2*position[exams[i].getID()]+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
import java.io.*;
import java.util.*;
class P2 {
public static void main(String [] args) throws FileNotFoundException
{
Scanner data = new Scanner(new File("Exam.txt"));
Exam[] readObjects = readAllExams(data);
Exam[] collateObjects = collateExams(readObjects);
System.out.println("1) Initially the list of exams of students is: ");
System.out.println();
for(int i = 0; i < readObjects.length; i++)
{
System.out.println(readObjects[i]);
}
System.out.println();
System.out.println("Sorted list: ");
for (int i = 0; i < collateObjects.length; i++)
{
System.out.println(collateObjects[i]);
}
}
public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted;
int score = 0;
int index = 0;
Exam[] object = new Exam[s.nextInt()];
while(s.hasNext())
{
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
else
s.next();
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
//Exam[] object = new Exam[s.nextInt()];
object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
//System.out.println();
index++;
}
readExam(s);
return object;
}
public static Exam readExam(Scanner s)
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted = 0;
int score = 0;
while (s.hasNext())
{
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
}
Exam temp = new Exam(firstName, lastName, ID, examTypeCasted, score);
return temp;
}
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int [] position = new int[exams.length];
int index = 0;
for (int i = 0; (i < exams.length) && (i < position.length); i++)
{
position[i] = -1;
if(exams[i].getExamType()=='m')
{
if(position[exams[i].getID()]==-1)
{
r[index*2] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
position[exams[i].getID()] = 2*index;
}
else
r[2*position[exams[i].getID()] - 1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
}
else
{
if(position[exams[i].getID()]==-1)
{
r[index*2+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
position[exams[i].getID()] = 2*index+1;
}
else
r[2*position[exams[i].getID()]+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
}
index++;
}
return r;
}
}
This is absolute and complete kluge, but it meets your criteria. If this doesn't work for you then you would have to look at object creation or something else to fit your needs.
static int maxId = 0;
public static void main(String [] args) throws FileNotFoundException
{
Scanner data = new Scanner(Answer28522397.class.getClassLoader().getResourceAsStream("exams.txt"));
Exam[] readObjects = readAllExams(data);
System.out.println("1) Initially the list of exams of students is: ");
System.out.println();
for(int i = 0; i < readObjects.length; i++)
{
System.out.println(readObjects[i]);
}
Object[][] collatedObjects = collateExams(readObjects);
System.out.println("");
System.out.println("Sorted list: ");
for (int i = 0; i < collatedObjects.length; i++)
{
if (collatedObjects[i][0] != null && collatedObjects[i][1] != null)
{
System.out.println(collatedObjects[i][0]);
System.out.println(collatedObjects[i][1]);
}
}
}
public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
{
int index = 0;
Exam[] object = new Exam[s.nextInt()];
while(s.hasNext())
{
Exam e = readExam(s);
maxId = e.getID() > maxId ? e.getID() : maxId;
object[index] = e;
index++;
}
return object;
}
public static Exam readExam(Scanner s)
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted = 0;
int score = 0;
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
return new Exam(firstName, lastName, ID, examTypeCasted, score);
}
public static Object[][] collateExams(Exam[] exams)
{
Exam [] r = new Exam[exams.length];
System.arraycopy(exams, 0, r, 0, exams.length);
Object[][] collation = new Object[maxId+1][2];
for(Exam exam : exams)
{
if (exam.getExamType() == 'm')
{
collation[exam.getID()][0] = exam;
}
else
{
collation[exam.getID()][1] = exam;
}
}
return collation;
}
Related
I have a final assignment in my Java class. I am not understanding and my teacher blows. please help!!
Here is the assignment:
I am having trouble doing the sort by GPA like the assignment says it needs to be in GPA sequence.
Here is the first file:
5
Aaron
Smith
4
Dallas
Lambert
3
Mike
Scott
2
George
Mcfly
1
Greg
Peterson
Here is the second file:
1
4
3.2
2
5
2.2
3
6
3.0
4
3
4.0
5
2
3.5
note the first data element in both files is student number.
Here is my program code:
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first file name: ");
String firstFile = "/Volumes/Sandisk/Personal/" + scanner.next();
File file = new File(firstFile);
FileReader fileReader = new FileReader(firstFile);
BufferedReader buffReader = new BufferedReader(fileReader);
//Second File input
Scanner scannerTwo = new Scanner(System.in);
System.out.print("Enter second file name: ");
String secondFile = "/Volumes/Sandisk/Personal/" + scannerTwo.next();
File fileTwo = new File(secondFile);
FileReader fileReaderTwo = new FileReader(secondFile);
BufferedReader buffReaderTwo = new BufferedReader(fileReaderTwo);
int studentNum;
int studentNumTwo;
String name;
String lname;
int classHour;
double grade;
int index = 0;
int indexTwo = 0;
double GPA;
double points;
String letterGrade;
//arrays
int[] studentNumArray = new int[20];
int[] studentNumTwoArray = new int[20];
String[] nameArray = new String[20];
String[] lnameArray = new String[20];
int[] classHourArray = new int[20];
double[] gradeArray = new double[20];
double[] GPAArray = new double[20];
String[] letterGradeArray = new String[20];
//first file
for (String numParse = buffReader.readLine(); numParse != null; numParse = buffReader.readLine()) {
studentNum = Integer.parseInt(numParse);
studentNumArray[index] = studentNum;
name = buffReader.readLine();
nameArray[index] = name;
lname = buffReader.readLine();
lnameArray[index] = lname;
index++;
}
//read file 2
for (String numTwoParse = buffReaderTwo.readLine(); numTwoParse != null; numTwoParse = buffReaderTwo.readLine()) {
studentNumTwo = Integer.parseInt(numTwoParse);
studentNumTwoArray[indexTwo] = studentNumTwo;
String classParse = buffReaderTwo.readLine();
classHour = Integer.parseInt(classParse);
classHourArray[indexTwo] = classHour;
String gradeParse = buffReaderTwo.readLine();
grade = Double.parseDouble(gradeParse);
gradeArray[indexTwo] = grade;
//GPA
points = grade * classHour;
GPA = points / classHour;
GPAArray[indexTwo] = GPA;
//Grade
if(GPA >= 4.0){
letterGrade="A";
letterGradeArray[indexTwo]=letterGrade;
}
if (GPA < 4.0 && GPA >= 3.4) {
letterGrade = "A";
letterGradeArray[indexTwo] = letterGrade;
}
if (GPA < 3.4 && GPA >= 2.7) {
letterGrade = "B";
letterGradeArray[indexTwo] = letterGrade;
}
if (GPA < 2.7 && GPA >= 2.0) {
letterGrade = "C";
letterGradeArray[indexTwo] = letterGrade;
}
if (GPA < 2.0 && GPA >= 1.2) {
letterGrade = "D";
letterGradeArray[indexTwo] = letterGrade;
}
if (GPA < 1.2 && GPA >= 0.1) {
letterGrade = "F";
letterGradeArray[indexTwo] = letterGrade;
}
if (GPA < 0.1) {
letterGrade = "NONE";
letterGradeArray[indexTwo] = letterGrade;
}
indexTwo++;
}
//final sort by GPA
double temp2;
int length2 = GPAArray.length;
for(int i = 0; i<length2; i++){
for(int j =i+1; j<length2; j++){
if(GPAArray[i]< GPAArray[j]){
temp2=GPAArray[i];
GPAArray[i]=GPAArray[j];
GPAArray[j]=temp2;
String temp6;
temp6=letterGradeArray[i];
letterGradeArray[i]=letterGradeArray[j];
letterGradeArray[j]=temp6;
int temp7;
temp7=studentNumTwoArray[i];
studentNumTwoArray[i]=studentNumTwoArray[j];
studentNumTwoArray[j]=temp7;
int temp3;
temp3=studentNumArray[i];
studentNumArray[i]=studentNumArray[j];
studentNumArray[j]=temp3;
}
}
}
studentNumArray=studentNumTwoArray.clone();
System.out.printf("%40s\n", "Student Report");
System.out.printf("%-20s %10s %15s %15s\n", "Student Number", "Student Name", "GPA", "Grade");
System.out.println("_______________________________________________________________________");
for (int i = 0; i < studentNumArray.length; i++) {
if (nameArray[i] != null) {
System.out.printf("%-18d %-1s %-18s %-20.2f %-10s\n",
studentNumTwoArray[i], nameArray[i], lnameArray[i], GPAArray[i], letterGradeArray[i]);
}
}
}
Please help if you are willing.
So, basically I have an assignment that requires for me to Write a java program to help maintain a class roll. The program must contain four classes: Student, Exams, ClassRoll and Assignment4(Main).
I have developed all the classes but the ClassRoll constructor it s not performing correctly. When I run the program I am prompted with the file name option, once i enter the file name I see null then the options to modify and / or display the list, but when I enter a command, it does not work, it gives me an error.
The Output should be
Expected input/output:
Assuming that the file data.txt contains:
COP2210
John Doe 50 60 70
Marco Boyle 50 60 73
Eric Munzon 45 100 90
Marry Able 95 100 100
Jack Smith 100 100 100
Elizabeth Gomez 100 100 100
The following is a sample input output run:
What is the name of input file: data.txt
Enter one of the following commands
a or add to add a student in the class roll
sa or average to sort the students based on their average
sn or names to sort the students based on their last names
r or remove to remove a student from the class roll
s or save to save the list of students back to the datafile
Here are my classes;
public class Student {
private String fName = "";
private String lName = "";
private Exam scores;
public Student(String f, String l){
fName=f;
lName=l;
scores = new Exam();
}
public void setScore1(int score) {
scores.setScore1(score);
}
public void setScore2(int score) {
scores.setScore2(score);
}
public void setScore3(int score) {
scores.setScore3(score);
}
public String toString() {
return lName + "\t" + fName + "\t" +
scores.toString();
}
public double getAverage() {
return (scores.getScore1() + scores.getScore2() +
scores.getScore3())/3.0;
}
public boolean equals(String f, String l) {
return f.equals(fName) && l.equals(lName);
}
public int compareTo(Student s){
if (lName.compareTo(s.lName) > 0)
return 1;
else if (lName.compareTo(s.lName) < 0)
return -1;
else if (fName.compareTo(s.fName) > 0)
return 1;
else if (fName.compareTo(s.fName) < 0)
return -1;
else return 0;
}}
public class Exam {
private int score1;
private int score2;
private int score3;
public Exam(){
score1=0;
score2=0;
score3=0;
}
public void setScore1(int score) {
score1=score;
}
public int getScore1() {
return score1;
}
public void setScore2(int score) {
score2=score;
}
public int getScore2() {
return score2;
}
public void setScore3(int score) {
score3=score;
}
public int getScore3() {
return score3;
}
public String toString() {
return Integer.toString(score1) + "\t"
+Integer.toString(score2)
+ "\t" + Integer.toString(score3) + "\t";
}}
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
Scanner fileScan, lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Title =" + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student s = new Student(firstName, lastName);
s.setScore1(lineScan.nextInt());
s.setScore2(lineScan.nextInt());
s.setScore3(lineScan.nextInt());
students.add(s);
//display(students);
ClassRoll c = new ClassRoll();
c.display();
}
}
void display() {
DecimalFormat fmt = new DecimalFormat("0.00");
System.out.println("\t\t\t" + title);
double classAverage = 0.0;
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
System.out.print(s.toString());
System.out.println("\t" + fmt.format(s.getAverage()));
classAverage = classAverage + s.getAverage();
}
System.out.println("\t\t\t" + fmt.format(classAverage /
students.size()));
}
public void insert() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
System.out.print("Score 1 -> ");
int score1 = input.nextInt();
System.out.print("Score 2 -> ");
int score2 = input.nextInt();
System.out.print("Score 3 -> ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
private int search(String f, String l) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(f, l)) {
return i;
} else {
i++;
}
}
return -1;
}
public Student find() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}}
public void delete() {
Scanner input = new Scanner(System.in);
System.out.print("First Name -> ");
String firstName = input.next();
System.out.print("Last Name -> ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student not found");
}
}
public void sortLastNames() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}
}}
public void sortAverage() {
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}}
public void save() throws IOException {
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
}
out.close();
}}
public class Assignment4bis {
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
System.out.print("Enter the name of the input file ->");
String fileName=input.next();
ClassRoll c = new ClassRoll();
c.display();
prompt();
System.out.print("Enter a command --> ");
String ans=input.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("i") ||ans.equalsIgnoreCase("insert") ||
ans.equalsIgnoreCase("a") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("n") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (ans.charAt(0))
{
case 'i': c.insert();
break;
case 'a': c.sortAverage();
c.display();
break;
case 'n': c.sortLastNames();
c.display();
break;
case 'r': c.delete();
c.display();
break;
case 'f': Student s=c.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 'd': c.display();
break;
}
prompt();
System.out.print("Enter a command --> ");
ans=input.next();
}
c.save();
System.out.println("Thank you for using this program");
}
public static void prompt(){
System.out.println("Enter one of the following commands");
System.out.println("i or insert to insert a student in the class
roll");
System.out.println("a or average to sort the students based on
their average");
System.out.println("n or names to sort the students based on their
last names");
System.out.println("r or remove to remove a student from the class
roll");
System.out.println("f or find to find a student in the class
roll");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");
}}
Errors that I m still getting...
run:
Enter the name of the input file ->data.txt
Title =COP2210
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at assignment4bis.ClassRoll.<init>(ClassRoll.java:40)
at assignment4bis.Assignment4bis.main(Assignment4bis.java:28)
Java Result: 1
Your ClassRoll "constructor" is a "pseudo-constructor":
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public void ClassRoll(String f) throws IOException {
Constructors have no return type, so get rid of the void:
public class ClassRoll {
ArrayList students = new ArrayList();
String title;
String fileName;
public ClassRoll(String f) throws IOException {
As a bit of side recommendations:
You look to be mixing user interface with one of your "model" or logical classes, ClassRoll, something you probably shouldn't do. I'd keep all user interface code, including use of a Scanner and File I/O separate from ClassRoll, which likely should just have code to create the collection, to allow other classes to add or remove from the collection, and to allow other classes to query the collection.
Take care to learn and follow Java code formatting rules. You've got some deviations from the standard, including have your class declaration lines indented the same as the method body and variable declaration lines, bunching up of end braces,... This makes your code hard for other Java coders to read and understand.
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
Code and Snap of the Exception are attached. Pls Help me out with InputMismatchException. I believe there is something wrong while entering the value at runtime
import java.util.Scanner;
class ObjectArray
{
public static void main(String args[])
{
Scanner key=new Scanner(System.in);
Two[] obj=new Two[3];
for(int i=0;i<3;i++)
{
obj[i] = new Two();
obj[i].name=key.nextLine();
obj[i].grade=key.nextLine();
obj[i].roll=key.nextInt();
}
for(int i=0;i<3;i++)
{
System.out.println(obj[i].name);
}
}
}
class Two
{
int roll;
String name,grade;
}
Instead of :
obj[i].roll=key.nextInt();
Use:
obj[i].roll=Integer.parseInt(key.nextLine());
This ensures the newline after the integer is properly picked up and processed.
use Integer.parseInt(key.nextLine());
public class ObjectArray{
public static void main(String args[]) {
Scanner key = new Scanner(System.in);
Two[] obj = new Two[3];
for (int i = 0 ; i < 3 ; i++) {
obj[i] = new Two();
obj[i].name = key.nextLine();
obj[i].grade = key.nextLine();
obj[i].roll = Integer.parseInt(key.nextLine());
}
for (int i = 0 ; i < 3 ; i++) {
System.out.println("Name = " + obj[i].name + " Grade = " + obj[i].grade + " Roll = " + obj[i].roll);
}
}
}
class Two {
int roll;
String name, grade;
}
output
a
a
1
b
b
2
c
c
3
Name = a Grade = a Roll = 1
Name = b Grade = b Roll = 2
Name = c Grade = c Roll = 3
import java.util.Scanner;
public class TestPerson
{
/**
* Creates a new instance of <code>TestPerson</code>.
*/
public TestPerson()
{
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Menus[] menu = { new Menus("Add Member") };
MemberType[] m = { new MemberType("Corporate Member"), new MemberType("VIP Member") };
Clubs[] c = { new Clubs("Yoga", "Miss AA"), new Clubs("Kick-boxing", "Mr.AA"), new Clubs("aerobics", "Mrs.Wendy") };
RegMember[] r = new RegMember[1];
Cmember cm;
Vipmember vip;
Scanner s = new Scanner(System.in);
int choice = 0;
for (int z = 0; z < menu.length; z++)
{
System.out.println((z + 1) + ". " + menu[z].toString());
}
System.out.println("\nEnter Your selection:");
int choice = s.nextInt();
while (choice == 1)
{
for (int i = 0; i < r.length; i++)
{
System.out.println("\nYour reg no is :" + (RegMember.getNextNo() + 1));
for (int a = 0; a < m.length; a++)
{
System.out.println((a + 1) + ". " + m[a].toString());
}
System.out.println("\nEnter Your selection:");
int sel = s.nextInt();
if (sel == 1)
{
s.nextLine();
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Company Name:");
String CompanyName = s.nextLine();
String memberType = "Corporate Member";
for (int b = 0; b < c.length; b++)
{
System.out.println((b + 1) + ". " + c[b].toString());
}
System.out.println("\nEnter Your selection:");
int sel2 = s.nextInt();
String clubs = "Yoga";
cm = new Cmember(Name, Hpnum, age, CompanyName, memberType, clubs);
r[i] = new RegMember(cm);
}
else
{
s.nextLine();
System.out.println("---You will get a free exercise class---");
System.out.println("Enter name:");
String Name = s.nextLine();
System.out.println("Enter Handphone:");
String Hpnum = s.next();
System.out.println("Enter Age:");
int age = s.nextInt();
System.out.println("Enter Email:");
String email = s.next();
String memberType = "VIP Member";
vip = new Vipmember(Name, Hpnum, age, email, memberType);
r[i] = new RegMember(vip);
}
s.nextLine();
}
}
displayInfor(r);
}
public static void displayInfor(RegMember[] r)
{
for (int i = 0; i < r.length; i++)
System.out.println(r[i].toString());
}
}
I am a beginner for java. I am facing the problem that my code is continue looping.How to solve it?? thank you.
Your choice variable is never set to not = 1. Therefore the while loop will continue to run forever.
edit: With the amount of log messages in that code you should be able to see where surely.
If you are using If statements as such why not just alter the choice variable manually.
Anyway its too vague your question specify which loop and it would be easier to help