JAVA: Signal start of new input with space instead of enter - java

I have an assignment to create a program that will take input and print it to the console. Pretty simple. There is one issue though. I have to store the information in separate variables but the input looks like this.
Input:
Blah 123 Green
I'm aware that I can create a single scanner input tied to a single variable that will store all of that as one String but for the assignment Blah, 123, and Green would all have to be stored in different variables. Normally what I would do if I could use the enter key to signal new input would be
Scanner scan = new Scanner(System.in);
String first = scan.nextLine();
int second = Integer.parseInt(scan.nextLine());
String third = scan.nextLine();
but in this case, the spaces have to act as the enter key instead. how would I go about this?

You could use next() to read individual inputs:
String first = scan.next();
int second = scan.nextInt());
String third = scan.next();

Related

Java console read input line by line and store in String array

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

Java : Get only 1 line of integers from the console?

I recently picked up Java and I am having an issue with some console input.
Basically, I want to read in an array of ints from the console in a format like this :
1 2 3 4 5 6
I looked through some examples on the forums and decided to do this by using the scanner nextInt() method.
My code currently looks like this :
Scanner get = new Scanner(System.in);
List<Integer> elements = new ArrayList<>();
while (get.hasNextInt()) {
elements.add(get.nextInt());
}
The problem with this code is that the while loop doesn't stop when I hit "Enter" on the console.
Meaning that after I enter some numbers (1 3 5 7) and then hit enter, the program doesn't continue with execution, but instead waits for more integers. The only way it stops is if I enter a letter to the console.
I tried adding !get.hasNextLine() as a condition in my while loop, but this didn't help.
I would be very greatful, if anyone has an idea how can I fix this.
If you want to read only one line the simpliest answer may be the best :)
Scanner in = new Scanner(System.in);
String hString = in.nextLine();
String[] hArray = hString.split(" ");
Now, in array hArray you have all elements from input and you can call them like hArray[0]
You can read one line, and then use that to construct another Scanner. Something like,
if (get.hasNextLine()) {
String line = get.nextLine();
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextInt()) {
elements.add(lineScanner.nextInt());
}
}
The Scanner(String) constructor (per the Javadoc) constructs a new Scanner that produces values scanned from the specified string.
Scanner get = new Scanner(System.in);
String arrSt = get.next();
StringTokinizer stTokens = new StringTokinizer(arrSt," ");
int [] myArr = new Int[stTokens.countTokens()];
int i =0;
while(stTokens.hasMoreTokens()){
myArr[i++]=Integer.parseInt(stTokens.nextToken());
}
java-8
You may use the following. User just has to enter each integer without pressing enter and press enter at the end.
Scanner get = new Scanner(System.in);
List<Integer> elements = Stream.of(get.nextLine().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

Parse a string and cast certain elements to int

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.

Storing inputs? (java)

if I use a scanner to read system input, how do i store the input in one string?
So far I have something like this.
Scanner user_input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = user_input.next();
If in the terminal I type, "Bob Saget", name = "Bob". I want name = "Bob Saget"
Can anyone give me detailed instructions, if they involve eliminating white space or using tokenizers or something?
Use nextLine instead of next in order to read the entire input line into your name variable :
String name = user_input.nextLine();
Use user_input.nextLine() method , it reads till ENTER key is pressed
Use the nextLine(); method. The next(); method only reads the first token, the input until the first space (separator).
nextLine();
reads the entire line.

double print before allowed to respond

I'm still new to programming and have been trying to learn how to fix this code
im trying to input and record a username and password depending on how many users I input, but when i run it it prints out the "whats your username?" question twice before i'm allowed to give a response. I've narrowed the problem down to the user[i]=in.nextLine() part
public static void main(String[] args){
System.out.println("How many Users?");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
String[] user;
user = new String[x];
String[] pass;
pass = new String[x];
for(int i=0; i<x;i++){
System.out.println("What is your Username?");
user[i] = in.nextLine();
Add in.nextLine(); after int x = in.nextInt(); to consume and ignore the new line character left over by call to nextInt()
When you use a scanner it consume only the bytes needed for the requested token.
If the first call is to get the number of users (nextInt) it reads only the minimum number of digits composing it and leave the \n (new line character) not consuming it.
Because you are asking for the next line on the loop the first nextLine use only the \n.
So the best solution to make your code correct is to add a
in.nextLine();
before the for loop.

Categories

Resources