How to alphabetize strings in Java using functions - java

import java.util.Scanner;
public class alphabetical {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner Alphabet= new Scanner(System.in);
System.out.println("Input First Name");
String UserInput= Alphabet.next();
System.out.println("Input second name");
String UserInput2= Alphabet.next();
System.out.println("Input third name");
String UserInput3= Alphabet.next();
System.out.println(alpha)UserInput,UserInput2,UserInput3));
}
public static void alpha(String fromUser,String fromUser2, String fromUser3)
{
if (fromUser.compareTo(fromUser2)>0)
{
System.out.println(fromUser2);
}
else if(fromUser.compareTo(fromUser3)>0)
{
System.out.println(fromUser3);
}
else if (fromUser2.compareTo(fromUser3)>0)
{
System.out.println(fromUser3);
}
else if (fromUser2.compareTo(fromUser)>0)
{
System.out.println(fromUser);
}
else if (fromUser3.compareTo(fromUser)>0)
{
System.out.println(fromUser);
}
else if (fromUser3.compareTo(fromUser2)>0)
{
System.out.println(fromUser2);
}
}
}
So that's my code but I don't know what I'm doing wrong. I've been working on this for a while and I need a code that will allow the user to input 3 names and then sort the names in alphabetical order
The requirements for this program is to have the user input 3 strings and print them out ordered alphabetically using a function that takes 3 strings-- the return type should be void-- this means that there nothing returned back to main, the function will just print out the three words in alphabetical order there should be 6 cases you need to worry about (think If, elseif...else).
Here is what a sample output might look like in the console (> denotes it's in the console-- you won't actually see this):
input first lowercase string
awesome
input second lowercase string
bogus
input third lowercase string
chillin
(THE FOLLOWING HAPPENS IN THE VOID FUNCTION)
Here are your words in alphabetical order
awesome
bogus
chillin

If you're really not allowed to use arrays or lists, I hope your professor is making you write a long-winded solution, so that he can "reveal" the better, array or list based version later.
For three items, it's true that there are six cases, and you can "just" write an if/else clause for each one:
// case 1 - abc
if(lessThan(a,b) && lessThan(b,c)) {
System.out.println(a + " " + b + " " + c);
}
// case 2 - acb
else if(lessThan(a,c) && lessThan(c,b)) {
System.out.println(a + " " + c + " " + b);
}
// case 3 - bac
else if(lessThan(b,a) && lessThan(a,c)) {
System.out.println(b + " " + a + " " + c);
}
... and so on, for each of abc,acb,bac,bca,cab,cba. For my own sanity I've assumed the existence of a lessThan() method containing a.compareTo(b) < 0 -- but you could use compareTo() directly if your professor also forbids you writing helper methods.
Because of the wording of the question, I guess this is what's expected -- it's not a sensible way to implement a sort, but it could be the basis on which to build something better. It does also allow you to directly count how many comparisons are being made, which could lead to some beginner's insight into the cost of an algorithm.
If you're allowed to use an array, and you're allowed to use a sort routine provided by Java, then just put the values into an array, sort it and print it:
public static void alpha(String a,String b, String c) {
String[] array = new String[] {a,b,c};
Arrays.sort(array);
System.out.println(array[0] + " " + array[1] + " " + array[2]);
}

In java 8 it is simple. You can sort collection of strings with lambda:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner Alphabet = new Scanner(System.in);
System.out.println("Input First Name");
String UserInput = Alphabet.next();
System.out.println("Input second name");
String UserInput2 = Alphabet.next();
System.out.println("Input third name");
String UserInput3 = Alphabet.next();
List<String> list = Arrays.asList(UserInput, UserInput2, UserInput3);
list.sort((String in1, String in2) -> in1.compareTo(in2));
list.forEach(System.out::println);
}

So you can use anything as long as you put it in a method ...
public static void alpha(String fromUser,String fromUser2, String fromUser3){
String[] sArray = {fromUser, fromUser2, fromUser3};
Arrays.sort(sArray);
for (String s : sArray){
System.out.print(s + " ");
}
}

Using java 8 streams you can do it like that:
public static void alpha(String fromUser,String fromUser2, String fromUser3) {
Stream.of(fromUser, fromUser2, fromUser3).sorted().forEach(System.out::println);
}

You're close, but you need to be comparing your String to both other Strings before producing your output. One approach is to create an individual if/else if/else block for each of your three lines of output. For example, here's the middle line given Strings s1, s2, s3.
// First Word
. . .
// Second Word
if ( (s1.compareTo(s2) >= 0) && (s1.compareTo(s3) <= 0) ) {
System.out.println(s1);
} else if ( (s2.compareTo(s1) >= 0) && (s2.compareTo(s3) <= 0) ) {
System.out.println(s2);
} else {
System.out.println(s3);
}
// Third Word
. . .
Another approach is to account for every permutation of how three things can be arranged. {abc, acb, bac, bca, cab, cba }. This is manageable when you have only three things to arrange, but gets quite nasty when you add more.
if ( (s1.compareTo(s2)<=0) && (s1.compareTo(s3)<=0) && (s2.compareTo(s3)<=0) ) {
// abc
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
} else if (s1.compareTo(s2)<=0) && (s1.compareTo(s3)<=0) && (s2.compareTo(s3)>=0) {
// acb
System.out.println(s1);
System.out.println(s3);
System.out.println(s2);
} else if . . .

Related

How to make this code decline String other than q

I still a little bit new so I'm going to include all of my java code and then explain what I am looking for.
import java.util.Scanner;
public class Part_I{
public static Scanner input = new Scanner(System.in);
public static String strInfo;
public static int number;
public static void main(String[] args){
String presidents[][] = {
{"1 ","George"," ","Washington"," (1789-1797) ","John Adams"},
{"2 ","John"," ","Adams"," (1797-1801) ","Thomas Jefferson"},
{"3 ","Thomas"," ","Jefferson"," (1801-1809) ","Aaron Burr"},
{"4 ","James"," ","Madison"," (1809-1817) ","George Clinton"},
{"5 ","James"," ","Monroe"," (1817-1825) ","Daniel D. Tompkins"},
{"6 ","John"," Quincy ","Adams"," (1825-1829) ","John C. Calhoun"},
{"7 ","Andrew"," ","Jackson"," (1829-1837) ","John C. Calhoun"},
{"8 ","Martin"," Van ","Buren"," (1837-1841) ","Richard M. Johnson"},
{"9 ","William"," Henry ","Harrison"," (1841) ","John Tyler"},
{"10 ","John"," ","Tyler"," (1841-1845) ","None"},
{"11 ","James"," K. ","Polk"," (1845-1849) ","George M. Dallas"},
{"12 ","Zachary"," ","Taylor"," (1849-1850) ","Millard Fillmore"},
{"13 ","Millard"," ","Fillmore"," (1850-1853) ","None"},
{"14 ","Franklin"," ","Pierce"," (1853-1857) ","William King"},
{"15 ","James"," ","Buchanan"," (1857-1861) ","John C. Breckinridge"},
{"16 ","Abraham"," ","Lincoln"," (1861-1865) ","Hannibal Hamlin"},
{"17 ","Andrew"," ","Johnson"," (1865-1869) ","None"},
{"18 ","Ulysses"," S. ","Grant"," (1869-1877) ","Schuyler Colfax"},
{"19 ","Rutherford"," B. ","Hayes"," (1877-1881) ","William Wheeler"},
{"20 ","James"," A. ","Garfield"," (1881) ","Chester Arthur"},
{"21 ","Chester"," ","Arthur"," (1881-1885) ","None"},
{"22 ","Grover"," ","Cleveland"," (1885-1889) ","Thomas Hendricks"},
{"23 ","Benjamin"," ","Harrison"," (1889-1893) ","Levi P. Morton"},
{"24 ","Grover"," ","Cleveland"," (1893-1897) ","Adlai E. Stevenson"},
{"25 ","William"," ","McKinley"," (1897-1901) ","Garret Hobart"},
{"26 ","Theodore"," ","Roosevelt"," (1901-1909) ","None"},
{"27 ","William"," Howard ","Taft"," (1909-1913) ","James S. Sherman"},
{"28 ","Woodrow"," ","Wilson"," (1913-1921) ","Thomas R. Marshall"},
{"29 ","Warren"," G. ","Harding"," (1921-1923) ","Calvin Coolidge"},
{"30 ","Calvin"," ","Coolidge"," (1923-1929) ","None"},
{"31 ","Herbert"," ","Hoover"," (1929-1933) ","Charles Curtis"},
{"32 ","Franklin"," D. ","Roosevelt"," (1933-1945) ","John Nance Garner"},
{"33 ","Harry"," S. ","Truman"," (1945-1953) ","None"},
{"34 ","Dwight"," D. ","Eisenhower"," (1953-1961) ","Richard Nixon"},
{"35 ","John"," F. ","Kennedy"," (1961-1963) ","Lyndon B. Johnson"},
{"36 ","Lyndon"," B. ","Johnson"," (1963-1969) ","None"},
{"37 ","Richard"," ","Nixon"," (1969-1974) ","Spiro Agnew"},
{"38 ","Gerald"," ","Ford"," (1974-1977) ","Nelson Rockefeller"},
{"39 ","Jimmy"," ","Carter"," (1977-1981) ","Walter Mondale"},
{"40 ","Ronald"," ","Reagan"," (1981-1989) ","George Bush"},
{"41 ","George"," ","Bush"," (1989-1993) ","Dan Quayle"},
{"42 ","Bill"," ","Clinton"," (1993-2001) ","Al Gore"},
{"43 ","George"," W. ","Bush"," (2001-2009) ","Dick Cheney"},
{"44 ","Barack"," ","Obama"," (2009-2017) ","Joe Biden"},
};
System.out.println("This will display the President and VP of the United States based on the number you provide.");
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
public static boolean isInteger(String strInfo){
if (strInfo == null) {
return false;
}
int length = strInfo.length();
if (length == 0) {
return false;
}
int i = 0;
if (strInfo.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = strInfo.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}
My main concern is with the while loop.
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
I want to make it so that it any string other than what is able to be converted to an int or "q" would say wrong input and make you input another string value. Right now, any string will make the program terminate. What should I change in that while loop and how should I change it or what should it look like instead so that if the string input is not q or convertible to an int will make wrong input display and ask for input again?
This will help you in achieving what you want to do
while (!strInfo.equals("q")) {
if (isInteger(strInfo)) {
number = Integer.parseInt(strInfo);
if (number >= 1 && number <= 44) {
System.out.println();
System.out.println(presidents[number - 1][0] + "President " + presidents[number - 1][1] + presidents[number - 1][2] + presidents[number - 1][3] + presidents[number - 1][4] + "Vice President " + presidents[number - 1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
You shouldn't check string equality using normal operators like "=" and "!=". Use the String .equals() method.
So your first line would be
while(!strInfo.equals("q"))
More info:
http://www.leepoint.net/data/expressions/22compareobjects.html
The reason your code is not working is because you are trying to compare whether the contents of two strings are equal using == operator (which only compares if the two references point to the same object). == Operator does not compare the contents of the two strings.
In order to make your code work, you would need to use equals to compare the contents of the two strings as follows :
while(!strInfo.equals("q"))
Now lets try to delve deep into why your code is not working. For that we need to understand the basic difference between == & equals
== Operator is used to compare if both the references on its either side point to the same object (Basically you can say its similar to
comparing address of the object to which the references point to).
Whereas equals in case of String compares the content of the two Strings. It is the responsibility of the creator of the class to override the default equals method to compare the objects of that class depending on what makes sense for that object. For example in case of String class the creators of the class have overriden the equals method to compare the contents of the Strings.
String a = "test"; // lets say the object guy has address : 24
String b = a; // now b points to the same object that is being referenced by a
System.out.println(a == b); // this will be true as both point to the same reference
System.out.println(a.equals(b)); // this will be true as the contents of both these strings is the same.
// Now lets consider a new strings having same content "test"
String c = "test";
System.out.println(a == c); // this will be false as both point to the different references or memory location
System.out.println(a.equals(c)); // this will be true as the contents of both these strings is the same.

Converting parts of Strings to Character to be used in if/else statements

I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.

Why isn't my program returning the value of my expression?

I am currently taking an AP Computer Science class in my school and I ran into a little trouble with one of my projects! The project requires me to create a calculator that can evaluate an expression and then solve it. I have got most of that down, but I ran into a little trouble because my teacher asked me to use a while loop to continuously ask for input and display the answer, and I am stuck on that. To end the program the user has to type in "quit" and I can't use system.exit() or any cheating thing like that, the program has to just run out of code. I have got most of that down too, but I am not able to find a why to return the expression in the Method MethodToReadInput(); Does anyone have any tips?
import java.util.*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
MethodToReadInput();
MethodToTestInput(MethodToReadInput());
}
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
}
else {
return expression;
}
}
public static void MethodToTestInput(String expression) {
while (!expression.equalsIgnoreCase("quit")) {
MethodToReadInput();
MethodtoEvaluateInput(expression);
}
System.out.println("Goodbye!");
}
public static void MethodtoEvaluateInput(String expression) {
if (OperatorFor2OperandExpressions(expression).equals("+")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) + SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("*")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) * SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("-")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) - SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("/")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + (FirstOperandFor2OperandExpressions(expression) / SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor2OperandExpressions(expression).equals("^")) {
System.out.println(FirstOperandFor2OperandExpressions(expression) + " " + OperatorFor2OperandExpressions(expression) + " " + SecondOperandFor2OperandExpressions(expression) + " = " + Math.pow(FirstOperandFor2OperandExpressions(expression),SecondOperandFor2OperandExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("|")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.abs(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("v")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sqrt(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("~")) {
double x = 0.0;
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + (Math.round(OperandFor1OperatorExpressions(expression))+ x));
}
else if (OperatorFor1OperandExpressions(expression).equals("s")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.sin(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("c")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.cos(OperandFor1OperatorExpressions(expression)));
}
else if (OperatorFor1OperandExpressions(expression).equals("t")) {
System.out.println(OperatorFor1OperandExpressions(expression) + " " + OperandFor1OperatorExpressions(expression) + " = " + Math.tan(OperandFor1OperatorExpressions(expression)));
}
}
public static double FirstOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static double SecondOperandFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[2];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
public static String OperatorFor2OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
return OperandOrOperator;
}
public static String OperatorFor1OperandExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[0];
return OperandOrOperator;
}
public static double OperandFor1OperatorExpressions(String expression) {
String[] tokens = expression.split(" ");
String OperandOrOperator = tokens[1];
double y = Double.parseDouble(OperandOrOperator);
return y;
}
}
You need to put the MethodToReadInput and MethodtoEvaluateInput inside a loop. For example:
public static void main(String[] args)
{
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String input = MethodToReadInput();
while (input != null)//exit the loop and the program when input is null
{
MethodtoEvaluateInput(input);//process the input
input = MethodToReadInput();//ask the user for the next input
}
}
public static String MethodToReadInput()
{
Scanner kb = null;
try
{
kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
{
System.out.println("Goodbye!");
return null;
}
else
{
return expression;
}
}
finally
{//always close the Scanner before leaving the method
if (kb != null)
kb.close();
}
}
Also, you should follow the Java Naming Convention and use shorter names for your methods.
Try to simplify your code, and use do-while-loop instead while-loop should produce a better code, do while will at least do one loop and then inspect the next condition before do the next loop, but while will inspect the condition first, if it is okay, it will do the loop. So here is the code:
public class Calculator {
public static void main(String[] args) throws IOException {
System.out.println("Welcome to the AP Computer Science calculator!!");
System.out.println();
System.out.println("Please use the following format in your expressions: (double)(space)(+,-,*,/...)(space)(double)");
System.out.println("or: (symbol)(space)(double)");
System.out.println();
String expression = "";
do {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit"))
System.out.println("Goodbye!");
else
MethodtoEvaluateInput(expression);
} while (!expression.equalsIgnoreCase("quit"));
inRn.close();
inSw.close();
}
}
Do this:
public static String MethodToReadInput() {
Scanner kb = new Scanner(System.in);
System.out.print("Enter an expression, or quit to exit: ");
String expression = kb.nextLine();
if (expression.equalsIgnoreCase("quit")) {
System.out.println("Goodbye!");
return "";
}
else {
return expression;
}
By returning an empty string you know what to look for when the user wants to exit. It needs to be an empty string that you return because your method is supposed to return a string. Also adding this return statement is needed because the compiler will complain otherwise because it is possible to reach the end of a non-void function (something that returns something) without actually reaching a return statement (so when you enter the if statement as you have it now). You must specify a return case for all possibilities if you specify a return type. In other words you must always return what you say you will.
There are several things that should be fixed about this.
First, let's answer your actual question. You can have a number of choices.
You can just simply return whatever the user has input. In fact, you may not actually need the method for this. But anyway, if your method returns "quit", the while loop can check while ( ! expression.equals("quit") ) just as it does now.
You could return null. This indicates that "The expression is not an actual expression". Then your while could be while ( expression != null ) which is more efficient than string comparison.
But you have other design issues with your program:
You are calling the same methods again and again to retrieve the same things. Those methods split the string - a relatively heavy operation - again and again. You should probably just have a parseExpression() method that returns your tokens, and then something that tests whether these tokens represent a unary operator or a binary one. Something along the lines of:
String [] tokens = parseExpression( expression );
if ( isUnaryExpression( tokens ) ) {
String operator = tokens[0];
String operand = tokens[1];
// Do something with operator and operand.
} else if ( isBinaryExpression( tokens ) ) {
String operator = tokens[1];
String operand1 = tokens[0];
String operand2 = tokens[2];
// Do something with operator and operands {
} else {
System.err.println( "Bad expression!" );
}
You are calling MethodToReadInput twice from your main. This means it will Read one input, do nothing about it, and then read another one which will be passed to MethodToTestInput. Drop the first call, it's unnecessary.
In the cause of better encapsulation, the main method should actually not even call MethodToReadInput. It should become the responsibility of MethodToTestInput to call that method. So you just call MethodToTestInput() from main without passing a parameter at all.
So the structure should be:
main: Display introduction, call your looping method.
looping method: Call input method. Loop while returned expression is still an expression rather than "quit". Inside the loop, call expression handler method.
expression handler method: Call parseExpression() method, check what the tokens are, do the math.
Finally, about your naming issues:
In Java, we name only classes with an uppercase first letter. Constants are named with all capitals (words separated by underscore). Method names begin with a lowercase letter.
You don't name a method MethodThatDoesThis. You should name it doThis, instead. This makes reading your code easier because it actually describe what is happening. So I'd name the methods something like:
The input method: getNextExpression
The looping method: runCalculator, or doCalculatorMainLoop or something like that.
The expression handler method: parseAndCalculate.
Or something along these lines.

How do I retrieve the length of individual Strings in a set?

In my current assignment, I have a text file that contains a large number of words which is stored in a List. one of my methods must store all words of a certain (user specified) length from this List into a Set. furthermore, the different lists are placed into two different classes. My question is: How do I retrieve the length of Individual elements in that list? EDIT: here are the complete classes.
File and List are set up like this in the client class, HangmanMain:
// Class HangmanMain is the driver program for the Hangman program. It reads a
// dictionary of words to be used during the game and then plays a game with
// the user. This is a cheating version of hangman that delays picking a word
// to keep its options open. You can change the setting for SHOW_COUNT to see
// how many options are still left on each turn.
import java.util.*;
import java.io.*;
public class HangmanMain {
public static final String DICTIONARY_FILE = "E:/CSC143/Workspace/Assignment2/src/dictionary.txt";
public static final boolean DEBUG = false; // show words left
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome to the cse143 hangman game.");
System.out.println();
// open the dictionary file and read dictionary into an ArrayList
Scanner input = new Scanner(new File(DICTIONARY_FILE));
List<String> dictionary = new ArrayList<String>();
while (input.hasNext()) {
dictionary.add(input.next().toLowerCase());
}
// set basic parameters
Scanner console = new Scanner(System.in);
System.out.print("What length word do you want to use? ");
int length = console.nextInt();
System.out.print("How many wrong answers allowed? ");
int max = console.nextInt();
System.out.println();
// set up the HangmanManager and start the game
List<String> dictionary2 = Collections.unmodifiableList(dictionary);
HangmanManager hangman = new HangmanManager(dictionary2, length, max);
if (hangman.words().isEmpty()) {
System.out.println("No words of that length in the dictionary.");
} else {
playGame(console, hangman);
showResults(hangman);
}
}
// Plays one game with the user
public static void playGame(Scanner console, HangmanManager hangman) {
while (hangman.guessesLeft() > 0 && hangman.pattern().contains("-")) {
System.out.println("guesses : " + hangman.guessesLeft());
if (DEBUG) {
System.out.println(hangman.words().size() + " words left: "+ hangman.words());
}
System.out.println("guessed : " + hangman.guesses());
System.out.println("current : " + hangman.pattern());
System.out.print("Your guess? ");
char ch = console.next().toLowerCase().charAt(0);
if (hangman.guesses().contains(ch)) {
System.out.println("You already guessed that");
} else {
int count = hangman.record(ch);
if (count == 0) {
System.out.println("Sorry, there are no " + ch + "'s");
} else if (count == 1) {
System.out.println("Yes, there is one " + ch);
} else {
System.out.println("Yes, there are " + count + " " + ch+ "'s");
}
}
System.out.println();
}
}
// reports the results of the game, including showing the answer
public static void showResults(HangmanManager hangman) {
// if the game is over, the answer is the first word in the list
// of words, so we use an iterator to get it
String answer = hangman.words().iterator().next();
System.out.println("answer = " + answer);
if (hangman.guessesLeft() > 0) {
System.out.println("You beat me");
} else {
System.out.println("Sorry, you lose");
}
}
}
my method is set up as such in the HangmanManager class.
import java.util.*;
import java.io.*;
public class HangmanManager {
private List<String> dictionary;
private int length;
private int max;
private Set<String> w = new HashSet<String>();
private SortedSet<Character> guess;
Integer L1 = new Integer(length);
public HangmanManager (List<String> dictionary, int length, int max){
this.dictionary = dictionary;
this.length = length;
this.max = max;
}
public Set<String> words (){
while (scan.hasNext()){
if (scan.next().equals(L1)){
w.add(scan.next());
}
}
return w;
}
public int guessesLeft(){
return max;
}
public SortedSet <Character> guesses(){
Scanner input = new Scanner (System.in);
return guess;
}
public String pattern(){
return null;
}
public int record (char guess){
return guess;
}
}
the Scan is just a placeholder name. As you can see in the first block, the while loop adds all the strings in the DICTIONARY_FILE in the "dictionary" list. What I want to do in the second block is add all the words of a certain length into the w list but I don't know how to read the file from a completely different class (if that's even possible) and I also don't know how to take the length of each individual element in said file. do you guys have any ideas? or do you need me to upload more info.
PS: the full title of my assignment is "Evil Hangman." From what I've looked up, its a fairly common programming assignment so you should be able to google it and get more info on what I mean.
PSS: don't mind the other methods in HangmanManager. I'm mostly focused on the "Words" method.
Thanks for the help.
Okay, so assuming you have the list with all the words set up, here is some pseudocode to guide you forwards.
for every string in set
check if word is of specified length
if true:
add word to set
if false:
do nothing
String api might have some useful methods for this, especially for determining the length of the string.. :)
About the latter part of your question, it is somewhat hard to answer how to access things in another class without more code to see how it is set up. Generally, you use a getter method to retrieve the field.

First, last and sometime middle name detection Java

I am trying to write a code to give off the user's name in different formats after they enter it. However, if a user does not have a middle name, the system should print that there was an error. I have it so it works perfectly if the user enters three names but does not work if the user enters two names. Here is my code:
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
String fullName;
Scanner in = new Scanner(System.in);
System.out.print ("What are your first, middle, and last names? ");
fullName = in.nextLine();
System.out.println(fullName);
if (fullName.contains(" "))
{
String[] nameParts = fullName.split(" ");
String firstInitial = nameParts[0].substring(0,1).toUpperCase();
String secondInitial = nameParts[1].substring(0,1).toUpperCase();
String thirdInitial = nameParts[2].substring(0,1).toUpperCase();
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
else
{
System.out.println ("Your initials are: " + firstInitial + secondInitial + thirdInitial);
String lastVariationOne = nameParts[2].substring(0, nameParts[2].length());
lastVariationOne = lastVariationOne.toUpperCase();
String firstVariationOne = nameParts[0].substring(0, nameParts[0].length());
firstVariationOne = firstVariationOne.substring(0,1).toUpperCase() + firstVariationOne.substring(1, nameParts[0].length());
System.out.println("Variation One: " + lastVariationOne + ", " + firstVariationOne + " " + secondInitial + ".");
String lastVariationTwo = nameParts[2].substring(0, nameParts[2].length());
lastVariationTwo = lastVariationTwo.substring(0,1).toUpperCase() + lastVariationTwo.substring(1, nameParts[2].length());
System.out.println("Variation Two: " + lastVariationTwo + ", " + firstVariationOne);
}
}
else
{
System.out.println("Wrong. Please enter your name properly.");
}
}
}
Instead of this:
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
something like
if(nameParts.length != 3)
{
System.out.println("Invalid entry");
}
might be preferrable.
Basically, in the case that there are only two names entered, split() will return an array of length 2, whose elements are accessible by indices 0 and 1.
But in your if condition you attempt to access index 2, which could be out of bounds (it would be OOB for the case where you entered only two names).
To resolve this, you could either (a) try it like you do, but catch the ArrayIndexOutOfBoundsException or (b) check first that split produced a properly sized array, then go from there (this was the approach I took with the change I listed).
I'd suggest (b), but both approaches seem fine.
If you don't input middlename, would the array size be 2?
So there is NO namespart[2].
Just check size of namespart.
#jedwards jedwards's solution is there.

Categories

Resources