I am trying to write some basic code for a class that wants me to pick 3 random numbers and then ask the user for input and see if those random numbers match in different ways. Anyway i am specifically required to use a for loop to generate these 3 numbers, but it is only generating one. Please help.
EDIT: I removed the problematic line, however now it seems i concatenated wrong and my firstNumber, secondNumber, and all those kinds of variables are blank? I am not sure what is causing this
import java.util.Scanner;
public class Lotteryv2
{
public static void main(String[] args)
{
//Generate a random number
String numberString = "";
for(int i = 0; i < 3; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);
numberString += lotteryNumberDigit;
}
System.out.println(numberString);
//extracting number string
String firstNumber = numberString.substring(0,0);
String secondNumber = numberString.substring(1,1);
String thirdNumber = numberString.substring(2,2);
String firstWin = firstNumber + secondNumber;
String secondWin = secondNumber + thirdNumber;
String allWin = firstNumber + secondNumber + thirdNumber;
// user guess
Scanner input = new Scanner (System.in);
System.out.println("Please enter three numbers (e.g 123): ");
String guess = input.next();
if (guess.substring(0,2).equals(firstWin))
{
System.out.println("Winner! " + allWin);
System.out.println("Congratulations, you guessed the first two numbers correctly!");
}
else if(guess.substring(1,3).equals(secondWin))
{
System.out.println("Winner! " + allWin);
System.out.println("Congratulations, you guessed the last two numbers correctly!");
}
else if(guess.equals(allWin))
{
System.out.println("Winner! " + allWin);
System.out.println("Congratulations, you guessed all three numbers correctly!");
}
else
{
System.out.println("Winner! " + allWin);
System.out.println("Sorry, you did not win");
}
//extracting three guess digits
}
}
Your loop does go for three times. However, the visible result is the same as if it were doing only one iteration, because the second iteration writes over the results of the first one, and the third iteration overwrites the results of the second iteration before you do anything with them.
Here is the problematic line:
numberString = Integer.toString(lotteryNumberDigit);
Once you remove it, your code will print a three-digit numeric string (possibly with leading zeros).
Your code that extracts the individual digits also needs changing: since endIndex is exclusive, you need to add 1 to it:
String firstNumber = numberString.substring(0, 1);
String secondNumber = numberString.substring(1, 2);
String thirdNumber = numberString.substring(2, 3);
In addition, you need to check that the value the end-user entered is at least three digits long. Otherwise you are going to get exceptions when extracting digits from the guess variable.
You are assigning the value of the number to a single String variable, thereby overriding it in each iteration. You might change it to:
String[] numberStringArray = new String[3];
for(int i = 0; i < numberStringArray.length; i++)
{
double lotto = Math.random();
int lotteryNumberDigit = (int)(lotto*10);
numberString += lotteryNumberDigit;
numberStringArray[i] = Integer.toString(lotteryNumberDigit);
System.out.println(numberStringArray[i]);
}
Related
I'm creating a simple average calculator using user input on Eclipse, and I am getting this error:
" java.util.NoSuchElementException: No line found " at
String input = sc.nextLine();
Also I think there will be follow up errors because I am not sure if I can have two variables string and float for user input.
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
String input = sc.nextLine();
float num = sc.nextFloat();
float sum = 0;
int counter = 0;
float average = 0;
while(input != "done"){
sum += num;
counter ++;
average = sum / counter;
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
Thanks a lot:)
First, the precision of float is just so bad that you're doing yourself a disservice using it. You should always use double unless you have a very specific need to use float.
When comparing strings, use equals(). See "How do I compare strings in Java?" for more information.
Since it seems you want the user to keep entering numbers, you need to call nextDouble() as part of the loop. And since you seem to want the user to enter text to end input, you need to call hasNextDouble() to prevent getting an InputMismatchException. Use next() to get a single word, so you can check if it is the word "done".
Like this:
Scanner sc = new Scanner(System.in);
double sum = 0;
int counter = 0;
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
for (;;) { // forever loop. You could also use 'while (true)' if you prefer
if (sc.hasNextDouble()) {
double num = sc.nextDouble();
sum += num;
counter++;
} else {
String word = sc.next();
if (word.equalsIgnoreCase("done"))
break; // exit the forever loop
sc.nextLine(); // discard rest of line
System.out.println("\"" + word + "\" is not a valid number. Enter valid number or enter \"done\" (without the quotes)");
}
}
double average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
Sample Output
Enter the numbers you would like to average. Enter "done"
1
2 O done
"O" is not a valid number. Enter valid number or enter "done" (without the quotes)
0 done
The average of the 3 numbers you entered is 1.0
So there are a few issues with this code:
Since you want to have the user either enter a number or the command "done", you have to use sc.nextLine();. This is because if you use both sc.nextLine(); and sc.nextFloat();, the program will first try to receive a string and then a number.
You aren't updating the input variable in the loop, it will only ask for one input and stop.
And string comparing is weird in Java (you can't use != or ==). You need to use stra.equals(strb).
To implement the changes:
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\"");
float sum = 0;
int counter = 0;
String input = sc.nextLine();
while (true) {
try {
//Try interpreting input as float
sum += Float.parseFloat(input);
counter++;
} catch (NumberFormatException e) {
//Turns out we were wrong!
//Check if the user entered done, if not notify them of the error!
if (input.equalsIgnoreCase("done"))
break;
else
System.out.println("'" + input + "'" + " is not a valid number!");
}
// read another line
input = sc.nextLine();
}
// Avoid a divide by zero error!
if (counter == 0) {
System.out.println("You entered no numbers!");
return;
}
// As #Andreas said in the comments, even though counter is an int, since sum is a float, Java will implicitly cast coutner to an float.
float average = sum / counter;
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the numbers you would like to average. Enter \"done\" at end : ");
String input = scanner.nextLine();
float num = 0;
float sum = 0;
int counter = 0;
float average = 0;
while(!"done".equals(input)){
num = Float.parseFloat(input); // parse inside loop if its float value
sum += num;
counter ++;
average = sum / counter;
input = scanner.nextLine(); // get next input at the end
}
System.out.println("The average of the "+ counter + " numbers you entered is " + average);
}
}
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 ");
import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.
I get a StringIndexOutOfBounds error with this Java program on the line:
String num3 = lottoString.substring(2,2);
Telling me that 2 is out of the range, but this code should randomly pick a three digit lottery number ranging from 000 through 999. What is my error?
import java.util.Scanner;
public class Lottery
{
public static void main(String[] args)
{
//Declare and initialize variables and objects
Scanner input = new Scanner(System.in);
String lottoString = "";
//Generate a 3-digit "lottery" number composed of random numbers
//Simulate a lottery by drawing one number at a time and
//concatenating it to the string
//Identify the repeated steps and use a for loop structure
for(int randomGen=0; randomGen < 3; randomGen++){
int lotNums = (int)(Math.random()*10);
lottoString = Integer.toString(lotNums);
}
String num1 = lottoString.substring(0,0);
String num2 = lottoString.substring(1,1);
String num3 = lottoString.substring(2,2);
String num12 = num1 + num2;
String num23 = num2 + num3;
String num123 = num1 + num2 + num3;
//Input: Ask user to guess 3 digit number
System.out.println("Please enter your three numbers (e.g. 123): ");
String userGuess = input.next();
//Compare the user's guess to the lottery number and report results
if(userGuess.equals(num123)){
System.out.println("Winner: " + num123);
System.out.println("Congratulations, both pairs matched!");
}else if(userGuess.substring(0,2).equals(num12)){
System.out.println("Winner: " + num123);
System.out.println("Congratulations, the front pair matched!");
}else if(userGuess.substring(1,3).equals(num23)){
System.out.println("Winner: " + num123);
System.out.println("Congratulations, the end pair matched!");
}else{
System.out.println("Winner: " + num123);
System.out.println("Sorry, no matches! You only had one chance out of 100 to win anyway.");
}
}
}
As mentioned in the other answer, every time you iterate over your loop, you reset the value of lottoString to just be one digit. You need to append to it, like this:
lottoString += Integer.toString(lotNums);
Your other problem is your use of the substring method. If both index positions are the same, such as 0,0, it returns an empty String. What you want is this:
String num1 = lottoString.substring(0,1);
String num2 = lottoString.substring(1,2);
String num3 = lottoString.substring(2,3);
for(int randomGen=0; randomGen < 3; randomGen++){
int lotNums = (int)(Math.random()*10);
lottoString = Integer.toString(lotNums);
}
You're assignining the result of Integer.toString() to lottoString. lotNums is a number between 0 and 9.
I guess you want
lottoString += Integer.toString(lotNums);
Ok so I wrote a program which asks user to input a number and then reverse it. I was successful in it however the program does not reverses numbers that end with a 0. for example if i enter 1234 it will print out 4321 however if i input 1200 it will only output 21. I tried converting the number that is to become output into string. Please help me understand where I am doing it wrong. Just remember I am a beginner at this :). Below is my code.
import java.util.*;
public class ReverseNumber
{
public static void main (String [] args)
{
Scanner n = new Scanner(System.in);
int num;
System.out.println("Please enter the number");
num = n.nextInt();
int temp = 0;
int reverse = 0;
String str = "";
System.out.println("The number before getting reversed " + num);
while (num != 0)
{
temp = num % 10;
reverse = reverse*10 + temp;
num = num/10;
str = Integer.toString(reverse);
}
//String str = Integer.toString(reverse);
System.out.println("The reversed number is " + str);
}
}
You're storing your reversed number as an int. The reverse of 1200 is 0021, but that's just 21 as an int. You can fix it by converting each digit to a string separately.
The problem is that you're calculating the reversed value as a number and, when it comes to numbers, there is no difference between 0021 and 21. What you want is to either print out the reversed value directly as you're reversing it or build it as a string and then print it out.
The former approach would go like this:
System.out.print("The reversed number is ");
while (num != 0)
{
System.out.print(num % 10);
num = num / 10;
}
System.out.println();
The latter approach would go like this:
String reverse = "";
while (num != 0)
{
reverse = reverse + Integer.toString(reverse);
num = num / 10;
}
System.out.println("The reversed number is " + reverse);
The latter approach is useful if you need to do further work with the reversed value. However, it's suboptimal for reasons that go beyond the scope of this question. You can get more information if you do research about when it's better to use StringBuilder instead of string concatenation.
I actually found this way really interesting, as this is not how I usually would reverse it. Just thought to contribute another way you could reverse it, or in this case, reverse any String.
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
int num = n.nextInt();
System.out.println("The number before getting reversed is " + num);
String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = sNum.length()-1; i >= 0; i--)
{
sNumFinal += sNum.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
If you wanted to take this further, so that you can enter "00234" and have it output "43200" (because otherwise it would take off the leading zeros), you could do:
public static void main()
{
Scanner n = new Scanner(System.in);
System.out.print("Please enter the number:");
String num = n.next(); // Make it recieve a String instead of int--the only problem being that the user can enter characters and it will accept them.
System.out.println("The number before getting reversed is " + num);
//String sNum = Integer.toString(num);
String sNumFinal = "";
for(int i = num.length()-1; i >= 0; i--)
{
sNumFinal += num.charAt(i);
}
System.out.print("The reversed number is " + sNumFinal);
}
And of course if you want it as an int, just do Integer.parseInt(sNumFinal);
The reason the two zero is being stripped out is because of the declaration of temp and reverse variable as integer.
If you assigned a value to an integer with zero at left side, example, 000001 or 002, it will be stripped out and will became as in my example as 1 or 2.
So, in your example 1200 becomes something like this 0021 but because of your declaration of variable which is integer, it only becomes 21.
import java.util.Scanner;
public class Reverse {
public static void main(String args[]){
int input,output=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter a number for check.");
input=in.nextInt();
while (input!=0)
{
output=output*10;
output=output+input%10;
input=input/10;
}
System.out.println(output);
in.close();
}
}