A program that will let the user input a string and then output each letter on a new line - input

import java.util.Scanner;
public class Program3_5
{
public static void main (String[]args)
{
Scanner scan = new Scanner(System.in);
String input = new String();
System.out.println("Please enter a string: ");
input=scan.next();
int length;
length = input.length;
input.substring();
System.out.println(charAt(0));
while (length)
{
System.out.println(charAt(0 + 1));
}
}
}
I am getting an error stating that it "cannot find symbol - variable length"
I have tried numerous things yet I am having trouble getting it to work. New to Java! Thanks in advance.
For example if the user were to input: Hello There
The Output would print the letters on separate lines.

String#length() is a method, not a field, of String. You need to call the method. In Java, methods are called (or "invoked") using parentheses. So, change
length = input.length;
// to
length = input.length();
Anticipating the next compile error you see:
while (length)
won't compile in Java because length is an int, but the condition part of a while must be a boolean. I'm guessing you want to continue as long as the string is not empty, so change the while condition to be
while (length > 0)
Other problems you'll need to solve to get your code to compile:
String#substring() requires integer arguments
Also, the code will compile with the String input = new String(); but the assignment is completely unnecessary. In Java, you almost never need to new a string. Instead, use string literals.

Related

Java Setter Using User Input

To make sure this doesn't get closed, read this. This isn't a duplicate post because the only other user input setter is in C or c something and if not that it's for a completly different application. How can I set up my setWord method to use user input and not be null. My current code gives off a null pointer because the variable is null, but I can't find out a viable way to set it's value using user input. Current code: Subclass:
package hangman;
public class Hangman {
private String word;
public void setWord(String word) {
this.word = toString();
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
System.out.println("Enter secret word: ");
return (this.getWord());
}
}
Main
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setWord();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
}
Again, the issue is that I can't find a way to set the private String "word" to user input without it ending up being null. Please dont mark this as duplicate I already looked at the generic cookie cutter nullpointerexception threads but haven't helped me at all. I've been stuck on this and it's my last part of my program. The null pointer is always at the stringbuilder, which suggests that secretWord is null.
Think about it: where do you ever set the word? setWord assigns the return of toString, which returns the result of getWord, but getWord just returns what this.word already was! Nowhere do you ever set a word, so it's never initialized! You just set this.word to what it was originally, which was null. This causes an NPE when you call secretWord.length(), since secretWord is null.
You have another problem, which I'm assuming is a typo here, where your call to setWord in your main isn't given an argument. That's illegal and creates an error of its own, so it should never reach the StringBuilder line.
Change setWord to:
public void setWord(String word) {
this.word = word; ; Set it to its argument
}
Then call it with a word as the argument:
hangman.setWord("Word");
Originally I had a toString which served no functional purpose. And the setWord method required a parameter which I didn't have so to fix it I replaced the setWord code with this
public void setWord() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the secret word: (Under 7 letters)");
this.word = scan.nextLine();
this.word = word;
}

How does this duplicate checker loop work?

Hi I hope someone can help. I'm trying to understand the following java program that loops until it finds two integers from the user that are the same:
import java.util.Scanner;
public class whileloop {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int previous, input = in.nextInt();
while(in.hasNextInt()){
previous = input;
input = in.nextInt();
if (input == previous){
System.out.println("Duplicate input found!");
}
}
}
So from my understanding, the program will call the user to provide two integers from .nextInt(), store those values in the variables named "previous" and "input", and then will proceed to the while loop. What I don't understand is what occurs right before the if condition. What is the point of having "previous" equate to "input" and then asking input for another integer? If I remove previous = input and input = in.nextInt() I get an error that says that the variables have not been initialized.... which confuses me since I thought that the variables "previous" and "input" got initialized when the program asked the user for the two integers? Evidently I'm quite confused, and would really appreciate help.

How to convert a handle string to a std::string

I am trying to convert a handle string to a normal string. I though the method I was using was working, but when I look in the debugger it appears that half of my string has been chopped off on the line that creates the chars variable. Any idea why and what the proper way to convert a handle string to a normal string woudl be?
std::string convert(String^ s) {
const char* chars = (const char*)(System::Runtime::InteropServices::Marshal::
StringToHGlobalAnsi(s)).ToPointer();
string myNewString = std::string(chars);
return myNewString;
}
It's probably the debugger that's cutting off the display of the string. You didn't mention how long a string you're using, but the debugger can't display infinite length, so it has to cut it off at some point.
To verify this, try printing myNewString to the console, or to the debugger via Debug::WriteLine or OutputDebugString.
However, there is a significant issue in your code: After allocating memory with StringToHGlobalAnsi, you must free it using FreeHGlobal.
If you want to continue using StringToHGlobalAnsi, I'd fix it up like this:
std::string convert(String^ s) {
IntPtr ptr = Marshal::StringToHGlobalAnsi(s);
string myNewString = std::string((const char*)ptr.ToPointer());
Marshal::FreeHGlobal(ptr);
return myNewString;
}
However, it's probably easier to use the marshal_as methods. This will take care of everything for you.
std::string output = marshal_as<std::string>(managedString);

Getting a return value from Antlr Listener?

i have a Antlr generated Listener, and i call my tree walker to go through the tree from a parse function in another class. Looks like this:
public double calculate(){
ANTLRInputStream input = new ANTLRInputStream("5+2");
Lexer lexer = new Lexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
Parser parser = new Parser(tokens);
ParseTree tree = parser.calculate();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(new Listener(), tree);
return 0;
}
So the listener works perfect with the enter() and quit() Functions and prints the correct value in the end:
public void exitParser(ParserContext ctx) {
result = stack.peek();
System.out.println(result);
}
But i wanna receive the final value in my calculate() function to return it there. Since exitParser(...) is void i dont know how to deal with it.
With the visitor i was able to do it like that:
public double calculate(){
// ...
String value = new WRBVisitor().visit(tree);
return Double.parseDouble(value);
}
Hope someone understands my problem and knows a solution for it.
Best regards
As mentioned in the comments: a visitor might be a better option in your case. A visitor's methods will always return a value, which is what you seem to be after. That could be a Double if your expressions always evaluate to a numeric value, or some sort of home-grown Value that could represent a Double, Boolean, etc.
Have a look at my demo expression evaluator (using a visitor) on GitHub: https://github.com/bkiers/Mu

What is this Objective C code doing

I am a developer in C-like languages (Java/JavaScript/C#) and I am attempting to convert some Objective-C code into Java.
For the most part, it is relatively straightforward but I have hit a stumbling block with the following bit of code:
typedef struct {
char *PAGE_AREA_ONE;
char *PAGE_AREA_TWO;
char *PAGE_AREA_THREE;
} CODES;
- (CODES*) getOpCode {
CODES *result = NULL;
result = malloc(sizeof(CODES));
result->PAGE_AREA_ONE = "\x1b\x1b\x1b";
result->PAGE_AREA_TWO = "\x2d\x2d\x2d";
result->PAGE_AREA_THREE = "\x40\x40";
return result;
}
What would the Java equivalent of this be? From what I can tell in other areas of the code, it is being used to store constants. But I am not 100% certain.
Thanks.
The typedef is just creating a structure that contains three string properties. The getOpCode method is apparently trying to create a new structure and assign values to those three properties. C# code would be:
public class Codes
{
public string PageAreaOne;
public string PageAreaTwo;
public string PageAreaThree;
}
public Codes GetCodes()
{
Codes result = new Codes();
result.PageAreaOne = "\x1b\x1b\x1b"; // three ESC characters
result.PageAreaTwo = "---";
result.PageAreaThree = "##";
return result;
}
The code in question is allocating a block of memory that the size of the CODES structure, filling it with some data, and returning a pointer to the new block. The data is apparently some operation codes (that is, instructions) for something, so perhaps the data is being sent to some other device where the instructions will be executed.