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.
Related
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;
}
Whenever I run my compiled code, it displays the largest number but it doesn't display the second largest number correctly. Here is my code:
package twoLargestNumbers;
import java.util.Scanner;
//find two largest numbers
public class twoLargestNumbers {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int num;
int counter=0;
int largest=0;//largest
int second=0;//second largest
System.out.println("Enter number:");
num=input.nextInt();
while(counter<5){
num=input.nextInt();
if(num>largest){
second=largest;//store largest to second largest
largest=num;//store largest to inputted number
}
else{
if(num>second)
second=num;//store second number to inputed number
}
counter=counter+1;
}
System.out.println("largest number is "+largest);
System.out.println("and second largest number is "+second);
}
}
What am I doing wrong? I reread and read this code and I cannot find out what the error is.
Remove the num=input.nextInt() before the while loop starts.
The initial input is being called and then straight away after the "first" input in the while method is called.
A couple of other tips, usually for a defined length of loop (in this case, 5) you would use a for loop to show your intent a bit more.
Also you can increment counter doing: counter++; or counter += 1;
Assuming the intent of your program is to ask for 5 numbers of input and then display the largest two, that should all help. Hope it did.
Also I don't think this block of code is needed, the second largest is already being stored in the first if statement.
else{
if(num>second)
second=num;//store second number to inputed number
}
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.
In my title screen, i have a code saying that the first controller using A is the PlayerIndex.one.
Here is the code:
public override void HandleInput(InputState input)
{
for (int anyPlayer = 0; anyPlayer <4; anyPlayer++)
{
if (GamePad.GetState((PlayerIndex)anyPlayer).Buttons.A == ButtonState.Pressed)
{
FirstPlayer = (PlayerIndex)anyPlayer;
this.ExitScreen();
AddScreen(new Background());
}
}
}
My question is: How can i use the "FirstPlayer" in other classes? (without this, there is no interest in this code)
I tried the Get Set thing but i can't make it work. Does i need to put my code in another class? Do you use other code to make this?
Thanks.
You can make a static variable say : SelectedPlayer,
and assign first player to it!
then you can call the first player through this class,
for example
class GameManager
{
public static PlayerIndex SelectedPlayer{get;set;}
..
..
..
}
and right after the loop in your code, you can say:
GameManager.SelectedPlayer = FirstPlayer;
I hope this helps, if your code cold be clearer that would be easier to help :)
Ok, so to do this properly you're going to have to redesign a little.
First off, you should be checking for a new gamepad input (i.e. you should be exiting the screen only when 'A' has been newly pressed). To do this you should be storing previous and current gamepad states:
private GamePadState currentGamePadState;
private GamePadState lastGamePadState;
// in your constructor
currentGamePadState = new GamePadState();
lastGamePadState = new GamePadState();
// in your update
lastGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
Really what you need to do is modify your class that deals with input. The basic functionality from your HandleInput function should be moved into your input class. Input should have a collection of functions that test for new/current input. For example, for the case you posted:
public Bool IsNewButtonPress(Buttons buton)
{
return (currentGamePadState.IsButtonDown(button) && lastGamePadState.IsButtonUp(button));
}
Then you can write:
public override void HandleInput(InputState input)
{
if (input.IsNewButtonPress(Buttons.A)
{
this.ExitScreen();
AddScreen(new Background());
}
}
Note: this will only work for one controller. To extend the implementation, you'll need to do something like this:
private GamePadState[] currentGamePadStates;
private GamePadState[] lastGamePadStates;
// in your constructor
currentGamePadStates = new GamePadState[4];
currentGamePadStates[0] = new GamePadState(PlayerIndex.One);
currentGamePadStates[1] = new GamePadController(PlayerIndex.Two);
// etc.
lastGamePadStates[0] = new GamePadState(PlayerIndex.One);
// etc.
// in your update
foreach (GamePadState s in currentGamePadStates)
{
// update all of this as before...
}
// etc.
Now, you want to test every controller for input, so you'll need to generalise by writing a function that returns a Bool after checking each GamePadState in the arrays for a button press.
Check out the MSDN Game State Management Sample for a well developed implementation. I can't remember if it supports multiple controllers, but the structure is clear and can easily be adapted if not.
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.