I am trying to get a while loop to break by pressing the Enter key on a keyboard. My code is:
package javaapplication4;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList( );
while (true) {
System.out.println("Please enter the numbers seperated by a space: ");
numbers.add(keyboard.nextDouble());
//want the while loop to break here by pressing "enter" after entering array values
}
System.out.println(numbers);
}
Don't use a loop for getting the input, or nextDouble. What you really want is one line of input, which you then split into a list of doubles. So use nextLine, split it, and parse each item. Something like this:
Scanner keyboard = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList( );
String input = keyboard.nextLine();
for(String item : input.split(" ")){
numbers.add(Double.parseDouble(item));
}
This ignores any sort of input validation, but it shows a general approach.
This will work because once you hit "enter", it ends the first line, meaning the scanner can move past the nextLine into the bulk of your code. Since you never try to read anything more, it doesn't block waiting for any more input, and can successfully exit once done.
I myself like to use try { ... } catch (NumberFormatException) so when you get a blank line (ie enter) your catch block is activated and you've escaped the loop
try {
while (true) {
System.out.println("Please enter the numbers seperated by a space: ");
numbers.add(keyboard.nextDouble());
//want the while loop to break here by pressing "enter" after entering array values
}
} catch (NumberFormatException ex) {}
System.out.println(numbers);
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList();
System.out.println("Please enter the numbers seperated by a space: ");
String line = keyboard.nextLine();
StringTokenizer token = new StringTokenizer(line, " ");
while(token.hasMoreTokens()) {
numbers.add(Double.parseDouble(token.nextToken()));
}
System.out.println("Numbers: " + numbers);
}
}
Related
I have tried changing int to String and char but neither seemed to work. Any help is greatly appreciated
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your phrase: ");
int phrase = input.nextInt();
System.out.println("You entered " + phrase);
// closing the scanner object
input.close();
}
}
Calling the nextInt() method attempts to get the next token as an int. If it is not an int, an InputMismatchException is thrown. If you enter input that can be represented as an int, then you will see your phrase printed.
Try this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your phrase: ");
String phrase = input.next();
System.out.println("You entered " + phrase);
// closing the scanner object
input.close();
}
}
next() returns the next complete token as a String.
java.util.Scanner documentation
As Lino has pointed out, if you intend on capturing multiple, seperated words, you can instead use nextLine() instead of next().
I have 3 files. Two are preset and aren't allowed to be changed:-
userInputTest (containing "main" method)
import java.util.Arrays;
public class UserInputTest {
public static void main(String[] args) {
UserInput userInput = new UserInput();
//Task 1
System.out.println(userInput.sayHello());
//Task 2
System.out.println(Arrays.toString(userInput.readTenNumbers()));
//Task 3
System.out.println(Arrays.toString(userInput.readTenNames()));
}
}
and 2) userInputTestsAll
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class UserInputUnitTestsAll {
UserInput userInput;
#BeforeEach
void createObject() {
userInput = new UserInput();
}
#Test
//Task 1
void testSayHello() {
assertEquals("Hello Suzy".toLowerCase(), userInput.sayHello().toLowerCase());
assertEquals("Hello Bob".toLowerCase(), userInput.sayHello().toLowerCase());
}
#Test
//Task 2
void testReadTenNumbers() {
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
assertArrayEquals(numbers, userInput.readTenNumbers());
int[] numbers1 = {10,20,30,40,50,60,70,80,90,100};
assertArrayEquals(numbers1, userInput.readTenNumbers());
}
#Test
//Task 3
void testReadTenNames() {
String[] names = {"Michael","Saru","Christopher","Sylvia","Paul","Harry","Phillipa","Gabriel","Jett","Ash"};
assertArrayEquals(names, userInput.readTenNames());
}
}
I need to write the 3rd file - called userInput (below), so that when userInputTestsAll is run, my file passes all the test. I have written the following (see code below) but, am getting errors because of the Scanner.close() method. It is for uni work and they insist that we close all Scanner objects after use. I know that closing the Scanner object closes System.in and it can't be reopened. Any suggestions please? When run in Eclipse IDE, the JUnit Failure trace has to come back green.
My code (which can be changed as required):
import java.util.Scanner;
public class UserInput {
// Task 1 - takes user keyboard input. Returns 'Hello' + user input
public String sayHello() {
Scanner keyboard = new Scanner(System.in); // create scanner object to read user inputs
String name = "Something went wrong";
System.out.println("Enter name: ");
name = keyboard.nextLine(); // read user input
keyboard.close(); // close scanner object
return "Hello " + name;
} // End of Task 1
// Task 2 - Reads ten consecutive user integer inputs from keyboard and stores them in an int array. Returns int array
public int[] readTenNumbers() {
Scanner keyboard = new Scanner(System.in); // create scanner object to read user inputs
int [] numbers = new int[10]; // declare array to hold ten integers
for (int i = 0; i < numbers.length; i++) { // loop to read user input each time and assign to numbers array
System.out.println("Enter integer #" + (i+1) + ": ");
numbers[i] = keyboard.nextInt(); // read user input and assign to array
keyboard.nextLine(); // removes 'stray data' (including carriage return, etc)
}
keyboard.close(); // close scanner object
return numbers;
} // End of Task 2
// Task 3 - Reads ten names from user input and stores in a String array. Returns the String array.
public String[] readTenNames() {
Scanner keyboard = new Scanner(System.in); // create scanner object to read user inputs
String[] names = new String[10]; // declare array to hold names
for (int i = 0; i < names.length; i++) { // loop to read user input each time and assign to names array
System.out.println("Enter name #" + (i+1) + ": ");
names[i] = keyboard.nextLine(); // read user input and assign to array
}
keyboard.close(); // close scanner object
return names;
}// End of Task 3
} // End of public class UserInput
I've tried everything I can think of, including putting the scanner object and close method in a seperate method/putting the Scanner.close method just in the last method/etc. T
his is 1st year, 1st semester uni work and the first coding we have had to do on reading user input, so I can't see it needing to be so longwinded/difficult.
import java.util.ArrayList;
import java.util.*;
public class Solution {
public static void main (String args []){
ArrayList<String> cars=new ArrayList<String>();
Scanner sc =new Scanner (System.in);
System.out.println(" enter the size of the list ");
int size=sc.nextInt();
for( int i =0;i<size;i++){
cars.add(i,sc.nextLine());
}
System.out.println(cars);
sc.close();
}
}
This program should output
1,2,3,4
But if I enter the size as 4 and I enter these values only but instead, if I write the size as 4 ... it doesn't take 4 arguments from me instead it will take three and print(' ',1,2,3)
please help
The nextLine() traverse the pointer to the next line. So using next solves the problem
import java.util.ArrayList;
import java.util.*;
public class Solution {
public static void main (String args []){
ArrayList<String> cars=new ArrayList<String>();
Scanner sc =new Scanner (System.in);
System.out.println(" enter the size of the list ");
int size=sc.nextInt();
for( int i =0;i<size;i++){
System.out.println(" enter the " + i + " number : ");
cars.add(i, sc.next());
}
System.out.println(cars);
sc.close();
}
}
You need to add sc.nextLine() just before the for loop.
When you enter a number then press Enter, input.nextInt() takes only the number, not the end of the line. However, when you execute input.nextLine(), it takes the end of the line which is already in the buffer from the first input. Always use input.nextLine() immediately after input.nextInt()
You were trying to accept a number but you have declared the ArrayList type as String. Your code will look like this
import java.util.ArrayList;
import java.util.*;
public class Main
{
public static void main(String[] args) {
ArrayList<String> cars=new ArrayList<String>();
Scanner sc =new Scanner (System.in);
System.out.println(" enter the size of the list ");
int size=sc.nextInt();
sc.nextLine();
for( int i =0;i<size;i++){
cars.add(i,sc.nextLine());
}
System.out.println(cars);
sc.close();
}
}
when you do list.add(i, value) what it does is keeps the value in the i index of the of List.
What .nextLine does it read the next line which which is blank, which resulting in *space* in the first position of the list.
so when you are doing cars.add(i,sc.nextLine()) this is adding space in the first index ie 0.
What u can do is.
for( int i =0;i<size;i++){
cars.add(i,sc.next());
}
When you do sc.next() it check for the next character rather then Traversing to the nextLine.
There are a couple of ways to deal with this problem e.g.
Input the size using Integer.parseInt(sc.nextLine())
Put a sc.nextLine(); after int size=sc.nextInt();
The reason for this is that Scanner#nextInt does not consume the line-break which was entered by pressing Enter. The sc.nextLine() consumes this line-break.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Declare the list
List<String> cars = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the list: ");
int size = Integer.parseInt(sc.nextLine());
for (int i = 0; i < size; i++) {
cars.add(i, sc.nextLine());
}
System.out.println(cars);
}
}
A sample run:
Enter the size of the list: 4
1
2
3
4
[1, 2, 3, 4]
A couple of more suggestions (as you can see in the code above):
Use the Generic type i.e. List instead of ArrayList for the type of the variable e.g. List<String> cars=new ArrayList<>();. Also, note that you do not need to put <String> again on the right side; the compiler can infer it from simply <>.
Do not close a Scanner for System.in as it also closes System.in and you will not be able to open it again unless you restart the application. There may be cases that your application has many classes and some other class in the application requires taking some input from the keyboard (System.in).
I get an extra comma on the end of my string after the user inputs their text. How do I get rid of the last comma? The good old fence post problem, but I'm stuck on the fence.
import java.util.Scanner;
public class fencepost {
public static void main(String[] args) {
System.out.print("Enter a line of text: ");
Scanner console = new Scanner(System.in);
String input = console.nextLine();
System.out.print("You entered the words: ");
Scanner linescanner = new Scanner(input);
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
System.out.print(", ");
}
}
}
I get as output "hello, there," with an extra comma after there.
Add an if statement inside your loop to determine if there's still a next line, if so, then add a comma, otherwise, don't add one:
while (linescanner.hasNext()) {
System.out.print(linescanner.next());
if (linescanner.hasNext()) {
System.out.print(", ");
}
}
I am working on a small program. I need to get a number of integers from the user and print them out. I also need to identify whether the input is valid or not. Here is my code:
List<Integer> tokens = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt()) {
tokens.add(sc.nextInt());
System.out.println(sc.nextInt());
}
My first question is how to identify the type of the input and store this information in a variable.
My second question is I enter an infinite loop when I run the code. After I enter the input, the program prints all of them and then waits for input again. How do I solve this problem?
I really appreciate your help.
This might help you:
Why are You calling sc.nextInt() 2 times in the loop without checking for next value?
Use an invalid number such as -1 to break the loop.
Don't forget to close the stream.
sample code:
List<Integer> tokens = new ArrayList<Integer>();
try (Scanner sc = new Scanner(System.in)) {
while (sc.hasNextInt()) {
int i = sc.nextInt();
if (i == -1) {
break;
}
tokens.add(i);
System.out.println(i);
}
}
System.out.println(tokens);
Read Java7- The try-with-resources Statement
Try this code -
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Stax {
public static void main(String[] args) {
List<Integer> tokens = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
String data = "";
System.out.println("Enter some numbers...");
while (sc.hasNext()) {
data = sc.next();
if (data.equalsIgnoreCase("EXIT")) {
System.out.println();
break;
}
try {
tokens.add(Integer.parseInt(data));
System.out.println(sc.next());
} catch (NumberFormatException e) {
System.out
.println("Error: Your input string cannot be converted to a number.");
e.printStackTrace();
}
}
}
}