How to do this Card class in java? - class

so basically for my computer science class we have to create a Card class which takes user input for the card notation (for example "4S") and has a getDescription method which returns the description of the card ("four of spades"). the problem is, i keep getting an "unreachable statement" error in regards to the if statement. I probably did the whole thing wrong but here is what i did:
import java.util.Scanner;
public class Card
{
private String face;
private String suit;
public Card()
{
Scanner card = new Scanner(System.in);
System.out.print("Enter the card notation: ");
String input = card.next();
face = input.substring(0,1);
suit = input.substring(1);
}
public String getDescription()
{
return "Your card was the ";
if (face.equals("A")) return "ace";
return getDescription();
}
}

Any code placed after a return statement is unreachable, because the return statement tells a method to exit and go back to wherever it was called from with the information provided. Thus they should go at the end of methods, once you've fully prepared the information you want to send back. Something like
public String getDescription() {
String s = "Your card was the ";
if (face.equals("A")) {
s += "ace";
};
return s;
}

Related

How to turn String into UnityEngine.Sprite?

So inside my "SpriteChanger" script, I have two sprites: "Happy" and "Sad". In my "GameControl" script, I have a string "currentMood" which starts out as "Happy". But then I have a public void to change the "currentMood" into "Sad".
Now in the SpriteChanger script, I put this.GetComponent ().sprite = which works when I manually put in the name of the sprite.
However, I do not want to have a bajillion of those if I had a lot of sprites I need to switch to. I need a way to have this.GetComponent ().sprite = take the literal input of "currentMood". But Unity keeps saying that it cannot implicitly convert String to UnityEngine.Sprite.
Here's the code:
GameControl{
public string currentMood = "Happy";
public void changeMood () {
currentMood = "Sad";
}
/some function that calls changeMood somewhere here/
} ..
.
SpriteChanger {
public Sprite Happy;
public Sprite Sad;
/*and a buncha other sprites*/
public void changeMood () {
this.GetComponent<SpriteRenderer> ().sprite = GameControl.instance.currentMood)
}
}
Don’t use strings in these situations. It is always better to use an integer or something else. A string takes 8 bytes for each character, but an integer can store any number near the billions with only 4 bytes. This is a much better way of storing values. You could change the part in the first script to:
GameControl{
public int currentMood = 0;//happy
public void changeMood () {
currentMood = 1;//sad
}
//some function that calls changeMood somewhere here
}
SpriteChanger {
public Sprite CurrentSprite;
public Sprite Happy;
public Sprite Sad;
/*and a buncha other sprites*/
public void changeMood () {
switch (GameControl.instance.currentMood)
{
case 0:
CurrentSprite = Happy;
break;
case 1:
CurrentSprite = Sad;
break;
...//more cases
default:
Debug.Log(“Unknown case”);
break;
}
this.GetComponent<SpriteRenderer>().sprite = CurrentSprite;
}
}
Here, we use a switch statement. It is basically the same thing as an if statement, just we use them in these cases. The problem you were getting with converting a string to a sprite is that strings are just a variable like an integer. The way we write code is much more different to the computer. Names are just what we call the variable. It is what we use to reference that value. A name is not a string, though. So we cannot use variables with a string for their name.
What is a switch?

Create observables using straight methods

I need to recollect some data calling to a method is connecting to a webservice.
problem: Imagine I need to update the content text of a label control according to this remote gathered information. Until all this data is recollected I'm not going to be able to show the label.
desired: I'd like to first show the label with a default text, and as I'm receiving this information I want to update the label content (please, don't take this description as a sucked code, I'm trying to brief my real situation).
I'd like to create an observable sequence of these methods. Nevertheless, these method have not the same signature. For example:
int GetInt() {
return service.GetInt();
}
string GetString() {
return service.GetString();
}
string GetString2 {
return service.GetString2();
}
These methods are not async.
Is it possible to create an observable sequence of these methods?
How could I create it?
Nevertheless, which's the best alternative to achieve my goal?
Creating custom observable sequences can be achieved with the Observable.Create. An example using your requirements is shown below:
private int GetInt()
{
Thread.Sleep(1000);
return 1;
}
private string GetString()
{
Thread.Sleep(1000);
return "Hello";
}
private string GetString2()
{
Thread.Sleep(2000);
return "World!";
}
private IObservable<string> RetrieveContent()
{
return Observable.Create<string>(
observer =>
{
observer.OnNext("Default Text");
int value = GetInt();
observer.OnNext($"Got value {value}. Getting string...");
string string1 = GetString();
observer.OnNext($"Got string {string1}. Getting second string...");
string string2 = GetString2();
observer.OnNext(string2);
observer.OnCompleted();
return Disposable.Empty;
}
);
}
Note how I have emulated network delay by introducing a Thread.Sleep call into each of the GetXXX methods. In order to ensure your UI doesn't hang when subscribing to this observable, you should subscribe as follows:
IDisposable subscription = RetrieveContent()
.SubscribeOn(TaskPoolScheduler.Default)
.ObserveOn(DispatcherScheduler.Current)
.Subscribe(text => Label = text);
This code uses the .SubscribeOn(TaskPoolScheduler.Default) extension method to use a TaskPool thread to start the observable sequence and will be blocked by the calls the Thread.Sleep but, as this is not the UI thread, your UI will remain responsive. Then, to ensure we update the UI on the UI thread, we use the ".ObserveOn(DispatcherScheduler.Current)" to invoke the updates onto the UI thread before setting the (data bound) Label property.
Hope this is what you were looking for, but leave a comment if not and I'll try to help further.
I would look at creating a wrapper class for your service to expose the values as separate observables.
So, start with a service interface:
public interface IService
{
int GetInt();
string GetString();
string GetString2();
}
...and then you write ServiceWrapper:
public class ServiceWrapper : IService
{
private IService service;
private Subject<int> subjectGetInt = new Subject<int>();
private Subject<string> subjectGetString = new Subject<string>();
private Subject<string> subjectGetString2 = new Subject<string>();
public ServiceWrapper(IService service)
{
this.service = service;
}
public int GetInt()
{
var value = service.GetInt();
this.subjectGetInt.OnNext(value);
return value;
}
public IObservable<int> GetInts()
{
return this.subjectGetInt.AsObservable();
}
public string GetString()
{
var value = service.GetString();
this.subjectGetString.OnNext(value);
return value;
}
public IObservable<string> GetStrings()
{
return this.subjectGetString.AsObservable();
}
public string GetString2()
{
var value = service.GetString2();
this.subjectGetString2.OnNext(value);
return value;
}
public IObservable<string> GetString2s()
{
return this.subjectGetString2.AsObservable();
}
}
Now, assuming that you current service is called Service, you would write this code to set things up:
IService service = new Service();
ServiceWrapper wrapped = new ServiceWrapper(service); // Still an `IService`
var subscription =
Observable
.Merge(
wrapped.GetInts().Select(x => x.ToString()),
wrapped.GetStrings(),
wrapped.GetString2s())
.Subscribe(x => label.Text = x);
IService wrappedService = wrapped;
Now pass wrappedService instead of service to your code. It's still calling the underlying service code so no need for a re-write, yet you still are getting the observables that you want.
This is effectively a gang of four decorator pattern.

Palindromes: in this program i have to try and figure out if the user input is a palindrome or not

When ever i execute the program the output says not a palindrome when it is a palindrome(only does this when input has spaces or punctuation) can some one tell me where i went wrong in my code?
public class Palindromes
{
public static void main(String[]args)
{
ConsoleIO keyboard=new ConsoleIO();
String word, word2="",terminate;
int length;
do
{
System.out.print("Enter a string:");
word=keyboard.readLine();
word=word.toLowerCase();
word=word.trim();
word=word.replaceAll("\\W", "");
word=word.replaceAll(" ","");
length=word.length();
//finding the reverse of the string
for(int i=length-1;i>=0;i--)
{
word2+=word.charAt(i);
}
//checking to see if the string is a palindrome
if(word.length()==1)
{
System.out.println("The string you entered is not a palindrome");
}
else if(word.equals(word2))
{
System.out.println("The string you entered is a palindrome.");
}
else
{
System.out.println("The string you entered is not a palindrome.");
}
System.out.print("Do you want to continue (yes or no):");
terminate=keyboard.readLine();
System.out.println();
}
while(terminate.equalsIgnoreCase("yes"));
}
}
I think you'd need to account for the punctuation because that will affect the plaindrome test you have. ra.cecar is not otherwise a palindrome. Have you tried adding more lines like the following?
word=word.replaceAll(".", "");
word=word.replaceAll("?", "");
word=word.replaceAll("!", "");
word=word.replaceAll("-", "");
To end all problem to Palindrome, I've made this Java program that will end all suffering to it. It's in Java so you're in luck. It basically strip every non-word character, put it to lower case just with 13 lines. Hope this help haha! Let's hope other guys would get lucky to find this too.
import java.util.Scanner;
public class Palindrome {
public static void main(String[]args){
if(isReverse()){System.out.println("This is a palindrome.");}
else{System.out.print("This is not a palindrome");}
}
public static boolean isReverse(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Please type something: ");
String line = ((keyboard.nextLine()).toLowerCase()).replaceAll("\\W","");
return (line.equals(new StringBuffer(line).reverse().toString()));
}
}

How to get down to StringLiterals with Eclipse AST?

I need to create an Eclipse plugin that displays a tooltip when I hover the mouse over a String literal.
But only if that String literal is the first parameter of a special method.
Here is the Test.java file I use to test my plugin:
package test;
public class Test {
public static void main(String[] args) {
String hello = "Hello";
String world = Translator.get("Test.worldLabel");
System.out.println(hello + " " + world);
}
}
I created a class implementing IJavaEditorTextHover and I need to compile the currently edited Java file to compute if the cursor is hovering a String that needs to be translated or not.
Hovering "Hello" will do nothing.
Hovering "Test.worldLabel" will display my tooltip because that literal is included inside a Translator.get() method call.
At first I used this (170 is inside "Test.worldLabel"):
ITypeRoot typeRoot = (ITypeRoot)
JavaUI.getEditorInputJavaElement(editorPart.getEditorInput());
JavaElement foundElement = (JavaElement) typeRoot.getElementAt(170);
But the foundElement contains the whole main() method: it is not fine-grained enough.
Then, the correct way is, I think:
private static ASTNode parse(ICompilationUnit unit, int position) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
parser.setIgnoreMethodBodies(false);
// TODO Future optimisation: parser.setFocalPosition(position);
return parser.createAST((IProgressMonitor) null); // parse
}
And in my IJavaEditorTextHover.getHoverInfo(...) implementation:
ICompilationUnit compilationUnit = (ICompilationUnit)
JavaUI.getEditorInputJavaElement(editor.getEditorInput())
int position = 170/*hoverRegion.getOffset()*/;
ASTNode ast = parse(compilationUnit, position);
And now, here is my question:
How, from this ast node, do I get the ASTNode reprensenting the StringLiteral at position 170 in the source code (the "Test.worldLabel" String)?
Bonus question: did I choose the right solution? On a performance basis.
Edit:
Well, here is a solution I found:
private StringLiteral findStringLiteralAtPosition(final ASTNode parent, final int position) {
final List<StringLiteral> stringLiterals = new ArrayList<StringLiteral>();
parent.accept(new ASTVisitor() {
#Override
public boolean visit(StringLiteral stringLiteral) {
int start = stringLiteral.getStartPosition();
int end = start + stringLiteral.getLength();
if (start <= position && position <= end) {
stringLiterals.add(stringLiteral);
}
return super.visit(stringLiteral);
}
});
return (stringLiterals.size() > 0 ? stringLiterals.get(0) : null);
}
Does it seam OK?
Or is it an easier way or a more performant one?
One solution will be not using the offset logic at all.
You can generalise the solution by using a node parent check.
Here is a sample code:
public boolean visit(StringLiteral stringLiteral) {
// Check if parent is a method inovacation.
if (stringLiteral.getParent().getNodeType() == ASTNode.METHOD_INVOCATION) {
// get the parent method inovacation.
MethodInvocation miNode = (MethodInvocation) stringLiteral.getParent();
//To do: null and empty check on argument list.
// Check if is the special method and this is the 1st argument
if (miNode.getName().toString().equals("SpecialMethod")
&& miNode.arguments().get(0).toString().equals(stringLiteral.toString())) {
System.out.println("Found it : " + stringLiteral.toString());
}
}
return true;
}

GWT CellTable, disable ButtonCell when clicked

I'm pretty new to GWT, but I've been making pretty fast progress until now.
I have a cell table, most of which is read only data returned from an RPC.
I have two columns in the cell table that the user can interact with. One is a TextInputCell, one is a ButtonCell.
When the user clicks the ButtonCell, i want to send the value in the TextInputCell for that row to an RPC.
I have all this working.
The part I cannot get to work is that when the button (ButtonCell) is clicked, I want to disable the button in that row until the RPC returns, and then re-enable it. I also want to clear the text in the input cell for that row when the RPC returns.
I cannot figure out how to get handles to the actual ButtonCell object that was clicked or the TextInputCell to monkey with them.
Any help appreciated.
bq
The problem is that there's no object for the button that was clicked. Your ButtonCell creates HTML that renders buttons - every button in the whole column was written by the same button cell, but there's no java object associated with them.
To disable the button directly, you'll have to first create a handle to it. You could do this by rendering an id in the html your ButtonCell creates, and then getting the element by id from the DOM.
What I do in a similar case is just re-render the entire table when there's a state change. It doesn't take that long, and you don't need to store any references (the whole reason you're using CellTable instead of Grid anyway). When you know your button should be disabled, you just render it disabled.
Both of these suggestions would require you to subclass your Cell objects so that you can do some custom rendering. It's not very difficult, but wrapping your head around the order of operations can be confusing. Good luck!
PS: If you just want to disable the button (and not empty the text field), I think onBrowserEvent gives you a handle to the Element that was clicked - you might be able to use that to disable it.
I have gone through this problem, but eventually I solved it.
check this code
package com.ex7.client;
import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
public class CWButton extends ButtonCell {
private int row = -1;
private String alternativevalue;
private String exTitle = "";
private String value;
private String title = "";
public CWButton( ) {
super();
}
#Override
public void render(com.google.gwt.cell.client.Cell.Context context,
String src, SafeHtmlBuilder sb) {
if (row == -1) {
sb.appendHtmlConstant("<button title='" + title + "' >" +value+"</button>");
return;
}
if (row != context.getIndex()) {
sb.appendHtmlConstant("<Button disabled='disabled' title='" + title + "' >"+ value+"</button>");
} else {
sb.appendHtmlConstant("<button title='" + exTitle + "' >"+ alternativevalue+"</button>");
}
}
#Override
public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context,
Element parent, String value, NativeEvent event,
ValueUpdater<String> valueUpdater) {
if (row == -1 || row == context.getIndex()) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
return;
}
}
public void setTitle(String title) {
this.title = title;
}
public int getRow() {
return row;
}
public String getExTitle() {
return exTitle;
}
public void setExTitle(String exTitle) {
this.exTitle = exTitle;
}
public void setRow(int row) {
this.row = row;
}
public String getAlternativeValue() {
return alternativevalue;
}
public void setAlternativeValue(String alternativeValue) {
this.alternativevalue = alternativeValue;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}