so I'm just finishing up my first computer programming class ever and I'm having problems with my main method. I have 2 classes. The first class is homeClass.java and the other class is homeInventory.java. I'm just going to show you some of my homeInventory.java class unless you smarter ppl feel like it's prudent to have my other class. Basically, I'm having a problem with my else if statements. The program runs w/ the if statement, but won't completely run through the other options (else if). I must be missing something pretty apparent but I'll just see what you have to say on it. Thanks in advance!
public static void main(String[] args) {
ArrayList<homeClass> homes = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int i = 0;
int j = 0;
String option = "";
String answer = "";
String statusAnswer = "";
do {
System.out.println("Menu:");
System.out.println("1. Add a new home.");
System.out.println("2. Remove a home.");
System.out.println("3. Update home sale status.");
System.out.println("4. Exit");
System.out.print("Option chosen: ");
try {
while(true) {
if(scnr.hasNext()) {
option = scnr.next();
break;
}
}
}
catch (NoSuchElementException NSEE) {
continue;
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.print("Error, non-integer");
break;
}
try {
if(option.equals("1")) {
homes.add(addHome(scnr));
System.out.println("Home added.");
homes.get(i).getListing();
break;
}
else if (option.equals("2")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Remove this listing? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
homes.get(i).removeListing();
System.out.println("Home removed.");
}
else if (!answer.equalsIgnoreCase("Y")) {
System.out.println("Home not removed. Choose next option.");
}
}
break;
}
else if (option.equals("3")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Do you want to change the sale status? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter home sale status: ");
statusAnswer = scnr.next();
homes.get(i).setSaleStatus(statusAnswer);
homes.get(i).getListing();
}
}
break;
}
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.println("Error, option failed.");
}
} while(!option.equals("4"));
System.out.print("Do you want the home information stored in a file? Y or N: ");
answer = scnr.next();
String outputFileName = "C:\\Temporary\\Home.txt";
for (j = 0; j < homes.size(); ++j) {
String listing = homes.get(i).getListing();
if (answer.equalsIgnoreCase("Y")) {
try {
printToFile(listing, outputFileName);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("File printed to: " + outputFileName);
}
else {
System.out.println("File not printed.");
}
}
scnr.close();
return;
}
}
Related
I keep on having an error when I run a java file in android studio. I tried the invalidate caches/ restart but the error keeps persisting.
The code in the file is as follows:
import PreviousOrder.PreviousOrder;
import Signup.Signup;
import Login.*;
import Store.*;
import Admin.Admin;
import DateTime.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Project {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(new File("src\\Stock.txt"));
Scanner scan2 = new Scanner(new File("src\\Price.txt"));
Login l = new Login();
Signup s = new Signup();
Store st = new Store();
Admin adm = new Admin();
DateTime dt=new DateTime();
PreviousOrder pre=new PreviousOrder();
int[] sto = new int[9];
int[] price = new int[9];
int cart[]=new int[9];
int sto1[]=new int[9];
int bill=0;
int w = 0, q = -1;
String ch="50000";String c;
while (w != 9) {
sto[w] = Integer.parseInt(scan1.nextLine());
w++;
}
w=0;
while (w != 9) {
price[w] = Integer.parseInt(scan2.nextLine());
w++;
}
st.setstock(sto);
st.setprice(price);
Details d=new Details();
do {
System.out.println("\n1 for LOGIN\n2 for SIGN UP");
Thread.sleep(1000);
System.out.print("Enter your choice : ");
c = scan.next();
int f = 1, e = 1;
if (c.equals("1")) {
while (f != 2) {
q = l.check();
if (q != -1 && q!=-2) {
System.out.println("You are logged in successfully.");
System.out.println("Welcome again " + l.name[q]+"\n");
dt.DateTime(l.user[q]);
f = 2;
} else if(q==-2) {
System.out.println("Invalid Password or user name. Login Again.");
f = 1;
} else {
System.out.println("User name does not exist.please enter proper user name or sign up first.");
System.out.println("\n1 for LOGIN\n2 for SIGN UP");
System.out.print("Enter your choice : ");
int y=scan.nextInt();
if(y==1) {
f=1;
} else if(y==2) {
String u=s.add();
System.out.println("Signed up Successfully.Please Login again.");
}
else
{
System.out.println("Invalid choice.");
}
}
}
ch=c;
} else if (c.equals("2")) {
String u=s.add();
System.out.println("Signed up Successfully.Please Login again.");
while (e != 2) {
q = l.check();
if (q != -1) {
System.out.println("You are logged in successfully.");
System.out.println("Welcome " + l.name[q]);
dt.DateTime(l.user[q]);
e = 2;
} else {
System.out.println("Invalid Password or user name . Login Again.");
e = 1;
}
}
ch=c;
} else {
ch="50000";
System.out.println("Invalid choice.");
}
}while(ch.equals("50000"));
System.out.println("\n\n"+":::::::::USER INFORMATION::::::::::");
l.UserDetails(q);
System.out.println("\n \n");
int wasd=0;
pre.Order(l.name[q],cart,bill,wasd);
System.out.println("\n\n");
if (l.role[q].equals("admin")) {
String ro="5";
String rol;
d.details(sto,price);
do {
System.out.println("\n1 for Change in stock \n2 for Change in price \n0 for Exit");
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println(e);
}
System.out.print("Enter your choice : ");
rol=scan.next();
if(rol.equals("1")) {
sto=adm.changestock(sto);
st.setstock(sto);
} else if(rol.equals("2")) {
price=adm.changeprice(price);
st.setprice(price);
} else if(rol.equals("0")) {
ro="0";
} else {
System.out.println("Invalid choice.");
}
} while(ro.equals("5"));
}
System.out.println("WELCOME TO FASHION HUB");
d.details(sto,price);
sto1=sto;
cart=st.Buy(sto1,price);
bill=st.Bill(cart,price);
System.out.println("TOTAL :"+bill);
int cou=1;
String h="1",hi;
do {
System.out.println("Do you want to change in your cart ?"+"\n"+"1 YES "+"\n"+"2 NO");
scan.skip("\\n");
hi=scan.nextLine();
if(hi.equals("1")) {
cart=st.Changecart(cart,price,sto1);
bill=st.Bill(cart,price);
if(bill!=0) {
System.out.println("TOTAL :"+bill);
}
h="2";
} else if(hi.equals("2")) {
cou=0;
System.out.println("Please visit Again.");
h="2";
} else {
System.out.println("Invalid choice.");
h="1";
}
}while(h.equals("1"));
String bu=" ";
if(bill!=0) {
String bu1 = "0";
do {
System.out.println("DO YOU WANT TO BUY ? \n 1 YES \n 2 NO");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.print("Enter your choice : ");
bu = scan.next();
if (bu.equals("1")) {
for (int i = 0; i < 9; i++) {
sto[i] = sto1[i] - cart[i];
}
System.out.println("Your order will be deliver to following address.");
System.out.println(l.address[q]);
bu1 = "1";
} else if (bu.equals("2")) {
bu1 = "1";
} else {
System.out.println("Invalid choice");
}
} while (bu1.equals("0"));
}
if (bill == 0 && cou==1) {
System.out.println("Please visit Again.");
}
wasd=1;
if(bu.equals("1")) {
pre.Order(l.name[q],cart,bill,wasd);
}
st.setstock(sto);
st.setprice(price);
FileWriter fw = new FileWriter("src\\Stock.txt");
for (int i = 0; i < 9; i++) {
String a=Integer.toString(sto[i]);
fw.write(a);
fw.write("\n");
}
fw.close();
FileWriter fw1 = new FileWriter("src\\Price.txt");
for (int i = 0; i < 9; i++) {
String a=Integer.toString(price[i]);
fw1.write(a);
fw1.write("\n");
}
fw1.close();
}
}
The error displayed is:
java: Cannot run program "/home/astro/Android/Sdk/bin/java" (in directory "/home/astro/.cache/Google/AndroidStudio2020.3/compile-server"): error=2, No such file or directory
So I've been working on an assignment that requires us to build a "Patient manager", that bases which patient to be treated first based on the emergency level. The main issue I'm running into is that when the user enters something apart from a number into the emergency column, it crashes the program and gives me an InputMismatchException, despite with me attempting to catch it. Any ideas are greatly appreciated!
import java.util.*;
public class PatientManager {
private PriorityQueue<Patient> waitingList;
public PatientManager() {
waitingList = new PriorityQueue<Patient>();
}
// Starter method
public void start() {
String choice;
Scanner in = new Scanner(System.in);
String name;
int emergency = 0;
int order = 0;
Patient patient;
System.out.println("-------------------------------");
System.out.println("(1) New Patient.");
System.out.println("(2) Next Patient.");
System.out.println("(3) Waiting List.");
System.out.println("(4) Exit.");
System.out.println("-------------------------------");
while (true) {
System.out.print("* Choose an item from the menu:");
choice = in.next();
switch (choice) {
case "1":
System.out.println("Enter patient's name:");
name = in.next();
System.out.println("Enter emergency [1 (low) to 5 (life-and-death)]:");
while (true) {
try {
emergency = in.nextInt();
if (emergency >= 1 && emergency <= 5)
break;
else {
System.out.println("(x) Wrong value. Try again:");
emergency = in.nextInt();
}
} catch (Exception e) {
System.out.println("(x) Wrong value. Try again:");
emergency = Integer.parseInt(in.nextLine());
}
}
order++;
patient = new Patient(order, name, emergency);
waitingList.add(patient);
System.out.println("Patient added to the waiting list.");
break;
case "2":
if (waitingList.isEmpty()) {
System.out.println("No more patients.");
} else {
patient = waitingList.remove();
System.out.println(patient.getName() + " is treated.");
}
break;
case "3":
if (waitingList.size() == 0) {
System.out.println("No patients in the list.");
} else {
System.out.println("Waiting list includes:");
Iterator<Patient> iterator = waitingList.iterator();
while (iterator.hasNext()) {
patient = (Patient) iterator.next();
System.out.println("- " + patient.toString());
}
}
break;
case "4":
System.out.println("Program terminated. Good bye!!");
in.close();
System.exit(0);
break;
default:
System.out.println("(x) Wrong choice.");
break;
}
}
}
}
To start with, your code is much more complicated than it needs to be. Replace the whole while loop with this then test again.
while (emergency < 1 || emergency > 5) {
try {
emergency = in.nextInt();
if (emergency < 1 || emergency > 5)
System.out.println("(x) Wrong value. Try again:");
}
catch (Exception e) {
System.out.println("(x) Wrong value. Try again:");
}
}
I managed to fix it. I cleared the result of scanner by just adding in.next() into the catch block. So it looks like this:
catch (Exception e) {
System.out.print("(x) Wrong value. Try again:");
in.next();
System.out.println(emergency);
}
I have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.
I was having some problem when try to try catch the IndexOutOfBoundsException for a List in Java. So I declared my list with 2 elements as:
List<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Then I tried to do a try catch:
do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try{
option = sc.nextInt();
} catch (IndexOutOfBoundsException e){
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
type = list.get((option - 1));
} while (option <= 0 || option >= 3);
However, when I entered anything larger than 2 for option, it threw me IndexOutOfBounds exception but I thought I did a try catch for it already?
Thanks in advance.
do {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + (i + 1) + ")" + list.get(i));
}
System.out.println(" ");
try {
option = sc.nextInt();
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
sc.next();
continue;
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
sc.next();
continue;
}
sc.nextLine();
if (option == 1) {
System.out.print("Enter name: ");
// scanner takes in input
} else if (option == 2) {
System.out.print("Enter desc: ");
// scanner takes in input
}
try {
type = list.get((option - 1));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
option=3;
}
} while (option <= 0 || option >= 3);
I have added new try-catch at type = list.get((option - 1));
To force user re-input option, I will set option to 3 at the catch cause
You are not going to catch the exception if you don't use an invalid value to call the list.
ArrayList<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Scanner sc = new Scanner(System.in);
int option;
try {
option = sc.nextInt();
System.out.println(list.get(option));
} catch (IndexOutOfBoundsException e) {
System.out.println("Invalid option");
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
}
sc.close();
You also can do it like this, it will loop till you enter a valid value and after a valid value is entered ask for name or whatever(not implemented)
ArrayList<String> list = new ArrayList<>(Arrays.asList("item1", "item2"));
Scanner sc = new Scanner(System.in);
int option = 0;
while(!(option == 1 || option==2) ) {
try {
option = sc.nextInt();
} catch (InputMismatchException e) {
System.out.println("Option input mismatch.");
}
}
System.out.println(list.get(option-1));
sc.close();
it has been 7 days since i have been started coding this.. i really can't understand what is my codes problem. . . why does my switch case never work?? the menu just returns without performing the specific function of the case..
i really need to know what the problem is.
.
.
.
.
.
package dakilangtaoako;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DakilangTaoAko {
public static void main(String[] args){
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String mydata[][] = new String[5][3] ;
String inttoword [] = new String [5];
int wordtoint[] = new int [5];
int mychoice = 0, temp;
String toreturn = "";
for (int outside = 0; outside < 5; outside++){
System.out.println("Entry no." + (outside + 1));
for (int inside = 0; inside < 3; inside++){
if(inside == 0){
try {
System.out.print("Name: ");
mydata[outside][inside]= dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.parse("OK"), null, ex);
}
} else if(inside == 1){
try {
System.out.print("ID: ");
mydata[outside][inside]= dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.parse("OK"), null, ex);
}
}
else if(inside ==2){
try {
System.out.print("Subject: ");
mydata[outside][inside]= dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.parse("OK"), null, ex);
}
}
}
}
for(int i=0;i<5;i++){
wordtoint[i]=Integer.parseInt(mydata[i][1]);
}
while(mychoice != 5){
System.out.println("-------- DISPLAY OPTIONS --------");
System.out.println("\t [1] Display Entries Alphabetically ");
System.out.println("\t [2] Display Entries by Ascending ID number ");
System.out.println("\t [3] Display Students Enrolled in Prog2 ");
System.out.println("\t [4] Display Students Enrolled in CSO ");
System.out.println("\t [5] Exit ");
System.out.println();
System.out.print("\t Choice:");
try {
mychoice = dataIn.read();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.SEVERE, null, ex);
}
switch (mychoice){
case 1:
System.out.println("----Entries In Alphabetical Order----");
for(int outside=0;outside<5;outside++){
inttoword[outside]=Integer.toString(wordtoint[outside]);
}
for(int outside = 0; outside < 5; outside++)
{
for(int inside = 1 ; inside < 5; inside++)
{
if(inttoword[outside].compareToIgnoreCase(inttoword[inside])>0)
{
temp=wordtoint[outside];
wordtoint[outside]=wordtoint[inside];
wordtoint[inside]=temp;
}
}
}
for(int outside = 0; outside < 5; outside++){
for(int inside = 0; inside < 5; inside++){
if(wordtoint[outside] == Integer.parseInt(mydata[inside][0])){
System.out.println(mydata[outside][0] + ";" + mydata[inside][1]);
}
}
}
System.out.print("Press [r] to Return to Main Menu...");
try {
toreturn = dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.SEVERE, null, ex);
}
if("r".equals(toreturn))
break;
case 2:
System.out.println(" ---- Entries by Ascending ID Number ----");
for (int outside = 0; outside < 5; outside++){
for(int inside = 1; inside < 5; inside++){
if(wordtoint[outside]>wordtoint[inside]){
temp = wordtoint[outside];
wordtoint[outside]= wordtoint[inside];
wordtoint[inside]= temp;
}
}
}
for(int outside = 0; outside < 5; outside++){
for(int inside = 0; inside < 5; inside++){
if(wordtoint[outside] == Integer.parseInt(mydata[inside][1])){
System.out.println(mydata[outside][0] + ";" + mydata[inside][1]);
}
}
}
System.out.print("Press [r] to return to main Menu...");
try {
toreturn = dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.SEVERE, null, ex);
}
if("r".equals(toreturn))
break;
case 3:
System.out.println(" ---- Students Enrolled in Prog2 ----");
String mustfind1 = "PROG2";
for(int outside = 0; outside < 5; outside++){
if(mydata[outside][2].equalsIgnoreCase(mustfind1)){
System.out.println(mydata[outside][0]+";"+mydata[outside][1]);
}
System.out.print("Press [r] to Return to Main Menu...");}
try {
toreturn = dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.SEVERE, null, ex);
}
if("r".equals(toreturn))
break;
case 4:
System.out.println(" ---- Students Enrolled in CSO ---- ");
String mustfind2 = "CSO";
for(int outside = 0; outside < 5; outside++){
if(mydata[outside][2].equalsIgnoreCase(mustfind2))
System.out.println(mydata[outside][0]+";"+mydata[outside][1]);
}
System.out.print("Press [r] to Return to Main Menu...");
try {
toreturn = dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.SEVERE, null, ex);
}
if("r".equals(toreturn))
break;
case 5:
mychoice = 5;
break;
default:
System.out.println("Sorry the Number is Not in the Choices!!");
System.out.print("Press [r] to Return to Main Menu...");
try {
toreturn = dataIn.readLine();
} catch (IOException ex) {
Logger.getLogger(DakilangTaoAko.class.getName()).log(Level.SEVERE, null, ex);
}
if("r".equals(toreturn))
break;
} }
} }
Problem is here
mychoice = dataIn.read();
read would return single character and when it assign to int it would convert to corresponding ascii code
For example , if you enter 2 it would assign as 50 in mychocie 1 as 49 and so..
Change it to
mychoice = Integer.parseInt(dataIn.readLine());
Would read as string and convert into mychoice ( off course you need to press enter key after your choice )
or
change your switch conditions to 49,50,51,52,53
And you do have other issues such as
Integer.parseInt(mydata[inside][0])) which is name in your case 1
Update
I have modified your case 1
Arrays.sort(mydata,new Comparator<String[]>(){
#Override
public int compare(String[] entry1, String[] entry2){
// Compare Name
return entry1[0].compareToIgnoreCase(entry2[0]);
}
} );
for (String[] entry : mydata) {
System.out.println("Name :"+entry[0]+ ",ID :" +entry[1]+"Subject :"+entry[2]);
}
Here mydata is your String two dimensional array, when the comparator calls compare method, it would pass String[] thats is actual entry. So inside the compare compare the name (0) position.
Incase if you want to sort by id , you can use entry[1] in compare method and entry[2] for Subject
You can follow the same pattern for remaining.