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]);
}
Related
I am curious how to get input data formatted from a user in java, for example if the user enters 1,2,3 how can I get these numbers in an array when the input look like this:
Scanner s = new Scanner();
String inputString = s.nextLine();
I can get a single number
Integer num = Integer.parseInt(inputString)
but I am unsure how handling multiple numbers would go
Well, you'd use... scanner. That's what it is for. However, out of the box a scanner assumes all inputs are separated by spaces. In your case, input is separated by a comma followed by/preceded by zero or more spaces.
You need to tell scanner this:
Scanner s = new Scanner(System.in);
s.useDelimiter("\\s*,\\s*");
s.nextInt(); // 1
s.nextInt(); // 2
s.nextInt(); // 3
The "\\s*,\\s*" think is a regexp; a bit of a weird concept. That's regexpese for 'any amount of spaces (even none), then a comma, then any amount of spaces'.
You could just use ", " too, that'll work, as long as your input looks precisely like that.
More generally if you have a fairly simple string you can use someString.split("\\s*,\\s*") - regexes are used here too. This returns a string array with everything between the commas:
String[] elems = "1, 2, 3".split("\\s*,\\s*");
for (String elem : elems) {
System.out.println(Integer.parseInt(elem));
}
> 1
> 2
> 3
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
While solving a problem at hacker-rank I am facing the issue that scanner/bufferedreader is unable to read the last. As the input provided by them is like
10
abcdefghijk
2
R 1 2
W 3 4
So both scanner/bufferedreader is unable to read the last line. If the input is like then the code seems to work fine.
10
abcdefghijk
2
R 1 2
W 3 4
(End of Input)
public class ScannerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int len = input.nextInt();
input.nextLine();
String inputString = input.nextLine();
int qc = input.nextInt();
input.nextLine();
System.out.println();
System.out.println(len + inputString + qc);
for(int i=0;i<qc;i++){
String l = input.next();
int le = input.nextInt();
int ri = input.nextInt();
input.nextLine();
System.out.println(l+le+ri);
}
input.close();
}
}
Here is the sample code which I am using. I know that we need a \r or\n at the end of line to readline from scanner / bufferedreader. But can anyone provide a solution to this issue as input comes from system that is predefined.
BufferedReader would read the last line even if it does not end in a line break. System.in is the culprit, that does its own line buffering.
A native system thing: suppose you pressed a couple of backspaces to change the last number...
The problem is here:
input.nextLine();
String inputString = input.nextLine();
You are consuming a line to just throw it away.
The other thing is: especially when dealing with standard libraries - don't assume that something is broken/doesn't work. In 99,999% of all case the problem is something within your code.
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.
Not sure if the title will make much sense but I'm currently quite confused and not sure how to work around my problem.
I'm trying to request from the user, a destination, a max time period (in the format HH:MM) and a maximum number of changes, which so far I have done. It should then calculate each journey’s total mins along with number of changes and then compare both with the user’s criteria, I recently edited my program to use case statements.
It does link to a .txt file that has the following data in it:
York
1
60
60
Alnwick
0
130
Alnwick
2
30
20
20
So my program asks for a destination, either York or Alnwick and a number of changes, maximum time, and so on but I can't figure out how to make it work with the chosen destination, current code to follow:
import java.io.FileReader;
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) throws Exception {
// these will never change (be re-assigned)
final Scanner console = new Scanner(System.in);
final Scanner INPUT = new Scanner(new FileReader("C:\\Users\\Luke\\workspace\\Coursework\\input.txt"));
System.out.print("-- MENU -- \n");
System.out.print("1: Blahblahblah \n");
System.out.print("2: Blahblahblah \n");
System.out.print("Q: Blahblahblah \n");
System.out.print("Pick an option: ");
int option = console.nextInt();
switch(option) {
case 1 :
while(INPUT.hasNextLine()) {
System.out.println(INPUT.nextLine());
}
break;
case 2 :
System.out.print("Specify desired location: ");
String destination = console.next();
System.out.print("Specify Max Time (HH:MM): ");
String choice = console.next();
// save the index of the colon
int colon = choice.indexOf(':');
// strip the hours preceding the colon then convert to int
int givenHours = Integer.parseInt(choice.substring(0, colon));
// strip the mins following the colon then convert to int
int givenMins = Integer.parseInt(choice.substring(colon + 1, choice.length()));
// calculate the time's total mins
int maxMins = (givenHours * 60) + givenMins;
System.out.print("Specify maximum changes: ");
int maxChange = console.nextInt();
// gui spacing
System.out.println();
int mins = INPUT.nextInt();
int change = INPUT.nextInt();
if ((mins > maxMins) || (change > maxChange)) {
System.out.format("Time: %02d:%02d, Changes: %d = Unsuitable \n", (mins / 60), (mins % 60), change);
}
else {
System.out.format("Time: %02d:%02d, Changes: %d = Suitable \n", (mins / 60), (mins % 60), change);
}
//Do stuff
break;
case 3 :
default :
//Default case, reprint menu?
}
}
}
Have edited it to reduce the size of the question for StackOverflow but if more code is needed please let me know - any further help would be greatly appreciated!
You should really learn how the Scanner works:
int Scanner.nextInt() Returns the next int value that occurred in the next line.
String Scanner.next() Returns the next piece of String separated by the default delimiter which is space " ". (You could use a different Delimiter with Scanner.useDelimiter(String)). In default case this returns the next single Word.
String Scanner.nextLine() Returns the next full line separated with the "\n" Character.
So if you want to get a destination that has two words for Example "New York" and you fetch it with Scanner.next() like you do. Then you take the time the same way. You will get destination="New" and choice = "York" which is not parsable for : and will crash.
The other problem you have is that a Scanner works from start to end. So if you choose option 1 and print all the output from your input file you will reach the end and hasNextLine() == false. Means you cannot get any INPUT.nextInt() after that point. But you try when chosing option 2 after that.
Your prorgamm should start by reading in your input file into a data structure that stores all the informations for you. And get them from there in further process.
What is crashing in your code for now is that you start reading your text file with INPUT.nextInt() but the first line of your text file is York which has no Int value in it. You could repair that by adding:
[...]
System.out.println();
INPUT.nextLine(); // skips the first line which is York
int mins = INPUT.nextInt();
int change = INPUT.nextInt();
[...]