This question already has answers here:
Most efficient way of converting String to Integer in java
(11 answers)
Closed 7 years ago.
My assignment is to create a randomly generated number, ask the user to enter a number, then compare the two and show a messagebox telling whether or not they match. This is my code so far...
import javax.swing.*; //GUI components
public class RandomGuessMatch {
public static void main(String[] args) {
Integer random = (1 + (int)(Math.random() * 5)),
userNum;
// Get the input
userNum = JOptionPane.showInputDialog("Enter a number 1 - 5.");
//Checks to see if numbers match
boolean matches = (random == userNum);
JOptionPane.showMessageDialog(null, "The random number is " + random + ". " + "Does it match? " + matches);
}
}
The only error I'm getting is when I'm trying to get the user input. "Cannot convert from String to Integer". But, I'm having trouble figuring out how to just get the user's number and correlate it to "userNum" so that I can compare it with "random". Any help?
JOptionPane's showInputDialog method returns a String. What you can do is use the resultant string as an argument in the Integer class's constructor:
userNum = new Integer(JOptionPane.showInputDialog("Enter a number 1 - 5."));
Additionally, since you are using Integer objects, you must use the equals method to compare them:
boolean matches = random.equals(userNum);
You can convert from String to Integer trough the parse.
int x = Integer.parseInt("1");
Note that this throws an Exception if the String is NaN
You need to cast your string response into an Integer using
Integer.parseInt(userChoice)
You can get the input this way:
userNum = Integer.getInteger(JOptionPane.showInputDialog("Enter a number 1 - 5."));
Later you can do some input validation to prevent non Integer input.
ShowInputDialog will return a String. Therefore, the variable that you put its value into must also have type String.
Try making a variable called "userInput" and put the value that the user enters in there. Then you can say
userNum = Integer.valueOf(userInput);
From there, compare the two Integers using "userNum.equals(random)". The double equals operator will only work on int types, not Integers.
If you read a user input it is a String, so you have to declare userNum as a String instead an Integer.
String userNum;
The next step is to compare your random number with the String. To do that you need the method Integer.valueOf(String s), so they will be both Integer values:
boolean matches = (random == Integer.valueOf(userNum));
Have fun :)
Related
This question already has answers here:
Using charAt method, won't add them as an Int, and wont print as string. Will explain better
(4 answers)
Using charAt in System.out.println displays integer?
(5 answers)
Why does this code print the ASCII value instead of the character
(2 answers)
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I'm getting the user to enter a string of numbers, then a for loop should pick out each number from the string and add it to an ArrayList. I'm sure someone can help me out fairly quickly
My problem is as follows. When I print out all the values in the ArrayList, It is printing out much higher numbers e.g. 1234 = 49 50 51 52.
I think what is happening is that it is printing out the ASCII values rather than the numbers themselves. Can anyone spot where and why this is happening?
I have tried changing the int variable barcodeNumberAtI to a char, which yields the same result.
Apologies for lack of comments but this was only supposed to be a quick program
int tempNewDigit;
String barCode, ans;
int barcodeNumberAtI;
ArrayList <Integer> numbers = new ArrayList <Integer>();
public void addNumbers(){
Scanner s = new Scanner(System.in);
do{
System.out.println("Please enter a 12 digit barcode\n");
barCode = s.nextLine();
for(int i = 0; i < barCode.length(); i++){
barcodeNumberAtI = barCode.charAt(i);
System.out.println(barcodeNumberAtI);
numbers.add(barcodeNumberAtI);
}
System.out.print("Would you like to add another? y/n\n");
ans = s.nextLine();
} while (!ans.equals("n"));
}
public void displayNumbers(){
for(int i = 0; i < numbers.size(); i++){
System.out.print(numbers.get(i));
}
}
Happens at this line: barcodeNumberAtI = barCode.charAt(i);
barCode.charAt(i) returns a char which is converted to a int by using its ASCII value.
Use this instead:
barcodeNumberAtI = Character.digit(barCode.charAt(i), 10);
What Character.digit does is converting its first argument from the type char to the corresponding int in the radix specified by the second argument.
Here's a link to the documentation
Trying to design a simple lottery program. Everything works except checking if the numbers entered are between 1 to 59.
Exercise says the numbers must be stored in a String variable.
so
if(num<0 || num>59) //wont work for me
Tried making another variable
int numConverted = Integer.parseInt(num)
We haven't covered converting String to int in class though so I don't think this is what expected. Got confused trying that way anyway so probably this is wrong.
Here is the code I have currently.
{
Scanner scan = new Scanner(System.in);
String num=""; //num variable is empty untill user inputs numbers
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
num = num +" "+ scan.nextLine();
}
System.out.println("Ticket printed £2. Your numbers are " + num);
}
In your posted code it's obvious that you want the User to supply 6 specific numerical values. These values are appended to the String variable named num (space delimited). You need to obviously do a few things here:
1) Make sure the value supplied by the user is indeed a numerical value;
2) Make sure the numerical values supplied fall within the minimum and maximum scope of the lottery itself (which you have stated is: 1 to 59);
3) Make sure the number entered by the User hasn't been supplied already.
You've been tasked to store the entered values into a String data type variable and that is all fine but at some point you want to carry out value comparisons to make sure that all the entered values actually play within the limits of the lottery.
When the User completes his/her entries, you end up with a space delimited string held in the num string variable. You now need to make sure that these values entered are indeed....numbers from 1 to 59 and none contain alpha characters.
In my opinion (and this is only because you need to store entered values into a String variable), it's best to use your String variable to gather User input, then test the input to make sure it is indeed a string representation of an actual integer number. Once this is established then we test to make sure if falls within the value min/max limits (1-59). Now we need to test to make sure the number entered hasn't already been entered before for this ticket.
Of course with each test described above, if one fails then the User should be prompted to re-enter a proper value. You can do this by utilizing a while loop. Plenty examples of this in StackOverflow but here's a quick example:
Scanner scan = new Scanner(System.in);
String ticketNumbers = "";
for(int i = 0; i < 6; i++) {
Boolean isOK = false;
while (!isOK) {
System.out.println("\nPlease enter your desired 6 ticket numbers:\n"
+ "(from 1 to 59 only)");
String num = scan.nextLine();
//Is the string entered an actual integer number?
//We use the String.matches() method for this with
//a regular expression.
if(!num.matches("\\d+")) {
System.out.println("You must supply a numerical value! "
+ "Try Again...");
continue;
}
if (ticketNumbers.contains(num + " ")) {
System.out.println("The number you supplied has already been chosen!"
+ " Try Again...");
continue;
}
if (Integer.parseInt(num) >= 1 && Integer.parseInt(num) <= 59) {
ticketNumbers+= num + " ";
isOK = true;
}
else {
System.out.println("The number you supply must be from "
+ "1 to 59! Try Again...");
}
}
}
System.out.println("Ticket printed £2. Your numbers are " + ticketNumbers);
How about -
if(Integer.parseInt(num) < 0 || Integer.parseInt(num) > 59)
This should work, place it after the input.
If it works, please mark this as correct, I need the rep!!!
Easy way would be add available numbers (suppose it wont grow more than 60. You can use a loop to add to this as well)
String numbers[] = {"1","2","3", "..."};
Then inside the loop
Arrays.asList(numbers).contains(num);
You can remove prefixing zero in order avoid conflicts with values like '02'
Here everything is String related.
If you don't want to explicitly convert to int, you could use a regular expression.
if (num.matches("[1-5]?[0-9]")) {
...
This checks whether the String consists of (1) maybe a digit from 1 to 5, followed by (2) definitely a digit from 0 to 9. That'll match any number in the range 0-59.
If you've got a whole series of numbers separated by spaces, you could expand this to cover a whole series like this.
if (num.matches("([1-5]?[0-9]\\s+)*[1-5]?[0-9]")) {
This matches any number of repetitions (including zero) of "a number followed by spaces", followed by a single repetition without a space. The "\\s" means "any whitespace character", the "+" after it means "one or more of what precedes", and the "*" means "zero more of what precedes" - which in this case is the term in parentheses.
Oh I see what you are trying to do
This is what you want
Scanner scan = new Scanner(System.in);
String allNums = "";
for(int i =0; i<6; i++)
{
System.out.println("Enter your number between 1-59");
int num = scan.nextInt();//Take the number in as an int
if(num >0 && num < 59)//Check if it is in range
{
allNums += num + " ";//if it is add it to a string
}
else
{
System.out.println("Number not in range");
i--;//go back one iteration if its not in range
}
}
System.out.println("Ticket printed £2. Your numbers are " + allNums);
This question includes numbers with leading zeros and numbers which normally counted as hexadecimal(like 09).Assume user input is integer,because i pass number to some function as integer.
For example
if user inputs 5 i should get 1
if user inputs 0005 i should
get 4
if user inputs 09 i should get 2
(Note)Below method does not work:
String.valueOf(integer).length()
The user input will probably be a String already, so you could just use String.length(). For example:
public static void main(String... args) {
Scanner in = new Scanner(System.in);
String number = in.next();
int numDigits = number.length();
System.out.println(numDigits);
}
If the input were an integer, it couldn't have leading zeros. If the initial input had zeros and you converted it to an integer at some point, you lost this information.
This only works if the number you want is a String. You don't have 0005 integer numbers unless it is not an integer, it is a String instead.
You have to save those numbers as a String instead of a int for this to work. Then you can use the .length() method
I am trying to get this code to run and basically solve an equation. So, I asked the user to write an equation. It looked like this:
System.out.println("Write an equation and I will solve for x.");
int answer = in.nextLine();
But I can't get the user to write a string and an int. Do I need to say String answer or int answer?
An int is used when you want the user to enter a number, but here you're looking for a combination of numbers and other characters, so you will need to use a string. When you have the equation stored in a string, you can use other methods to split up the equation into something solvable, then set int answer to whatever the answer comes out to be.
On a simpler side, String will be required input from the user, User will enter the equation.
Then comes the complex part of solving/computing the equation.
1.) create your own parser to pass operands/operator.
2.) Provide a equation with values to some API, you can make use of MVEL or ANTLR
Here's a little program that demonstrates one way to get the equation and divide into numeric / non-numeric values provided the equation input is space delimited. You can then determine what the non-numeric values are and proceed from there.
import java.util.Scanner;
public class SolveX{
public static void main(String[] a){
Scanner in = new Scanner(System.in);
System.out.println("Write an equation and I will solve for x.");
String input = "";
while( in.hasNext() ){
input = in.next();
try{
double d = Double.parseDouble(input);
System.out.println("Double found at: " + input);
// Do what you need to with the numeric value
}
catch(NumberFormatException nfe){
System.out.println("No double found at: " + input);
// Do what you need to with the non numeric value
}
}
}//end main
}//end SolveX class
I'm running a java program I created that stores data inputted by user. Specifically 4 array lists which are songName, songArtist, songYear & songAlbum.
I have a user input for "songYear" and I only want the program to accept a maximum of 4 digits in length and give an error otherwise, how can this be achieved?
here's the code I have for my add entry method:
public void addEntry(){
String newName = ui.getString("Enter the name of the track");
songName.add(newName);
String newArtist = ui.getString("Who performs this track");
songArtist.add(newArtist);
String newAlbum = ui.getString("What album is this track from");
songAlbum.add(newAlbum);
System.out.print("What year was the track released? ");
int newYear=input.nextInt(4);
songYear.add(newYear);
System.out.println("\n" + "Thank you, " +songName.get(songName.size()-1) + " has been added to the library.");
System.out.println("\n" + "Press 2 to view your library." + "\n");
}
You can use regex like: ^.{4}$
Means only if user typed 4 digits - return true, otherwise return false
To be sure that user used 4 numbers YYYY use something like:
^(?=[1-9]+)\d{4}$
Makes sure the year is 1 or 2 followed by three numbers; valid ranges in this case would be 1000-2999
^(?=[1-2][0-9]+)\d{4}$
Finally your code should be like:
if(inputUserStr.matches("^(?=[1-2][0-9]+)\d{4}$")){
// do some stuff
}
else{
// print error about valid input form [YYYY]
}
Depends entirely on the language but some approaches are:
check the string input using a len function; or
convert it to an integer and ensure it's less than 10,000; or
a regular expression like ^\d{1,4}.
No doubt there'll be other validation checks such as ensuring string input is all-numeric, and you're not trying to input a song that was written twenty years in the future, but they're added checks you should consider.
1) Accept the user's input and using the substring method, save only the first four characters (Specify to user that first 4 characters are considered).
2) You can ask the user to reenter the value if it is not 4 characters:
Scanner sc = new Scanner(System.in);
String a = sc.next();
if (a.matches("...."))
{
System.out.print(a);
}
else
{
System.out.print("Input again:" );
a = sc.next();
}
I've written a sample regex for 4 characters. But you can always change it.