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);
Related
So I'm building a program that reads user input in integers and adds the value of all the integers togther
My main method is :
public static void main(String[] args) {
My current code is :
Scanner scanner = new Scanner(System.in); // imports scanner
System.out.print("Enter an number: "); // ask user to enter number
// Repeat until next item is an integer
while (!scanner.hasNextInt())
{
scanner.next(); // Read and discard offending non-int input or int + not int input
System.out.print("Please enter digits only: "); // tells user to enter again
}
// if user enters int , exits while loop
//adds ints entered
int userNumber = scanner.nextInt(); // Gets the int
int sumofUsernumber = (0);
while (userNumber > 0) {
sumofUsernumber = sumofUsernumber + userNumber % 10;
userNumber = userNumber / 10;
}
System.out.println("The combined value of " + userNumber + (" is ") + sumofUsernumber)
In the last line it supposed to print ther number the user enetered then the sum of the number, instead it prints, 0.
For example : if user enters 101 I'm trying to get it to print
"The combined value of 101 is 2"
Instead it prints
"The combined value of 0 is 2"
You need to store userNumber in some other variable as you are mutating the input from user directly.
The following code will help you
// adds ints entered
int userNumber = 101;
int temp = userNumber;
int sumofUsernumber = 0;
while (temp > 0) {
sumofUsernumber = sumofUsernumber + temp % 10;
temp = temp / 10;
}
System.out.println("The combined value of " + userNumber + (" is ") + sumofUsernumber);
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 have to do a program that returns the reverse of a number that is input by a user, event the numbers that start and finish with 0 (ex. 00040, it would print 04000)
I was able to do the reverse of the number, but it doesn't print out the 0's and I can't use String variables, just long variables or integers.
Here is my code:
import java.util.Scanner;
public class Assignment_2_Question_2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Welcome to Our Reversing Number Program");
System.out.println("-----------------------------------------");
System.out.println();
System.out.println("Enter a number with at most 10 digits:");
long number = keyboard.nextInt();
long nbDigits = String.valueOf(number).length();
System.out.println("Number of digits is " + nbDigits);
System.out.print("Reverse of " + number + " is ");
long revNumber = 0;
while (number > 0){
long digit = number % 10;
if (digit == 0){ // The teacher told me to add this
nb0 ++; // need to not take into account the 0's inside the number
}
revNumber = revNumber * 10 + digit;
number = number/10;
}
for (int i = 0; i < nb0; i++) { // This will print the number of 0's counted by the if statement and print them out.
System.out.println("0");
}
System.out.println(revNumber);
String answer;
do{
System.out.println("Do you want to try another number? (yes to repeat, no to stop)");
answer = keyboard.next();
if (answer.equalsIgnoreCase("yes")){
System.out.println("Enter a number with at most 10 digits:");
long otherNumber = keyboard.nextInt();
long nbrDigits = String.valueOf(otherNumber).length();
System.out.println("Number of digits is " + nbrDigits);
System.out.print("Reverse of " + otherNumber + " is ");
long reversedNumber = 0;
while (otherNumber != 0){
reversedNumber = reversedNumber * 10 + otherNumber%10;
otherNumber = otherNumber/10;
}
System.out.println(reversedNumber);
}
else
System.out.println("Thanks and have a great day!");
}while(answer.equalsIgnoreCase("yes")&& !answer.equalsIgnoreCase("no"));
}
}
Can someone help me? Thank you
Probably not what is intended but clearly (based on problem statement) you must see all digits entered (to include leading 0's) otherwise it is an "impossible solution" - and you state you cannot receive input as a String...
So this snippet reads one digit at a time where each digit is received as an int:
Scanner reader = new Scanner(System.in);
reader.useDelimiter(""); // empty string
System.out.print("Enter number: ");
while (!reader.hasNextInt()) reader.next();
int aDigit;
int cnt = 0;
while (reader.hasNextInt()) {
aDigit = reader.nextInt();
System.out.println("digit("+ ++cnt + ") "+aDigit);
}
System.out.println("Done");
Prints (assume user enter 012 (enter)):
Enter number: digit(1) 0
digit(2) 1
digit(3) 2
Done
You naturally have more work to do with this but at least you have all user entered digits (including leading zeros).
You can use buffer reader;
Like this given code And if you want to do some arithmetic operations in the numbers then you can convert it into int using parseInt method.:-
import java.util.Scanner;
import java.lang.*;
class Main {
public static void main(String args[])
{
System.out.println("ENTER NUM");
Scanner SC = new Scanner(System.in);
String INP = SC.nextLine();
StringBuffer SB = new StringBuffer(INP);
SB.reverse() ;
System.out.println(SB);
}
}
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]);
}
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();
}
}