dimanche 22 février 2015

Trouble reformatting code to include methods



Hi need to write this code so that it is broken up into methods correctly and I am lost. The methods I need to use are (as well as the main method etc):



menu()
string_function()
number_function()
create_username()


Here is what I have done, it is almost working code but it wont break up into a more modular state.



package testOne;


import java.io.*;
import java.util.Scanner;
public class MainMenu {

public static void main(final String[] args) {
System.out.print("Enter your full name: ");

final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String me = null;

try {
me = br.readLine();
} catch (final IOException ioe) {
System.out.println("Error trying to read your name");
System.exit(1);
}

System.out.println();
System.out.println("Thank you, " + me +".");
System.out.println();
System.out.println ("Please choose from one of the following options:");
System.out.println();
System.out.println("1 = create new user");
System.out.println("2 = do maths");
System.out.println("3 = exit");

int choice = 0;
final Scanner scanchoice = new Scanner(System.in);

while (choice != 3) {



System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\":");
choice = scanchoice.nextInt();

switch (choice) {
case 1: create_name();
break;
case 2: Factorial();
break;
case 3: System.out.println("Thanks for using this programme");
System.exit(0);
break;
default: System.out.println("I am sorry, please enter 1, 2 or 3");
break;
}




}//WHILE LOOP BRACKET

scanchoice.close();

}//MAIN METHOD BRACKET

public static void Factorial() {
// TODO Auto-generated method stub


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println("The factorial of " + n + " is " + result);
return;
}

public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}

public static void create_name() {
System.out.print("Enter name: ");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String fullName = null;

try {
fullName = br.readLine();
}
catch (IOException ioe) {
System.out.println("Error trying to read your name");
System.exit(1);
}

int spacePos = fullName.indexOf(" ");

String firstName = fullName.substring(0, 1);
String secondInitial = fullName.substring(spacePos+1, spacePos+6);
String userName = firstName.concat(secondInitial);

System.out.println("Hello. Your username is " + userName);
}
}


I really need help here!




Aucun commentaire:

Enregistrer un commentaire