Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Please help me in using for loops, for I am fairly new to Java. When I ran my program, the compiler threw out an error saying that my for loop is not a statement and it hinted at the variable guess, so I put String in front of guess because I declared it as a String. After I compiled this newly edited program, it threw out another error, this time saying that the variable guess was already declared outside of the for loop. Is there any way that I can use a variable declared outside of the for loop in the for loop? Here is the code:
import java.util.Scanner;
import java.util.Random;
public class Lottery{
public static void main(String args[]){
// create Scanner object
Scanner in;
in = new Scanner(System.in);
// create counter variable
int counter = 0;
// prompt user to choose between and including 000 and 999
System.out.print("Please pick a number between and including 000 and 999: ");
// initialize guess
String guess = in.next();
// get first two digits of guess
String firstTwoDigitsGuess = guess.substring(0, 2);
// get last two digits of guess
String lastTwoDigitsGuess = guess.substring(1);
// create Random number
Random number = new Random();
// initialize range
int range = number.nextInt(1000);
// convert int range to String
String rangeString = Integer.toString(range);
// firstTwoDigits declaration and initialization for first two digits of rangeString
String firstTwoDigitsString = rangeString.substring(0, 2);
// secondTwoDigits declaration and initialization for last two digits of rangeString
String lastTwoDigitsString = rangeString.substring(1);
// firstTwoDitigsRangeTrailingZero declaration and initialization
String firstTwoDigitsRangeTrailingZero = "";
// secondTwoDigitRangeTrailingZero declaration and initialization
String lastTwoDigitRangeTrailingZero = "";
// while statement
for(guess; !guess.equals(rangeString); ){
// if-else-if statement for trailing zeroes
if(range < 100){
// create zero variable
char zero;
zero = '0';
// create number with one trailing zero
int oneTrailingZero;
oneTrailingZero = zero + range;
// convert int oneTrailingZero to String
String oneTrailingZeroString = Integer.toString(oneTrailingZero);
// create first two digits of one trailing zero
String firstOneTrailingZeroString = oneTrailingZeroString.substring(0, 1);
// create last two digits of one trailing zero
String lastOneTrailingZeroString = oneTrailingZeroString.substring(1);
// // nested if-else-if statements
// all digits match
if(guess.equals(oneTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Perfect guess, all digits match!");
// first two digits match
}else if(firstTwoDigitsGuess.equals( firstOneTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("The first two digits match!");
// last two digits match
}else if(lastTwoDigitsGuess.equals( lastOneTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("The last two digits match!");
}else{
// do nothing
}
}else if(range < 10){
// create doubleZero variable
String doubleZero = "00";
// create number with double trailing zeroes
String doubleTrailingZero;
doubleTrailingZero = doubleZero + range;
// create first two digits of double trailing zeroes
String firstDoubleTrailingZeroString = doubleTrailingZero.substring(0, 1);
// create last two digits of double trailing zeroes
String lastDoubleTrailingZeroString = doubleTrailingZero.substring(1);
// // nested if-else-if statements
// all digits match
if(guess.equals(doubleTrailingZero)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Perfect guess, all digits match!");
// first two digits match
}else if(firstTwoDigitsGuess.equals( firstDoubleTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Firt two digits match!");
// last two digits match
}else if(lastTwoDigitsGuess.equals( lastDoubleTrailingZeroString)){
// notify user has won
System.out.println("Winner!\nRandom number: " + range);
// notify user why they won
System.out.println("Last two digits match!");
}else{
// do nothing
}
// wrong guess
}else{
// notify user's guess is wrong
System.out.println("The guess you chose was wrong. You did not get a perfect guess. Neither did your first or last two digits match the random number. The random number was: " + range);
}
}
}
}
You don't need the guess in the for loop as it is not instantiating it. Instead try...
for( ; !guess.equals(rangeString); ) {...}
I'm pretty sure that's why it's hinting at it. Typically, at least in Java, if no variable is being created in the for, then it complains if you do as you did. For instance, this...
int i = 0;
for(i; i < 10; ++i) {...}
complains while this...
for(int i = 0; i < 10; ++i) {...}
does not.
a for loop works very similar to a while loop for example,
int i = 0;
while(i < 4){
//do stuff
i++;
}
is the same as
for(int i = 0; i < 4; i++){
//do stuff
}
So in the first part, you are defining a variable, in the second part, you are saying "keep going as long as this is true" and in the end you are saying "do this at the end of each loop"
So try
for( ;!guess.equals(rangeString); ){//your code}
However you would probably be better off replacing your for loop with this:
while(!guess.equals(rangeString)){//your code}
Loop statements are formed like this:
for(int i = 0; i < 10; i++){
// start^ end^ ^increment
}
Related
I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.
package reversedHiLo;
//Import utility
import java.util.*;
public class ReversedHiLo
{
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.next();
sc.nextLine();
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
}
There are two places where there is a problem:
The first one sc.nextInt() method - which only reads the int
value by keeps current reading buffer on the same line. So to
ignore/skip everything what is after int on the input line (which is
probably \n or \r\n if you only enter the number) you have to
use sc.nextLine().
The second one is sc.next() method - which
only reads first token(or simply word) from your line. That is
probably why you only get "less" value assigned to response
and that will never be .equals to "less than". So you will
have to replace sc.next() one with sc.nextLine() and remove
unnecessary sc.nextLine() from the next line.
Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.
If my explanation is still not clear have a look at the code I have modified for you below:
public static void main(String[] args)
{
//create scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
int answer = sc.nextInt();
sc.nextLine(); // This one is necessary to ignore everything on the same line as your number was typed in
//Create the first guess
int guess = 1 + (int)(100*Math.random());
//Create an array that stores the range of the player's number
int[] range = new int[] {1,100};
//While loop that guesses the number
while(guess != answer)
{
System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
String response = sc.nextLine(); // This reads the whole input line
//Conditionals to set the range of the guess
if(response.equals("less than"))
{
range[1] = guess;
}
else
{
range[0] = guess;
}
//Guess a new number based on the range
guess = range[0] + (int)((range[1] - range[0]) * Math.random());
}
//Final print
System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
//Close scanner
sc.close();
}
So the purpose of this program is to get the user to enter an integer that the program will recognize as a string. Then the program has to be able to recognize each of the numbers entered and manipulate them as follows. Digits are to be added together if the digits are the same or if the next digit is greater. Digits are to be subtracted if the next digit is smaller.
An example:
The input "234224" should output 13(2+3+4-2+2+4)
However my program gives an output of 17.
I don't know how to fix the problem. My problem is in my first if statement. When the second occurrence of "2" is read I want the program to subtract 2 from the output being calculated but instead it adds 2 because of how I coded the first if statement.
Could someone give me a solution using the same method I used if possible?
public class StringManipulation {
public static void main(String[] args) {
String userInt;
int total = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
userInt = input.nextLine();
for (int k = 0; k < userInt.length(); k++) {
int presentNum = userInt.charAt(k);
System.out.println(userInt.charAt(k));
if (presentNum == userInt.charAt(0)) {
presentNum = Character.getNumericValue(presentNum);
total += presentNum;
System.out.println("counter currently at (same)" + total);
} else if (presentNum >= userInt.charAt(k - 1)) {
total += Character.getNumericValue(presentNum);
System.out.println("counter currently at (adding)" + total);
} else if (presentNum < userInt.charAt(k - 1)) {
total -= Character.getNumericValue(presentNum);
System.out.println("counter currently at (subtracting)" + total);
}
}
System.out.println("Output= " + total);
input.close();
}
}
Your problem is with your initial check
if (presentNum == userInt.charAt(0))
in other words, you do stuff if the number you're looking at is the same as the first number. In this particular case, that condition kicks in when you encounter the 2 later in the string, and you end up adding it instead of subtracting it.
You probably wanted that condition to be
if (k == 0)
if (presentNum == userInt.charAt(0)) {
presentNum=Character.getNumericValue(presentNum);
total+=presentNum;
System.out.println("counter currently at (same)" + total);
}
Your problem lies here. The first digit is added to the sum regardless of the previous digit. That means the output changes from 13(2+3+4-2+2+4) to 17(2+3+4 +2 +2+4).
You should have something like
if (k==0){
presentNum=Character.getNumericValue(presentNum);
total+=presentNum;
}
for the first digit.
Try to change the first if condition, as follows
if (k==0) {
presentNum = Character.getNumericValue(presentNum);
total += presentNum;
System.out.println("counter currently at (same)" + total);
}
Because, at the first iteration you have only one operand and you don't have take the value at 0th index for the condition, rather than that just see whether is it the first index.
I'm prompting a user for a number and am trying to determine the amount of even, odd, and zeros in that number
/* This program will determine and print the number of even, zero, and odd digits in
* an integer
*
* Author: Marco Monreal
* Date: 11/01/2016
*/
import java.util.Scanner;
public class PP5_3
{
public static void main(String[] args)
{
String exit_loop, go_again, user_num, first_char_string;
int odds, evens, zeros;
int first_char; //, second_char, third_char, fourth_char, fifth_char, sixth_char, seventh_char, eighth_char, ninth_char, tenth_char;
Scanner scan = new Scanner (System.in);
evens = 0;
odds = 0;
zeros = 0;
exit_loop = "no"; //initializing while loop
while (exit_loop.equals ("no"))
{
System.out.println ("Choose any number between 0 and 2,147,483,647. Don't include commas please.");
user_num = scan.next ();
I'm getting stuck around this area; "first_char" is not returning the digit value that I want/need.
//assigning a variable to each character of user_num
first_char = user_num.lastIndexOf(0);
/*second_char = user_num.charAt(1);
third_char = user_num.charAt(2);
fourth_char = user_num.charAt(3);
fifth_char = user_num.charAt(4);
sixth_char = user_num.charAt(5);
seventh_char = user_num.charAt(6);
eighth_char = user_num.charAt(7);
ninth_char = user_num.charAt(8);
tenth_char = user_num.charAt(9);*/
//copy every character into a string value
first_char_string = String.valueOf(first_char);
if (first_char == 2 || first_char == 4 || first_char == 6 || first_char == 8)
{
evens++;
}
else if (first_char_string.equals("1") || first_char_string.equals("3") || first_char_string.equals("5") || first_char_string.equals("7") ||
first_char_string.equals("9"))
{
odds++;
}
else
zeros++;
} //ends while loop
System.out.println ("There are " +evens+ " even numbers, " +odds+ " odd numbers, and " +zeros+ "zeros in ");
scan.close ();
} //ends main method
} //ends class
Hi take a look on this line:
user_num = scan.next (); // this will scan your user input, but does not jump to the next line
you might want to use:
user_num = scan.nextLine();
Also you made a mistake in your lastIndexOf(char) method.
This method expects a char. you supply this method an int e.g:
first_char = user_num.lastIndexOf(0);
this works because java interprets your number a an ASCI-number. the char representated by ASCI "0" is null. What you want to do is search for the character '0'. Like the following:
first_char = user_num.lastIndexOf('0');
The same for your equalisations:
first_char == 2 ---> first_char == '2';
Another notice. Please use camel case istead of underscores. instead of user_num you should write userNum. Thats the standard.
Yet another notice. The lastIndexOf() method will return the nummber of the last occurence of the parameter. e.g:
String test = "hello test";
test.lastIndexOf(e); // this will return 7 for it is the number ofthe last occurence of 'e'
I think yu want to use charAt(0) this returns the charactere at specified position
Last Notice. why are you comparing char values representing numbers ?
why not do the following:
int userNum = Integer.valueOf(yourCharHere).
Update
If I understood your comment correctly the your 'X' in the snippet below is defined by the user
first_char = userNum.charAt(X);
If I get you right you have a problem because you dont know how long the input of the user is. Instead of assigning the individual numers to variables I would do the following:
//Parsing your String into a int
int userNum = Integer.valueOf(yourUserInputHere);
Arraylist singleDigits = new ArrayList()<>;
//This goes through all digits of your number starting with the last digits
while (userNum > 0) {
singleDigits.add( userNum % 10);
userNum = userNum / 10;
}
//Reverses your list of digits
Collections.reverse(singleDigits);
Example input: 13467
your List should look like: [1],[3],[4],[6],[7]
This enables you to get the single digits by calling:
singleDigits.get(0) -> [1];
singleDigits.get(3) -> [6];
...
I hope that helps
First create sets that are containing odd/even/zero numbers:
Set<Integer> odds = "13579".chars().boxed().collect(Collectors.toSet());
Set<Integer> evens = "02468".chars().boxed().collect(Collectors.toSet());
Set<Integer> zero = "0".chars().boxed().collect(Collectors.toSet());
Then get an input from the user
Scanner scan = new Scanner(System.in);
System.out.println("Choose a number:");
String number = scan.next();
scan.close();
Parse number character by character to find out how many digits are matching each set:
long numberOfOdds = number.chars().filter(odds::contains).count();
long numberOfEvens = number.chars().filter(evens::contains).count();
long numberOfZeros = number.chars().filter(zero::contains).count();
Finally, display the result:
System.out.println("There are " + numberOfEvens + " even numbers, " + numberOfOdds + " odd numbers, and " + numberOfZeros + " zeros in ");
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
boolean isAnInteger = false;
while (isAnInteger)
{
if (digit >= 10)
{
System.out.println("Please enter an integer: ");
}
else
{
System.out.println("Correct! " + digit + " is an integer!");
}
}
}
I'm currently taking AP Computer Science and I'm curious as to how to solve this (albeit basic) issue. I'm aware that "while" loops continue whatever is in their respective curly brackets when a condition in their parenthesis continues to be a met.
When I tried setting the while condition to while (digit >= 10), it resulted in an infinite loop (correct me, but it is due to the fact that if the user inputs a digit of 10 or greater, the condition will KEEP being met and continue infinitely). So, I tried setting the while condition to some boolean value, and an if nested inside with the prior condition. Now, when the user enters 10, nothing happens after, and the program ends.
How do I write the above code so that the System will continue printing "Please enter an integer:" if the condition (of inputting 10 or greater and the opposite) continues to be met?
There is a basic "poor design" issue that the variable isAnInteger has a scope wider than needed (it lives past the last line that needs it).
The "correct" approach is loop that contains the logic that determines "integerness" of the input and doesn't leave variables in scope when the loop ends, other than the captured input in digit of course.
Next, you want to separate the concerns of capturing input with checking it, so first create a method that gets a digit:
private static int readNumber(Scanner in) {
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
in.nextLine(); // you must clear the newline char from the buffer
return digit;
}
Next, write a simple while() loop that keeps reading until it gets good input:
int digit = 10; // bad input
while (digit > 9) {
digit = readNumber(in);
}
Putting it all together with the final message:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int digit = 10; // initialize with "bad" input
while (digit > 9) {
digit = readNumber(in);
}
System.out.println("Correct! " + digit + " is an integer!");
}
private static int readNumber(Scanner in) {
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
in.nextLine(); // you must clear the newline char from the buffer
return digit;
}
This approach makes the code much easier to read and understand.
Also notice how there is no repeated code (such as the line asking for a digit, or reading input).
The main conceptual piece here is that you don't update your value anywhere inside of your loop. Because it does not update, it will always remain the value it was when it entered the loop (that is, digit >= 10 will remain true until the program stops running).
You must update your values inside of your loop.
However, there's another concept you're missing: you're guaranteed to run the loop at least once, so you should take advantage of the do...while loop instead.
Note that I make use of nextLine() to avoid any wonky nextInt() issues.
(Oh, by the way: any number you're looking for is an integer. You should communicate that you're looking for an integer less than 10 instead.)
System.out.print("Please enter a digit: ");
int digit = Integer.parseInt(in.nextLine());
boolean isAnInteger;
do {
if (digit >= 10) {
System.out.println("Please enter an integer: ");
digit = Integer.parseInt(in.nextLine());
isAnInteger = false;
} else {
System.out.println("Correct! " + digit + " is an integer!");
isAnInteger = true;
}
} while (isAnInteger);
Yes, Makoto has it right.
You never update your values inside the while loop. In your original case, when you just wanted to keep printing out Please enter an integer: , you never ask for an input right after that line. Your original digit value will continue to be greater than or equal to 10, and will keep the loop going.
Even with your current code, you will still run into an infinite loop if your digit value is less than 10. Notice how the boolean isAnInteger is independent of whether your digit is less than 10.
The best way to fix this is by using something like this:
in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
while (digit >= 10)
{
System.out.println("Please enter an integer: ");
digit = in.nextInt();
}
System.out.println("Correct! " + digit + " is an integer!");
What this does is it keeps checking to see if digit is greater than or equal to 10. If so, it will continue to ask the user for an input. If at any time during the iteration of the loop the user enters a value less than 10, it will not execute the next iteration, and leaves the loop. It will then execute the last println.
However, if the first input is less than 10, it will skip the while loop and execute the println at the bottom.
If you want to use a boolean like you did, you can do it in such a manner:
in = new Scanner(System.in);
System.out.print("Please enter a digit: ");
int digit = in.nextInt();
bool isAnInteger = true;
if (digit >= 10)
isAnInteger = false;
while (!isAnInteger) // checks if digit is not an integer
{
System.out.println("Please enter an integer: ");
digit = in.nextInt();
if !(digit >= 10)
isAnInteger = true;
}
System.out.println("Correct! " + digit + " is an integer!");
Makoto's way of using a do while loop is probably better, although this may be a better way of visualizing it (since you used a while loop).
I am self-learning Java and am stuck on a simple project. I'd like to receive 6 unique 'lottery' numbers from a user.
User will be asked to input an integer.
Each user input will be placed into an array.
If the user inputs a previously input number, I want to prompt to reenter the number again.
Recheck the new input. If unique, continue the for loop. If non-unique, run step 3 again.
So far, all I have is:
public static int[] userLottoInput()
{
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < userNums.length; i++ ) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
for (int k=i; k<userNums.length; k++) {
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}
}
}
Any help is appreciated!!
Try and keep you logic simple.
While the user hasn't enter 6 numbers, loop
Ask the user for a value
Check to see if it's a duplicate
If it is, ask the user to re-enter the value
If it's not (a duplicate) increment the counter to the next element...
For example...
public static int[] userLottoInput() {
int[] userNums = new int[6];
Scanner keyboard = new Scanner(System.in);
int i = 0;
// Keep looping until we fill the array, but
// allow the control to fall somewhere else
while (i < userNums.length) {
System.out.printf("Enter Lottery number %d: ", i + 1);
userNums[i] = keyboard.nextInt();
// Check for duplicates
boolean duplicate = false;
// We only need to check up to i - 1, as all the
// other values are defaulted to 0
// We also don't need to check for the last number entered ;)
for (int k = 0; k < i; k++) {
// Check for duplicated
if (userNums[k] == userNums[i]) {
System.out.println("No duplicates allowed, please try again");
duplicate = true;
// Break out of the loop as we don't need to check any more..
break;
}
}
// If no duplicates where found, update i to the next position
if (!duplicate) {
i++;
}
}
return userNums;
}
With this, there is only one point at which you prompt the user. Everything else is used to control the element position (i) to meet your requirements.
Now, I'm sure that there are other ways to do this and this is just a simple example ;)
Move the asking of number outside loop, when received the number loop over the numbers array to find a match. If match found re-ask for number (outside the for loop used for finding the match), else if match not found, then add the number to array.
Don't you think your for loop is little complicated. Anyways, you can try this :
for (int k=0; k<i-1; k++) { //Start k=0 means from the first stored value
while (k!=i && userNums[k] == userNums[i]) {
System.out.printf("if");
System.out.printf("Error! Try again: ");
userNums[i] = keyboard.nextInt();
}
}