How to read values till user presses enter in JAVA? - java

I need to take input in the form of-
Given 'n' number of boxes and each of these boxes may contain any number of distinct integers,
So first user enters n,then for each value of i from 1 to n,I need to enter values till enter is pressed.
I don't know how to do this,
Eg-
5
1 2 3 4 5 6 7 8 9
1 2
1
4 5 6
3 4 5 6 7
I have tried this-
String str;
for(int i=0;i<n;i++)
{
while(true)
{
str=scanner.next();
if(str.isEmpty())
break;
int val=Integer.parseInt(str);
}
}
Also tried str.equals("\n") and str.equals(""),
But nothing is working.
Somebody please help me out.Thanks.

Try something like this:
int n = scanner.nextInt();
for(int i=0;i<n;i++)
{
String str = scanner.nextLine();
String[] array = str.split(" ");
}
You take a String from user (a single line of numbers) and you split it by space, so you have all the numbers as String in the array. Then you have to parse them to int or do whatever you want with them.

try this
String str;
for(int i=0;i<n;i++)
{
while(true)
{
str=scanner.next();
if(!str.equalsIgnoreCase(""))
break;
int val=Integer.parseInt(str);
}
}

In Scanner class has
next(){only take input upto any white space character occur}
nextLine(){ takes input upto new line character }
Try with nextLine() method and then try to store in any array
Using n value.Then you can use split or string tokenzer function and then we extract integer from in it

This worked for me
while (true) {
String str = sc.nextLine();
if (str.equalsIgnoreCase("")) break;
}

Related

How can user inputs be typed in so that I can separate each value by a comma instead of pressing Enter after each value?

Instead of having to press Enter after each value input with Scanner, is there a way to type all values at once, and then press enter and be done?
import java.util.Arrays;
import java.util.Scanner;
class Arrayex {
public static void main(String[] args)
{
int [] numbers = new int[5];
Scanner s=new Scanner(System.in);
System.out.println("Current array: " + Arrays.toString(numbers));
System.out.println("Type in the numbers: ");
for(int i=0; i< numbers.length; i++)
{
numbers[i] = s.nextInt();
}
System.out.println("Array elements are: " + Arrays.toString(numbers));
}
}
Current array input by pressing Enter after every number
How I want to type in the numbers into the array
My friend told me I can use a String array and convert it to int array and type the string as "1,2,3,4,5".
Wouldn't this only use up the location at numbers[0] instead of numbers[0] to numbers[5]?
Enter all int elements in one line using space, it will use as separate int values.
it will look like this.
No need to take input as String and parse it to an integer.
(White)space as delimiter
As others have noted, if you just use space as separator, then you could leverage the Scanner to convert the input to ints. The input 2 3 5 7 11 will yield an int[] with the given integers als elements.
Comma as delimiter
If you want to use comma as delimiter instead, the current code won't work. The input 2,3,5,7,11 will indeed try to shove 2,3,5,7,11 into numbers[0], which obviously will fail, and an InputMismatchException will be thrown at you.
Instead, you could set the delimiter:
Scanner s = new Scanner(System.in);
s.useDelimiter("[,\n]")
This will cause the Scanner to process the tokens between each comma or newline as separate elements.
Note that we couldn't just use , alone, because then the Scanner keeps reading from System.in indefinitely.

Getting multiple inputs from user with char and integers Java

I'm trying to allow the user to put in multiple inputs from the user that contain a char and integers.
Something like this as input: A 26 16 34 9
and output each int added to an array.
I was thinking I could have the first input as a character and then read the rest as a string which then I separate and put into an array.
I'm not new to coding but new to java. I've been doing c++ so the syntax is a bit different.
This is what I have so far, I haven't set up my array yet for the integers.
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
int firstNumber;
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
int n = reader.nextInt();
if (n=='A') {
//if array is full System.out.println("The list is full!");
//else
System.out.println("Integer " + " " + "has been added to the list");
}
else if (n=='Q') {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Could you specify better how should your input be given? From your question, if I understand well, the user simply type "A" followed by a list of numbers separated by a space. So I would simply read the next line, split it in words (separated by a space) and check if the first word is the letter "A". Here it goes:
import java.util.Scanner;
public class Program0 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("'A' to enter a number. 'Q' to quit");
String line = reader.nextLine();
String[] words = line.split(" ");
if (words.length > 0 && words[0].equals("A")) {
//if array is full System.out.println("The list is full!");
// => I don't understand this part
//else
for(int i = 1; i<words.length; i++){
int integer = Integer.parseInt(words[i]);
System.out.println("Integer " + integer + " has been added to the list");
//do your stuff here
}
}
else if (words.length > 0 && words[0].equals("Q")) {
System.out.println("List of integers: ");
System.out.println("Average of all integers in the list: ");
}
else{
System.out.println("Invalid Action");
}
reader.close();
}
}
Note that in your solution, you read the next int from your scanner and then try to compare it with the character 'A'. This will not work because A is not an int. If you really want to get the first character from your scanner, you could do:
String line = reader.nextLine();
if(line.length() > 0){
char firstChar = line.charAt(0);
//do your stuff here
}
A character is not an int. You cannot read an int to expect something like 'A'. You can read a String and take its first character though. Scanner doesn't offer a convenient method to read the next String and expect it to be only one-character long. You'd need to handle that yourself.
But considering you don't know in advance how many numbers there will be to read, your solution to read the entire line and interpret it entirely, is the better one. That means you can't use nextInt() nor nextDouble() nor next() nor nextWhateverElse().
You need nextLine(), and it will give you the entire line as a String.
Then you can split() the result, and check if the first is one-char-long. Then you can parse all the others as int.
I don't immediately recall how to write this in Java – it's been a bit of a while – but what I'd do is to first separate the string by spaces, then attempt to do ParseInt on each piece.
If the string isn't a valid integer, this method will throw an exception, which you can catch. So:
If you make it to the next statement, an exception didn't happen, so the value is an integer.
If, instead, you find yourself in the exception-handler (having caught [only ...] the expected kind of exception, the value is a string.
Of course, don't "catch" any exception-type other than the NumberFormatException that you're expecting.
By the way, it is perfectly routine to use exceptions in this way. Let Java's runtime engine be the authority as to whether it's an integer or not.

How to read integers between white spaces?

I'm trying to write a Hangman game project in which the user can have 15 guesses and 4 spaces to check. The numbers (of spaces) are separated by spaces. Here is my code, but it doesn't work for some reasons. Any help is appreciated !
System.out.println("\nPlease enter the letter you want to guess: ");
char guessLetter = input.next().charAt(0);
if (Character.isLetter(guessLetter)){
System.out.println("Please enter the spaces you want to check (separated by spaces): ");
String guessSpaces = input.next();
for (int index = 0; guessSpaces.charAt(index) == ' ';index++){
if(guessSpaces.charAt(index)== secretWord.indexOf(guessLetter)){
System.out.println("You guess is in the word");
I don't really understand your code, but if you want to read some integers, this is how to do it:
String[] strings = input.nextLine().split(" ");
ArrayList<Integer> integers = new ArrayList<>();
for (String s : strings) {
if (s.trim().equals("")) {
continue;
}
integers.add(Integer.parseInt(s));
}
Now you have a list of integers stored in integers. For example, if I enter
90 68 6 786
The array list will contain exactly that. However, if you enter some invalid values in there, an exception will be thrown.
Also, it seems like that your for loop is checking whether the letter that the user entered is in the secret word. No need to use a for loop for this! Just do this:
if (secretWord.contains(Character.toString(guessLetter))) {
System.out.println("Your guess is in the word!");
}

Using variables with parseInt in Java

So i'm supposed to collect data from user inputs for a game
int[] player1 = new int[4];
try {
player1[4] = Integer.parseInt(keyin.nextLine());
}
catch(NumberFormatException e) {
System.out.println("Player 2 : "); }
The try-catch is to skip to the next player when player1 presses Enter, but the problem I'm getting is I can't seem to find a way to use the variables the player1 has inputted. I need those values to compare with another, but using int player1[0] does not work.
Where can I find the values the person has entered?
An example of the program running:
Player 1: 12 1 5 // these numbers are user inputted
Player 2: 12 4 3
[...]
You need to setup a loop to both read in the inputs, as well as to display those inputs.
Your code below does not work; you are trying to access data that is beyond the bounds of your array.
player1[4] = Integer.parseInt(keyin.nextLine());
If you declare you array like this: int[] player1 = new int[4];
Then you have the following indexes to use:
| 0 | 1 | 2 | 3 |` //This gives you 4 indexes! But player1[3] is the last usable index
Remember that when you are trying to access elements of arrays or any element in programming, computers begin numbering at zero! Any attempt to access data beyond this can result in undesired behavior, casuing the program to terminate abruptly.
I encourage you to examine the following resources:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
http://www.tutorialspoint.com/java/java_loop_control.htm
http://www.programmingsimplified.com/java/tutorial/java-while-loop
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
while ((n = input.nextInt()) != 0) {
System.out.println("You entered " + n);
System.out.println("Input an integer");
}
System.out.println("Out of loop");
}
String string = keyin.nextLine();
String[] parts = string.split("[ ]+");
Then check the size of parts and loop through that.

JAVA My two-dimensional array scanned from a text file prints without the first column

I am working on a lab for school so any help would be appreciated, but I do not want this solved for me. I am working in NetBeans and my main goal is to create a "two-dimensional" array by scanning in integers from a text file. So far, my program runs with no errors, but I am missing the first column of my array. My input looks like:
6
3
0 0 45
1 1 9
2 2 569
3 2 17
2 3 -17
5 3 9999
-1
where 6 is the number of rows, 3 is the number of columns, and -1 is the sentinel. My output looks like:
0 45
1 9
2 569
2 17
3 -17
3 9999
End of file detected.
BUILD SUCCESSFUL (total time: 0 seconds)
As you can see, everything prints correctly except for the missing first column.
Here is my program:
import java.io.*;
import java.util.Scanner;
public class Lab3
{
public static void main(String[] arg) throws IOException
{
File inputFile = new File("C:\\Users\\weebaby\\Documents\\NetBeansProjects\\Lab3\\src\\input.txt");
Scanner scan = new Scanner (inputFile);
final int SENT = -1;
int R=0, C=0;
int [][] rcArray;
//Reads in two values R and C, providing dimensions for the rows and columns.
R = scan.nextInt();
C = scan.nextInt();
//Creates two-dimensional array of size R and C.
rcArray = new int [R][C];
while (scan.nextInt() != SENT)
{
String line = scan.nextLine();
String[] numbers = line.split(" ");
int newArray[] = new int[numbers.length];
for (int i = 1; i < numbers.length; i++)
{
newArray[i] = Integer.parseInt(numbers[i]);
System.out.print(newArray[i]+" ");
}
System.out.println();
}
System.out.println("End of file detected.");
}
}
Clearly, there is a logical error here. Could someone please explain why the first column is invisible? Is there a way I can only use my rcArray or do I have to keep both my rcArray and newArray? Also, how I can get my file path to just read "input.txt" so that my file path isn't so long? The file "input.txt" is located in my Lab3 src folder (same folder as my program), so I thought I could just use File inputFile = new File("input.txt"); to locate the file, but I can't.
//Edit
Okay I have changed this part of my code:
for (int i = 0; i < numbers[0].length(); i++)
{
newArray[i] = Integer.parseInt(numbers[i]);
if (newArray[i]==SENT)
break;
System.out.print(newArray[i]+" ");
}
System.out.println();
Running the program (starting at 0 instead of 1) now gives the output:
0
1
2
3
2
5
which happens to be the first column. :) I'm getting somewhere!
//Edit 2
In case anyone cares, I figured everything out. :) Thanks for all of your help and feedback.
Since you do not want this solved for you, I will leave you with a hint:
Arrays in Java are 0 based, not 1 based.
As well as Jeffrey's point around the 0-based nature of arrays, look at this:
while (scan.nextInt() != SENT)
{
String line = scan.nextLine();
...
You're consuming an integer (using nextInt()) but all you're doing with that value is checking that it's not SENT. You probably want something like:
int firstNumber;
while ((firstNumber = scan.nextInt()) != SENT)
{
String line = scan.nextLine();
...
// Use line *and* firstNumber here
Or alternatively (and more cleanly IMO):
while (scan.hasNextLine())
{
String line = scan.nextLine();
// Now split the line... and use a break statement if the parsed first
// value is SENT.

Categories