I was working on a bit of code where you would take an input of 2 numbers, separated by a comma, and then would proceed to do other actions with the numbers.
I was wondering how I would parse the string to take the first number up to the comma, cast it to and int and then proceed to cast the second number to an int.
Here is the code I was working on:
Scanner Scan = new Scanner(System.in);
System.out.print("Enter 2 numbers (num1,num2): ");
//get input
String input = Scan.nextLine();
//parse string up to comma, then cast to an integer
int firstNum = Integer.parseInt(input.substring(0, input.indexOf(',')));
int secondNum = Integer.parseInt(Scan.nextLine());
Scan.close();
System.out.println(firstNum + "\n" + secondNum);
The first number is cast to an integer just fine, I run into issues with the second one.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
How would I be able to then take the second integer out of the input string and cast it to an Int.
The error mode you're encountering seems reasonable indeed, as you're reading the next line from the scanner and therefore explicitly no longer operating on the first input anymore.
What you're looking for is probably this:
int secondNum = Integer.parseInt(input.substring(input.indexOf(',') + 1));
When defining secondNum, you're setting it equal to the parsed integer of the next line the scanner object reads, but all of the data has already been read. So rather than read from the scanner again, you'll want to call Integer.parseInt on everything after the comma.
It fails because all digit are given by the user on the same line. and you have two Scanner.nextLine(); the second is probably empty.
here is a solution :
Scanner Scan = new Scanner(System.in);
System.out.print("Enter 2 numbers (num1,num2): ");
//get input
String input = Scan.nextLine();
StringTokenizer st = new StringTokenizer(input, ",");
List<Integer> numbers = new ArrayList<>();
while (st.hasMoreElements()) {
numbers.add(Integer.parseInt(st.nextElement()));
}
System.out.println(numbers);
If input on one line, both the numbers will be stored in the String variable input. You don't need to scan another line. It will be empty, and you cannot cast the empty string to an int. Why not just parse the second number out of input, as you did the first.
Related
I am trying to read multiple variables from the console with the scanner in only one line (separated with a blank space).
if I type:
int hight = Integer.parseInt(reader.nextLine());
int width = Integer.parseInt(reader.nextLine());
int depth = Integer.parseInt(reader.nextLine());
then it displays my numbers (for example 1,2,3) like this:
1
2
3
but I would want it to display my numbers like that: 1 2 3
Can someone help me?
One way to do this is to use nextInt instead of nextLine:
int hight = reader.nextInt();
int width = reader.nextInt();
int depth = reader.nextInt();
Your input can then be like this:
1 2 3
Note that you have to enter all three numbers before pressing ENTER, or else your input will look like this again:
1
2
3
Another way to do this is to use a regex to specify the exact format that you want your input to be in, call nextLine, and match the line that the user entered to the regex pattern:
Matcher matcher = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)").matcher(reader.nextLine());
if (matcher.matches()) {
int height = Integer.parseInt(matcher.group(1));
int width = Integer.parseInt(matcher.group(2));
int depth = Integer.parseInt(matcher.group(3));
} else {
// input was invalid!
}
As per your comment you can simply read numbers as integers like :
Scanner br =new Scanner(System.in);
int a=br.nextInt();
int b=br.nextInt();
int c=br.nextInt();
Give input as 1 2 3.
To input all 3 values in one line you can use. . readInt() three times instead of using .readNextLine(). That way you can put your input like this 1 2 3 and after pressing Enter on the keyboard (which is by default used to end the input) you get what you were asking for.
If your intention was to get an output in one line instead of multiline one, you should use other version of method printing to the console:
System.out.print(height + " " + weight + " " + depth)
System.out.println() prints the next line character after its argument, System.out.print() doesn't.
For input in single line in space separated format. You can do that using Scanner and BufferReader in Java.
1. Scanner class
Scanner sc = new Scanner(System.in);
int[] integers;
String input = sc.nextLine();
String[] strs= input().split(" ");
for(int i=0;i<strs.length;i++){
integers[i]=Integer.parseInt(strs[i]);
}
2. BufferReader Class
BufferReader br = new BufferReader(new InputStreamReader(System.in));
int[] integers;
String input = br.readLine();
String[] strs= input().trim().split("\\s+");
for(int i=0;i<strs.length;i++){
integers[i]=Integer.parseInt(strs[i]);
}
I'm trying to write a program that is practically a stack. Given a text file with certain keywords, I want my program to evaluate the text line by line and perform the requested action to the stack.
For example, if the input file is:
push 10
push 20
push 30
The resulting stack should look like:
30
20
10
However, I don't know how to push these values into the stack without hardcoding an int value after the word push. I made a String variable and assigned it to scanner.nextLine()
From there, I compare the line with strLine: if strLine is equal to push followed by some Number, then that number would be pushed on the stack.
However, it seems that the method nextInt() isn't taking this number from the input stream.
Scanner input = new Scanner(file)
int number;
String strLine;
while (input.hasNextLine()){
strLine = input.nextLine();
number = input.nextInt();
if(strLine.equals("push " + number)){
stack.push(number);
}
How can I fix this?
Thank you.
Get the input and split it with space " "!
That will give ["push","1"]
convert the first index to int and then push the value to stack!
while (input.hasNextLine()){
String[] strLine = input.nextLine().split(" ");
if(strLine[0].equals("push")){
stack.push(Integer.parseInt(strLine[1]));
}
else if(strLine[0].equals("pop")){
stack.pop();
}
else{
system.out.println("Please enter a valid input!");
}
}
Hope it helps!
input.nextLine reads the whole line, including the number. What you can do instead is to use input.next() to get the "push" and input.nextInt() to get the number. This example is using Scanner with System.in (so it needs "quit" to exit the while loop), but it should also work with a file (in which case you don't need to type "quit" to exit the program, as it will do so automatically when the input file has no more input). The advantage of using parseInt (as some of the other answers have suggested) is that you can catch any errors in integer input using a try/catch block.
import java.util.Scanner;
import java.util.Stack;
import java.util.InputMismatchException;
public class StackScanner {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
Scanner input = new Scanner(System.in);
int number;
String strLine;
while (input.hasNext()){
strLine = input.next();
if(strLine.equals("push")){
try {
number = input.nextInt();
stack.push(number);
} catch ( InputMismatchException e) {
System.out.println("Invalid input. Try again.");
input.nextLine();
continue;
}
} else {
break;
}
}
System.out.println(stack);
}
}
Sample output:
push 5
push 6
push 3
quit
[5, 6, 3]
change this:
number = input.nextInt();
to this:
number = Integer.parseInt(input.nextLine());
nextLine method parses the whole line including any numbers in the line. So, you need to take care of splitting the line and parsing the number in your code.
Something like below will work where I split the line with spaces. Although, there are many such ways possible.
Scanner input = new Scanner(file);
String strLine;
Stack<Integer> stack = new Stack<>();
int number;
while (input.hasNextLine()){
strLine = input.nextLine();
if(strLine.startsWith("push")){
String[] sArr = strLine.split("\\s+");
System.out.println(strLine);
if(sArr.length==2){
number=Integer.parseInt(sArr[1]);
stack.push(number);
System.out.println(number);
}
}
}
If I understand your problem, I would simply tokenize the line by splitting on whitespace.
It looks like your input is relatively structured: you have a keyword of some kind then whitespace then a number. If your data is indeed of this structure, split the line into two tokens. Read the value from the second one. For example:
String tokens[] = strLine.split(" ");
// tokens[0] is the keyword, tokens[1] is the value
if(tokens[0].equals("push")){
// TODO: check here that tokens[1] is an int
stack.push(Integer.parseInt(tokens[1]));
} else if (tokens[0].equals("pop")) { // maybe you also have pop
int p = stack.pop();
} else if ... // maybe you have other operations
I am writing a program and I need to input a value for index, but the index should be composite, e.g 44GH.
My question is, how to make the program to do not crash when I ask the user to input it and then I want to display it?
I have been looking for answer in the site, but they are only for integer or string type.
If anyone can help, would be really appreciated.
Scanner s input = new Scanner(System.in);
private ArrayList<Product> productList;
System.out.println("Enter the product");
String product = s.nextLine();
System.out.println("Input code for your product e.g F7PP");
String code = s.nextLine();
}
public void deleteProduct(){
System.out.println("Enter the code of your product that you want to delete ");
String removed = input.nextLine();
if (productList.isEmpty()) {
System.out.println("There are no products for removing");
} else {
String aString = input.next();
productList.remove(aString);
}
}
Remove all non digits char before casting to integer:
String numbersOnly= aString.replaceAll("[^0-9]", "");
Integer result = Integer.parseInt(numbersOnly);
The best way to do it is to create some RegEx that could solve this problem, and you test if your input matches your RegExp. Here's a good website to test RegExp : Debuggex
Then, when you know how to extract the Integer part, you parse it.
I think the OP wants to print out a string just but correct me if I am wrong. So,
Scanner input = new Scanner(System.in);
String aString = input.nextLine(); // FFR55 or something is expected
System.out.println(aString);
Then obviously you can use:
aString.replaceAll();
Integer.parseInt();
To modify the output but from what I gather, the output is expected to be something like FFR55.
Try making the code split the two parts:
int numbers = Integer.parseInt(string.replaceAll("[^0-9]", ""));
String chars = string.replaceAll("[0-9]", "").toUpperCase();
int char0Index = ((int) chars.charAt(0)) - 65;
int char1Index = ((int) chars.charAt(1)) - 65;
This code makes a variable numbers, holding the index of the number part of the input string, as well as char0Index and char1Index, holding the value of the two characters from 0-25.
You can add the two characters, or use the characters for rows and numbers for columns, or whatever you need.
I have a question regarding reading strings from java console. When I give input of words each line until I stop with "stop" All those words should be stored in one array of string.
My input will be:
apple
Mango
grapes
stop -----> on stop the string ends here
All the 3 fruit names will be stored in temp.
But when I type one word and want to type another by clicking enter to go to next line, it prints the output.
How should I modify this?
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the words");
String temp=scanner.nextLine();
Your problem is that you're reading one line from console and print it.
What you should do is keep reading lines until "stop", and that could be done by having a while loop.
This code should work well for you:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the words");
String input = scanner.nextLine(); // variable to store every input line
String fruits = ""; // this should store all the inputs in one string
while(! input.equals("stop")) {
fruits += input + ","; // using comma to separate the inputs
input = scanner.nextLine();
}
String[] res = fruits.split(","); // splitting the string to have its content in an array
I'm writing a program for an assignment where the the user can search contents of a text file. The text file contains lines with Text and Numbers.
I want to prompt the user to enter a number, (e.g. a pin number), and a compare sign (=, <, >,)
I want to fetch and print where the number in the lines of file that matches the given number based on the given compare sign.
Here is what I have so far:
System.out.print("Enter integer: ");
String Value = input.next();
System.out.print("Enter type (=, <, >): ");
String Type = input.next();
while (file.hasNextLine())
{
String lines = file.nextLine();
if(lines.contains(Value))
{
if (compareType.equals(">"))
{
System.out.println(lines);
}
}
I appreciate any help you can give. Thanks.
Although I am not certain what you are asking, here is what I can give you from my understanding of your request.
You start off correctly getting the required values from the user.
System.out.print("Enter integer: ");
String val = input.next();
System.out.print("Enter type (=, <, >): ");
String operator = input.next();
while(file.hasNextLine()){
String line = file.nextLine();
if(operator.equals("=") && line.contains(val)){ //check if operator is equals and if line contains entered value
System.out.println(line);//if so, write the current line to the console.
}else if(operator.equals(">")){//check if operator is greater than
String integersInLine = line.replaceAll("[^0-9]+", " ");//we now set this to a new String variable. This variable does not affect the 'line' so the output will be the entire line.
String[] strInts = integersInLine.trim().split(" "))); //get all integers in current line
for(int i = 0; i < strInts.length; i++){//loop through all integers on the line and check if any of them fit the operator
int compare = Integer.valueOf(strInts[i]);
if(Integer.valueOf(val) > compare)System.out.println(line);//if the 'val' entered by the user is greater than the first integer in the line, print the line out to the console.
break;//exit for loop to prevent the same line being written twice.
}
}//im sure you can use this code to implement the '<' operator also
}