I have to do an assignment in my Java class using the Scanner method to input an integer (number of items), a string (name of the item), and a double (cost of the item). We have to use Scanner.nextLine() and then parse from there.
Example:
System.out.println("Please enter grocery item (# Item COST)");
String input = kb.nextLine();
The user would input something like: 3 Captain Crunch 3.5
Output would be: Captain Crunch #3 for $10.5
The trouble I am having is parsing the int and double from the string, but also keeping the string value.
First of all, split the string and get an array.
Loop through the array.
Then you can try to parse those strings in array to their respective type.
For example:
In each iteration, see if it is integer. Following example checks the first element to be an integer.
string[0].matches("\\d+")
Or you can use try-catch as follow (not recommended though)
try{
int anInteger = Integer.parseInt(string[0]);
}catch(NumberFormatException e){
}
If I understand your question you could use String.indexOf(int) and String.lastIndexOf(int) like
String input = "3 Captain Crunch 3.5";
int fi = input.indexOf(' ');
int li = input.lastIndexOf(' ');
int itemNumber = Integer.parseInt(input.substring(0, fi));
double price = Double.parseDouble(input.substring(li + 1));
System.out.printf("%s #%d for $%.2f%n", input.substring(fi + 1, li),
itemNumber, itemNumber * price);
Output is
Captain Crunch #3 for $10.50
Scanner sc = new Scanner(System.in);
String message = sc.nextLine();//take the message from the command line
String temp [] = message.split(" ");// assign to a temp array value
int number = Integer.parseInt(temp[0]);// take the first value from the message
String name = temp[1]; // second one is name.
Double price = Double.parseDouble(temp[2]); // third one is price
System.out.println(name + " #" + number + " for $ " + number*price ) ;
Related
I am working on a program that allows the user to input an integer, double, character, and a string. I have used variables to store the numbers in I am using BlueJ as my IDE, and my question is how I can reverse a system.out.println line that has variables in it?
Here is my code below:
import java.util.Scanner;
import java.lang.String;
public class Lab1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Entering a integer
int money = 0;
System.out.println("Enter an integer:");
money = input.nextInt();
//entering a double
double cost = 10;
System.out.println("Enter a double:");
cost = input.nextDouble();
//Entering a character
char a;
System.out.println("Enter a character:");
a = input.next().charAt(0);
//Entering a string
System.out.println("Please enter a string:");
String string = input.next();
System.out.println();
//Single line separated by spaces
int num = money;
double price = cost;
char b = a;
String text = string;
System.out.println("Single line:");
System.out.print(num + " " + price + " " + b + " " + text);
//Values in reverse
System.out.println();
System.out.println();
System.out.println("Values in reverse:");
}
}
Note: I am using BlueJ for this, and I have tried reversing the variables but, I couldn't.
My output:
Enter an integer:
45
Enter a double:
98.32
Enter a character:
a
Please enter a string:
welcome
Single line:
45 98.32 a welcome
The reverse of '45 98.32 a welcome' should be:
Welcome a 98.32 and 45.
Thank you and have a great day.
System.out.println("Values in reverse:");
System.out.print(text + " " + b + " " + price + " " + num)
For this simple question, I thought you need to change the order of output then it would be fine?
Anyway, if this is not your expected output, do tell me so.
In case this is what you are looking for, reverse() method is for the StringBuilder class: String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder which meant you can only reverse the string output rather than the println in Java.
The problem is like this:
I have two programs which takes input from a console but in different manner:
1)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
2)
Scanner input = new Scanner(System.in);
int temp1 = input.nextInt();
// input.nextLine();
String str = input.nextLine();
int temp2 = Integer.parseInt(str);
int total = temp1+temp2;
System.out.println(total);
In 1st case 1 take inputs in 2 different lines like
1
2
so it gives correct answer but in 2nd case I removed the input.nextLine() statement to take inputs in a single line like:
1 2
it gives me number format exception why?? and also suggest me how I can read integers and strings from a single line of a console.
The problem is that str has the value " 2", and the leading space is not legal syntax for parseInt(). You need to either skip the white space between the two numbers in the input or trim the white space off of str before parsing as an int. To skip white space, do this:
input.skip("\\s*");
String str = input.nextLine();
To trim the space off of str before parsing, do this:
int temp2 = Integer.parseInt(str.trim());
You can also get fancy and read the two pieces of the line in one go:
if (input.findInLine("(\\d+)\\s+(\\d+)") == null) {
// expected pattern was not found
System.out.println("Incorrect input!");
} else {
// expected pattern was found - retrieve and parse the pieces
MatchResult result = input.match();
int temp1 = Integer.parseInt(result.group(1));
int temp2 = Integer.parseInt(result.group(2));
int total = temp1+temp2;
System.out.println(total);
}
Assuming the input is 1 2, after this line
String str = input.nextLine();
str is equal to " 2", so it can't be parsed as int.
You can do simply:
int temp1 = input.nextInt();
int temp2 = input.nextInt();
int total = temp1+temp2;
System.out.println(total);
in your next line there is no integer ... its trying to create and integer from null ... hence you get number formate exception. If you use split string on temp1 then you get 2 string with values 1 and 2.
how can I look for an word in a array list? in my code I search the array by position using get, but I want to compare a string (from user input) to the elements of the array, and then if it's found print all the elements contained in the position where the string was found.
import java.util.ArrayList;import java.util.Scanner;
public class Shoes {
Scanner input = new Scanner(System.in);
ArrayList shoesList = new ArrayList();
public void Shoe1() {
int Shoe1;
String Color1;
float Size1;
float Price1;
System.out.println("Enter model of the shoe: ");
Shoe1 = input.nextInt();
System.out.println("Enter color of the shoe: ");
Color1 = input.next();
System.out.println("Enter size of the shoe: ");
Size1 = input.nextFloat();
System.out.println("Enter price of the shoe: ");
Price1 = input.nextFloat();
shoesList.add("" + "model: " + Shoe1 + "\n" + "color: " + Color1 +//adds the variables, shoe, color, size and
"\n" + "size: " + Size1 + "\n" +"price: " + Price1); //price to one spot of the array
}
public void getSpecific(int value){
//gets and specific value taking input from the user
int select = value;
System.out.println(shoesList.get(select));
}
so what i want to do is search by the model of the shoe, say i have a model 1, if i search for "model 1" i want the program to display all the information stored in the position of the array where model 1 is.
You have a List of String you can use either startsWith(String) or contains(CharSequence). However, you should probably move those fields into your Shoes class and store instances of Shoes in your List.
No problem!
So, we want to:
1. Loop over the shoeList
2. See which shoe has the text
3. Print that shoe
//Note: Instead of taking an int, its better to take all the String. Example "model 1".
public void printShoe(String value){
for(String shoe : shoeList){ //The sign ":" said that, for every String in shoeList,
//do the following
if(shoe.contains(value))
{System.out.println(shoe);break;}//Break will make it not print more than 1 shoe
}
}
This method will do it.
String getIfContainsUserInput(String userInputString)
{
for (String shoeString : shoesList)
{
if (shoeString.matches(".*" + Pattern.quote(userInputString) + ".*"))
return shoeString;
}
return null;
}
How do I enter a digit like '23423' and output it like '2 3 4 2 3'? And how do I make it so that user cannot enter less or more than 5-digits?
(Your help would be appreciated. I just need hints from you guys since I'm learning Java. Looking forward to learn something new.)
This is what I have so far:
Scanner input = new Scanner(System.in);
int value1, value2, value3, value4, value5;
System.out.print("Enter a number: ");
value1 = input.nextInt();
System.out.print("Enter a number: ");
value2 = input.nextInt();
System.out.print("Enter a number: ");
value3 = input.nextInt();
System.out.print("Enter a number: ");
value4 = input.nextInt();
System.out.print("Enter a number: ");
value5 = input.nextInt();
System.out.printf(" %d " + " %d " + " %d " + " %d " + " %d\n ", value1, value2, value3, value4, value5);
It can be redone with a loop: make the loop read the input 5 times and, each time, put the i-th read value at the i-th position of an array.
Then, to print it, you can just use a for loop that prints each element of the array.
If you really want them to enter a single 5 digit number, you're going to have to do validation on the users input and then give an error if the input isn't valid. If the requirements are such that the first digit of your 5 digit number should never be zero, you can just get an int and then check if it is greater than 9999 and less than 100000. Otherwise take it as a string and check the length, then turn it into an integer once you have validated it.
The most appropriate solution seem to me a while loop where you build a string and add a space. In the aftermath of the while processing you should eliminate the last space. Something like the following should fit your needs. I have used the apache commons project, but you also utilize your own class.
Scanner scanner = new Scanner(System.in);
String str = "";
while (scanner.hasNext()) {
String next = scanner.next();
if (next.equals("E")) {
break;
}
if (NumberUtils.isNumber(next)) {
for (int i = 0; i < next.length(); i++) {
str += Integer.valueOf(next.substring(i, i + 1)) + " ";
}
}
}
str = str.substring(0, str.length() - 1);
System.out.println("your number: " + str);
With "E" you can exit the loop.
I just started learning Java and I'm having trouble formatting string. In the problem I have a string a user inputted that is a name in the format: "First Middle Last". I need to output the string in the format: "Last, First MI. " (MI is middle initial).
Here is what I have so far, I have the first name working, but unsure how to go about getting the last and middle initial out of the string.
// Variable declarations
String name, first, last, middle;
Scanner scan = new Scanner (System.in);
// Get name from user in format "First Middle Last"
System.out.println("Enter the person's name: ");
name = scan.nextLine();
// Get first, middle initial, and last name from the string
first = name.substring(0, name.indexOf(" "));
middle =
last =
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middle + ".");
so for example if the user entered: "John Robert Doe", it would output as "Doe, John R."
Any help is appreciated.
You can use the split method of the String class
// Get first, middle initial, and last name from the string
String nameParts [] = name.split(" ");
// not sure if you need these variables, but I guess you get the picture
first = nameParts [0];
middle = nameParts [1];
last = nameParts [2];
middleInital = middle.charAt(0);
// Output formatted name as "Last, First MI."
System.out.println(last + ", " + first + " " + middleInital + ".");
Take a look at the String.split method. This allows you to find the substrings. Then you only have to place them in the correct order
Take a look at String split and charAt method of String class.
String person_data = "John Robert Doe" ;
String[] data = person_data.split(" ");
char MI = data[1].charAt(0);
System.out.println(data[2] +","+ data[0] + " "+ MI);
Output = Doe,John R
Here
Data[0] == "John"
Data[1] == "Robert"
Data[2] == "Doe"
MI = first character of Data[1] which is R.
Try this:
String name = "First Middle Last";
String[] data = name.split(" ");
String formatted = String.format("%s, %s %c.", data[2], data[0], data[1].charAt(0));
The last line assigns the value "Last, First M." to the variable formatted, as expected. This solution makes use of Java's Formatter class, which is a big help for all your string formatting needs.
You will need to first split the string (using String.split) and then format it.
Forgive me since I'm typing this on my iPad, the answer will look as follows:
String names = name.split("\\s+"); \\Split on whitespaces, including tab, newline and carriage return.
StringBuilder sb = new StringBuilder();
for (int x = 0; x < names.length; x++) {
switch (x) {
case 0: sb.apppend(names[names.length - 1]).append(", ");
break;
case 1: sb.append(names[0]).append(" ");
break;
case 2: sb.append(Character.toUpperCase(names[1].charAt(0))).append(".");
break;
default: break;
}
}
String fullName = sb.toString();