So I'm trying too write a program that will print the letters of a string backwards on each line, but I can only get it too print the last letter of the string infinitely. Can anyone show me how I would get the result I want?
This is what I wrote so far:
String word = "anything";
int length = word.length();
char letter = word.charAt(length-1);
while(length > 0)
System.out.println(letter);
I'm trying to teach my self java, so any help is much appreciated.
public static void main(String[] args) {
Scanner userIn = new Scanner(System.in);
System.out.printf("Enter a word: ");
String word = userIn.nextLine();
char[] reverse = word.toCharArray();
int length = reverse.length;
for (int i = reverse.length - 1; i >= 0; i--) {
System.out.println(reverse[i]);
}
}
}
Name:
nambla_dot_org_rules_you2011-06-03 19:45
And the output....
run:
Enter a word: anything
g
n
i
h
t
y
n
a
BUILD SUCCESSFUL (total time: 3 seconds)
Name:
nambla_dot_org_rules_you2011-06-03 19:50
Yeah, I forgot to remove the scaffolds...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner userIn = new Scanner(System.in);
System.out.printf("Enter a word: ");
String word = userIn.nextLine();
char[] reverse = word.toCharArray();
for (int i = reverse.length - 1; i >= 0; i--) {
System.out.println(reverse[i]);
}
}
}
So I was able to do this in 16 lines of Java code on the first attempt and the entire thing took me 5 minutes.
/**
* Set of classes for handling advanced operations on strings,
* as per application guidelines.
*
* @package AdvancedStringHandling
* @author Anonymous
*/
interface ASH_IStringContainer
{
public function __construct($string);
public function __toString();
}
interface ASH_IFactory
{
public static function create($type);
}
public function __construct($code = self::UNSPECIFIED, $message = '')
{
$this->code = (int)$code;
$this->message = (string)$message;
}
}
class ASH_FactoryException extends Exception { }
class ASH_StringContainerFactoryException extends ASH_FactoryException { }
/**
* Base inheritance class for all string containers. Not to be used as a standard string container.
*
* @abstract
* @see ASH_StandardString
*/
abstract class ASH_StringContainer implements Countable, ArrayAccess, ASH_IStringContainer
{
protected $str = array();
public function __construct($string = '')
{
$this->_set($string);
}
public function __toString()
{
return implode($this->str);
}
/**
* Magic method for allowing chainable standard string function calls on the string container's internal string.
*
* @final
* @param mixed ... Use whichever variables are appropriate for the function call you want to make
* @return $this if the result of the call was null, or if the call modified the internal string/array, otherwise returns the value of the call
*/
final public function __call($name, $arguments)
{
switch ($name)
{
case 'echo':
case 'print':
return call_user_func_array(array(__CLASS__, '_echo'), $arguments);
break;
default:
try
{
$rf = new ReflectionFunction($name);
$offset = -1;
// determine where our stored string is supposed to go in the argument list
foreach ($rf->getParameters() as $paramNum => $param)
{
switch ($param->getName())
{
case 'glue':
case 'subject':
case 'str':
case 'str1':
case 'string':
case 'hebrew_text':
$offset = $paramNum;
break 2;
}
}
if ($offset === -1)
{
throw new ASH_StandardStringFunctionAsMethodCallException(
ASH_StandardStringFunctionAsMethodCallException::UNSUPPORTED,
"Function {$name} not a supported standard string function to use as a magic method with StringContainer."
);
}
else
{
// insert our stored string in the appropriate space in the argument list before we pass it to the function
array_splice($arguments, $offset, 0, (string)$this);
$retval = $rf->invokeArgs($arguments);
// should we return a (chainable) reference to self, or keep the value given to use by the call?
if (is_string($retval) || is_array($retval))
{
// this function intends to modify the stored value
$this->_set($retval);
$retval =& $this;
}
elseif(is_null($retval))
{
$retval =& $this;
}
return $retval;
}
}
catch (ReflectionException $e)
{
throw new ASH_StandardStringFunctionAsMethodCallException(
ASH_StandardStringFunctionAsMethodCallException::UNRECOGNIZED,
"Function {$name} is not a known function."
);
}
break;
}
}
/**
* Manages the intricacies of our internal "string array"
* @return $this
*/
private function _set($string)
{
$this->str = str_split(is_array($string) ? implode(' ', $string) : (string)$string);
}
/**
* Chainable command for outputting current state of the string.
* @return $this
*/
private function _echo($prepend = '', $append = '')
{
print($prepend . (string)$this . $append);
return $this;
}
function prepend($string)
{
$this->_set($string . (string)$this);
return $this;
}
function append($string)
{
$this->_set((string)$this . $string);
return $this;
}
function set($string)
{
$this->_set($string);
}
/// Countable implementation
public function count()
{
return sizeof($this->str);
}
/// ArrayAccess implementation
public function offsetSet($offset, $value)
{
$this->str[$offset] = (string)$value;
}
public function offsetExists($offset)
{
return isset($this->str[$offset]);
}
public function offsetUnset($offset)
{
$this->str = array_splice($this->str, $offset, 1);
}
public function offsetGet($offset)
{
return $this->str[$offset];
}
}
/**
* Standard string container, default created by factory
*/
class ASH_StringContainer_Standard extends ASH_StringContainer { }
/**
* Standard string container, default created by factory
*/
class ASH_StringContainer_Reverse extends ASH_StringContainer
{
public function __construct($string)
{
parent::__construct($string);
$this->str = array_reverse($this->str);
}
}
abstract class ASH_Factory implements ASH_IFactory
{
/**
* used to cache classname bases (expensive string operations)
* @internal
*/
private static $classnameBaseLookup = array();
/**
* Private constructor prevents inherited classes from being able to instantiate
* @private
*/
private function __construct()
{
}
/**
* Default implementation of factory creation.
* If the class to be created does not follow naming conventions,
* or requires arguments in the constructor, you must override $create.
*
* @return object classname decided by naming convention
* @see getClassName
* @see getClassNameBase
*/
public static function create($type)
{
$className = self::getClassName($type);
if (class_exists($className))
{
return new $className();
}
else
{
throw new ASH_FactoryException("Unknown class type {$containerType} for factory " . get_called_class());
}
}
/**
* @return string Full class name being called by the Factory (by convention)
*/
protected static function getClassName($type)
{
$classSubname = preg_replace('/[\s]+/', ' ', ucwords(preg_replace('/[^a-zA-Z ]/', '', (string)$type)));
return self::getClassNameBase() . "_{$classSubname}";
}
/**
* @return string Base class name prefix for which the inherited factory is associated (by convention)
*/
protected static function getClassNameBase()
{
$classname = get_called_class();
if (!isset(self::$classnameBaseLookup[$classname]))
{
$parts = explode('_', $classname);
if ('Factory' === end($parts))
{
array_pop($parts);
}
self::$classnameBaseLookup[$classname] = implode('_', $parts);
}
return self::$classnameBaseLookup[$classname];
}
}
abstract class ASH_StringContainer_Factory extends ASH_Factory
{
const DEFAULT_CONTAINER_TYPE = 'Standard';
public static function create($type = self::DEFAULT_CONTAINER_TYPE)
{
return self::createString('', $type);
}
public static function createString($string, $type = self::DEFAULT_CONTAINER_TYPE)
{
$className = self::getClassName($type);
if (class_exists($className) && is_subclass_of($className, self::getClassNameBase()))
{
return new $className($string);
}
else
{
throw new ASH_StringContainerFactoryException("Unknown StringContainer type {$type} (expected class {$className})");
}
}
}
/**
* Inline Unit Test (IUT)
* @internal
*/
if (isset($argc) && strstr($argv[0], basename(__FILE__)))
{
// environment setup
$argumentString = implode(' ', array_slice($argv, 1));
$argumentString = $argumentString ? $argumentString : 'Default Unit Test String';
// test
ASH_StringContainer_Factory::createString($argumentString, 'Reverse')
->print()
->strrev()
->print("\n")
->strtoupper()
->append(' (I am typing in all caps to indicate that I am shouting)')
->print("\n");
}
$ php -f "AdvancedStringHandling_Main.php"
gnirtS tseT tinU tluafeD
Default Unit Test String
DEFAULT UNIT TEST STRING (I am typing in all caps to indicate that I am shouting)
>>23
Learn how to use Emacs, and use it. You have a good IDE for most languages out there.
Read SICP, now learn a Lisp. You have enough knowledge to learn any other language and get only the good from it, and
>>26
This is one of the bigger obstacles to CL adoption today. Of course, enduring the shitty editor isn't quite as bad as enduring the shitty evaluator, or enduring the shitty libraries.
Or, if you prefer a GUI, you should use notepad++ if you use Windows.
Or you could install a linux distro. If you're new to those, I recommend Ubuntu, within which you should use gedit.
Name:
Anonymous2011-06-04 3:58
# pythonistas do it better
print '\n'.join(list(reversed('anything')))
Name:
Anonymous2011-06-04 4:13
>>21
Emacs and Vim are good, but if you're stuck on Windows for the rest of your life and can't figure out how to install a VM I'd go with SublimeText.
vim is rather nice. I recommend that.
Or, if you prefer a GUI, you should use gvim if you use Windows.
Or you could install a linux distro. sage for ubanto within which you should use vim/gvim.
Seriously. You can use vim or gvim anywhere. There's no reason not to use it on one system and not on another.
>>30
I found Sublime was more interested in flirting with my GPU than helping me write code. While I was evaluating Windows editors a while back, I found e was quite good, in a comprehensive sense. vim on Windows still beats it, but worth having nonetheless.
>>29,31
Am I reading that right? Is join() really a method on the glue string in Python?
I'm sure there's enough vim scripts to turn it into an above-par Lisp editor.
Name:
Anonymous2011-06-04 7:24
>>35
It's about as elegant as making all functions know their names but not letting the programmer change the __name__ field of functions, or making print a keyword instead of a function.
Use Eclipse for Java.
Or at least that's what I'd do.
I use Emacs for my Python and Lisp, never done a single line of Java. Which is why I have no job.