I want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried writing
System.out.println("If you take" + stepsOne * firstNum + "steps in a 10 second interval, you could potentially achieve...");
and just about every variation I can think of but I keep getting error messages. Apparently javac hates me for some reason. :/
Also, whenever the greeting displays, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
Here's my code:
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner userInputScanner = new Scanner(System.in);
int firstNum;
firstNum = 6;
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello," + userName + ". How many steps do you take in a ten second interval?");
String stepsOne = userInputScanner.nextLine();
System.out.println("If you take" + stepsOne + "steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute:");
System.out.println ("Number of steps per hour:");
}
}
There is a crucial difference between the string 123 and the integer 123 - the first is merely a sequence of characters, which have no mathematical meaning. You need to parse the string, meaning that you must construct an integer based on the characters of the string. There's a built-in method for this (although it's very interesting to do it yourself too): Integer.parseInt().
String stepsOneString = userInputScanner.nextLine();
int stepsOne = Integer.parseInt(stepsOneString);
Now, stepsOne is an integer on which you can perform mathematical operations. However, Integer.parseInt() throws an exception that you'll need to handle. At this point in your course, I'm guessing that you're expected to use the built-in conversion capabilities of the Scanner:
int stepsOne = userInputScanner.nextInt();
This will essentially perform the two above steps for you.
I strongly recommend that you read up on the subject of data types, which will explain the above concepts.
Once you have a string representing a number, you can use Integer.parseInt() to get an integer from it.
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
Here is a complete program with improved spacing.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Bob. What is your name?");
String userName = userInputScanner.nextLine(); //Asks user name
System.out.println("Hello, " + userName +
". How many steps do you take in a ten second interval?");
String stringSteps = userInputScanner.nextLine();
int steps = Integer.parseInt(stringSteps);
System.out.println("If you take " + steps +
" steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + (6 * steps));
System.out.println ("Number of steps per hour: " + (60 * 6 * steps));
}
}
Basically, I just want to take a number the user enters and multiply it by a couple of different numbers I set but I can't figure out how to declare an integer and get it to play nicely with whatever number the user enters. I've tried typing
First problem is stepsOne is String, so it can't be used to perform arithmetic on (at least not they type you're trying). So you need to convert it to a int
int stepsOneInt = Integer.parseInt(stepsOne);
nb: This will throw a NumberFormatException if the String can't be converted to a int value, so beware of that
Now you can use it to perform other arithmetic tasks
System.out.println("If you take " + (stepsOneInt * firstNum) + " steps in a 10 second interval, you could potentially achieve...");
Also, whenever the greeting displays in javac, there's no space between the data the user enters and my system.out.println stuff so if they enter the name "George" it comes out as "HelloGeorge". Not as big of an issue as the above but if you know how to fix that then have at it. :)
That's because you don't add any spaces before you print the value
System.out.println ("Hello, " + userName + ". How many steps do you take in a ten second interval?");
Not sure to understand your issue...
You can't do stepsOne*firstNum as stepsOne is a String.
If stepsOne must be an int, just do this:
int stepsOne = userInputScanner.nextLine(); //Asks user a nb
Related
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);
import java.util.Scanner;
public class Tipping {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Please enter initial price followed by tip percentage: ");
double Price = s.nextDouble(); double TipRate = s.nextDouble();
double TipAmount;
TipAmount = (Price*TipRate)/100;
System.out.println("Tip amount: " + TipAmount);
System.out.print("Total price: " + (TipAmount + Price) +".");
}}
I always get the price on the first line and the tiprate on the other.
Judging by your wording, you don't like that when input is handled via the Scanner, pressing Enter on the first double value (The Price) it advances to the next line and waits for the second double value (The TipRate). First of all, the character "Enter" is essentially the system dependent new-line character, so the Scanner immediately splits the input when the enter key is pressed. Specifically, the Scanner uses the Character.isWhiteSpace(char ch); function to evaluate where to split the tokens.
It all depends on how you want your input handled. Sadly, without importing a Curses-esque library and using a custom command prompt, the "\n" character cannot be reversed. What you can do is write your input and separate it by a space, for example writing "23.4 12.3" will write the input in the same line and correctly break the line into the 2 tokens you want.
If it is purely for aesthetic reasons you could catch the token as a String, evaluate if the "\n" character exists within and ask the user to re-input the variables in a single line or, if the "\n" character doesn't exist, split the String on the " " character and then use the Double.valueOf(String str); function.
Beware not to use the (Scanner in).setDelimiter(String str) since that will avoid breaking the tokens on the "\n" character (If the str String is for example " ") and will only freeze your program until the user splits 2 inputs with the space character and then throw an InputMismatchException because 12.3\n12.3 32.3 would be "valid" input but the token "12.3\n12.3" can't be evaluated to a single Double variable.
Sure, avoid calling:
System.out.println()
As the name (somehow) indicates, that prints a whole "line"; ending with a line break.
So, either call System.out.print() multiple times; or better practice: call System.out.println() once, but give all the strings you wanted to be printed to that call.
And as I just saw your comment: you are calling println() - in the line before you call print()!
Given your comment: you have to understand how that scanner works. The scanner reads strings; and by default, line by line.
In other words: when you use nextDouble() then the scanner assumes that you will enter a string that represents a number - but that your input is "terminated" by the user pressing ENTER. In other words; those line breaks are inevitable!
So, simply deal with them like:
System.out.print("Please enter initial price: ");
double Price = s.nextDouble();
System.out.print("Please enter tip percentage: ");
double TipRate = s.nextDouble();
double TipAmount = (Price*TipRate)/100;
System.out.println("Tip amount: " + TipAmount + " results in Total price: " + (TipAmount + Price) +".");
Long story short: when using the console in/out like this; you can't prevent certain line breaks. Simply accept that, and don't get to much into perfectionism.
Use instead of System.out.println (which stands for print line) with System.out.print. The System.out.println will print an line break after the given string on the output stream.
You could also combine the print's with a single print line.
For example you could use this:
System.out.println(String.format("Tip amount: %f Total Price: %f", TipAmount, (TipAmount + Price)));
Update
Simple solution for the scanner problem would be to input the numbers in one line separated with a whitespace.
Today started learning Java and I need help to clear my doubt.
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
Scanner leo = new Scanner(System.in);
double f, s;
System.out.println("Enter first number: ");
f = leo.nextDouble();
System.out.println("Enter second number: ");
s = leo.nextDouble();
System.out.println("The sum is " + f + s);
}
}
When I write +f+s then both are treated as String.
Enter first number: 2
Enter second number: 5
The sum is 2.05.0
But when I write (f+s) then they are treated as doubles (which is the desired result).
Enter first number: 3
Enter second number: 4
The sum is 7
Why does that happen?
Also why do we write the line import java.util.Scanner before the class JavaAapplication1?
P.S. Is this series of videos Video Link good for learning Java?
I suspect that what matters is the order of operation
In
System.out.println("The sum is:"+f+s)
The first operation is "The sum is:"+f so the + operator takes a string and a double as operands and the f variable is cast to its string value. Then second + operator takes "The sum is:2"+0.5 and again we have a conversion from double to string.
However, in
System.out.println("The sum is:"+(f+s))
We first have f+s calcualted which is an addition between two doubles followed by a concatenation.
I hope this makes sense.
It is the BODMAS rule which stands for Brackets, Orders, Division, Multiplication, Addition, Subtraction
Since you dont add them in brackets, it adds(concatenates) the string. It evaluates everything within the bracket
("string" + f + s)
Unless you specifically add brackets
("string" + (f + s))
In this case, the inner brackets are evaluated first and then the outer.
Also why do we write the line import java.util.scanner before the
class java application 1?
In order to use the imported stuff in the class, you need to import before class, so the compiler knows.
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.
I have a college assignment where I need to print out items sold by a hardware store, take input from a user, perform some calculations on that input, and then print out an invoice.
I have been able to successfully print out the items sold by the hardware store, but am encountering problems with the while loop that takes the input.
The program asks the user to enter a CODE and then asks for the corresponding QUANTITY. This works fine on the first iteration of the loop, but on the second iteration the user prompts for "CODE:" and "QUANTITY:" appear on the same line, despite my use of println when prompting the user.
I would greatly appreciate a detailed response appropriate for someone new in programming.
Here's the code:
import java.util.Scanner;
class HardwareStore {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO THE HARDWARE STORE!");
System.out.println("----------------------------------------------------------------------");
String sticky = "G22";
String keyring = "K13";
String screwy = "S21";
String padlock = "I30";
int stickyprice = 10989;
int keyringprice = 5655;
int screwyprice = 1099;
int padlockprice = 4005;
System.out.println("CODE\t\tDESCRIPTION\t\t\t\t\tPRICE");
System.out.println("----\t\t-----------\t\t\t\t\t-----");
System.out.println(sticky + "\t\tSTICKY Construction Glue, Heavy Duty, \n\t\t7oz, 12 Pack \t\t\t\t\t$" + stickyprice);
System.out.println(keyring + "\t\tCAR-LO Key Ring, Quick Release, \n\t\t1 Pack\t\t\t\t\t\t$ " + keyringprice);
System.out.println(screwy + "\t\t!GREAT DEAL! SCREW-DUP Screwy Screws, \n\t\tDry Wall Screws, 3 in. Long, 50 Pack\t\t$ " + screwyprice);
System.out.println(padlock + "\t\tLET-IT-RAIN, Weather Proof Padlock, \n\t\tPortable, One Push Functionality\t\t$ " + padlockprice);
System.out.println("----------------------------------------------------------------------");
int i = 10000;
String [] usercode = new String[i];
int [] userquantity = new int[i];
System.out.println("PLEASE ENTER YOUR ORDER:");
while (true) {
System.out.println("CODE: (X to terminate)");
usercode[i] = in.nextLine();
if (usercode[i].equalsIgnoreCase("x")) {
break;
}
System.out.println("QUANTITY: ");
userquantity[i] = in.nextInt();
}
}
}
when you enter the QUANTITY you're pressing enter. That newline character isn't used by in.nextInt();, it remains in the scanner buffer, until you roll around to in.nextLine() again.
At that point in.nextLine() reads until it finds a newline character, which just happens to be the next one in the buffer. So it skips straight to QUANTITY again.