I am trying to split data by lines, using the method split. This is the code i am trying to use but i can't figure out what to use for the parameters of .split(). This is how the data will be in the txt.
19
23
58
49
Scanner sc = new Scanner(new File("random.txt"));
string line = sc.nextLine();
String[] numbers = line.split(" ");
int nums = new int[numbers.length];
for(int i=0;i<numbers.length;i++)
nums[i] = Integer.parseInt(numbers[i]);
The end goal is so that the data can be put into an array, not to just print it.
You dont need to use split if you have only one number in each line.
just use the following
Scanner sc = new Scanner(new File("C:/projects/random.txt"));
while( sc.hasNext()){
System.out.println(sc.nextInt());
}
Try to use it like this:
Scanner sc = new Scanner(new File("random.txt"));
int[] nums;
int i=0;
while(sc.hasNext()){
String line = sc.nextLine();
nums[i] = Integer.parseInt(line);
i++;
}
Hope this helps.
Just as simple as that, you don't need split since you're reading line by line as #Luiggi Mendoza said
Scanner sc = new Scanner(new File("C:/projects/random.txt"));
while( sc.hasNext()){
nums[i] = Integer.parseInt(numbers[i]); //They're stored in here
i++;
}
int max = i; //To keep length of numbers that have been read
for(i = 0; i < max; i++){
System.out.println(nums[i]); //We print them from the array
}
Try this
while(true){
int tmp=line.indexOf(" ");
if(tmp==-1)
break;
System.out.println(ar[i]);
ar[i++]=Integer.parseInt(line.substring(0,tmp));
line =line.substring(tmp+1);
}
Related
Please I have a proble, this is my code so far
System.out.println("Please give alue for the table");
int value = scanner.nextInt();
String[] StringArray = new String[value];
for (int i=0; i<value; i++)
{
System.out.println("Please insert string for the position:"+(i+1));
StringArray[i] = scanner.nextLine();
}
}
And my output is that
Please give alue for the table
3
Please insert string for the position:1
Please insert string for the position:2
Why i can't insert String to the position 1 and my program goes me in position 2 and after??
Please I need help, I can't unsterstand.
Thanks for your time.
Because reading an int does not consume the entire buffer, which still has an \n left. As per the documentation, nextLine reads until \n, so the first time you'll just get an empty string.
You can easily solve this by adding scanner.nextLine() right after the nextInt():
System.out.println("Please give alue for the table");
int value = scanner.nextInt();
scanner.nextLine(); // get rid of everything else left in the buffer
String[] StringArray = new String[value];
for (int i=0; i<value; i++)
{
System.out.println("Please insert string for the position:"+(i+1));
StringArray[i] = scanner.nextLine();
}
you can use BufferedReader and InputStreamReader :)
System.out.println("Please give alue for the table");
BufferedReader scanner=new BufferedReader(new InputStreamReader(System.in));
int value = Integer.parseInt(scanner.readLine());
String[] StringArray = new String[value];
for (int i=0; i<value; i++)
{
System.out.println("Please insert string for the position:"+(i+1));
StringArray[i] = scanner.readLine();
}
Hi I am trying to read an input.txt file by using a scanner, but I keep getting the input mismatch exception and I am unsure why. The file that I am reading in is formatted like this: first is a single number to identify array size. The next line is a list of integers delimited by commas. This is what I have but it fails on the first integer being read in:
File inputFile = new File("input.txt");
Scanner scan = new Scanner(inputFile);
int arraySize = scan.nextInt();
scan.nextLine();
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = scan.nextInt();
}
I also think I will probably need something in there to catch the commas after each int. Maybe scan.next(",")? but it is failing before the first comma.
Thanks in advance!
EDIT: input file for example:
5
-1, -2, -3 , -4, -5
File inputFile = new File("C:\\file.txt");
Scanner scan = new Scanner(inputFile);
String size = scan.nextLine(); // read size
String aux = scan.nextLine();
aux = aux.replaceAll("\\s",""); // remove whitespaces for better Integer.parseInt(String)
String[] parts = aux.split(",");
System.out.println("size "+size);
for (int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
scan.close();
Then you can convert the strings to integers.
You need to specify the delimiter that you read the string. It defaults to consume only whitespace, not commas.
public static void main (String[] args)
{
int size = 5;
Scanner sc = new Scanner("-1, -2, -3, -4, -5");
sc.useDelimiter("\\s*,\\s*"); // commas surrounded by whitespace
for (int i = 0; i < size; i++) {
System.out.println(sc.nextInt());
}
}
Example
Your problem is that calling scanner.nextInt() delimits the elements with a space. There are two things you can do to fix this: you can either set the delimiter to be ", " (scanner.useDelimiter(", ");) or see Oscar M's answer.
Example:
Scanner sc = new Scanner("-1, -2, -3, -4");
sc.useDelimiter(", ");
System.out.println(sc.nextInt());
System.out.println(sc.nextInt());
Output:
-1
-2
When I am trying to write the following code, the computer takes several inputs. But what I want is it should take only one line as an input and save all the integers in that line in an array. Can you help me with this please?
import java.util.*;
class InputInteger{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int[] array=new int[20];
int i=0;
while(input.hasNext()){
array[i]=input.nextInt();
i++;
}
input.close();
}
}
But what I want is it should take only one line as an input and save all the integers in that line in an array.
First, I urge you not to close() a Scanner that you have created around System.in. That's a global, and close()ing can cause you all kinds of issues later (because you can't reopen it). As for reading a single line of input and splitting int values into an array, you could do use Scanner.nextLine() and something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
if (input.hasNextLine()) {
String line = input.nextLine();
String[] arr = line.split("\\s+");
int[] vals = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
vals[i] = Integer.parseInt(arr[i]);
}
System.out.println(Arrays.toString(vals));
}
}
Edit Based on your comment,
String line = "1 31 41 51";
String[] arr = line.split("\\s+");
int[] vals = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
vals[i] = Integer.parseInt(arr[i]);
}
System.out.println(Arrays.toString(vals));
Output is
[1, 31, 41, 51]
If you need to handle errors, I suggest you use a List like
List<Integer> al = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
try {
al.add(Integer.parseInt(arr[i]));
} catch (NumberFormatException nfe) {
}
}
// You could now print the List
System.out.println(al);
// And if you must have an `int[]` copy it like.
int[] vals = new int[al.size()];
for (int i = 0; i < al.size(); i++) {
vals[i] = al.get(i);
}
System.out.println(Arrays.toString(vals));
You can capture the input as String and use for loop to process it:
Scanner input=new Scanner(System.in);
int[] array=new int[20];
String numbers = input.nextLine();
for(int i = 0 ; i<numbers.length() ; i++){
array[i]=Character.getNumericValue(numbers.charAt(i));
}
But in this case, the number of digits must be not exceed your array size, which is 20. Or else it will throw ArrayIndexOutOfBound Exception. You may want to do Exception handling on this.
Or to avoid that, you can declare your array with size equal to length of the input:
int[] array=new int[numbers.length()];
See the demo here
Scanner input = new Scanner(System.in);
ArrayList<Integer> nums = new ArrayList<Integer>();
boolean repeat = true;
while (repeat) {
System.out
.print("Enter a bunch of integers seperated by spaces, or 'q' to quit: ");
String line = input.nextLine();
if (line.equals("q"))
repeat = false;
else {
String[] numbers = line.split("\\s+");
for (String num : numbers) {
if (!nums.contains(num))
nums.add(Integer.parseInt(num));
}
}
}
for (Integer i : nums) {
System.out.println(i);
}
input.close();
I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
Try this
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
if (in.hasNextInt())
System.out.println(in.nextInt());
else
in.next();
}
}
By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.
If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this
Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.
String input = scanner.nextLine(); // get the entire line after the prompt
String[] numbers = input.split(" "); // split by spaces
Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()
Scanner has a method called hasNext():
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
System.out.println(scanner.nextInt());
}
If you know how much integers you will get, then you can use nextInt() method
For example
Scanner sc = new Scanner(System.in);
int[] integers = new int[3];
for(int i = 0; i < 3; i++)
{
integers[i] = sc.nextInt();
}
Java 8
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int arr[] = Arrays.stream(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.
import java.util.Scanner; // imports class so we can use Scanner object
public class Test
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter numbers: ");
// This inputs the numbers and stores as one whole string value
// (e.g. if user entered 1 2 3, input = "1 2 3").
String input = keyboard.nextLine();
// This splits up the string every at every space and stores these
// values in an array called numbersStr. (e.g. if the input variable is
// "1 2 3", numbersStr would be {"1", "2", "3"} )
String[] numbersStr = input.split(" ");
// This makes an int[] array the same length as our string array
// called numbers. This is how we will store each number as an integer
// instead of a string when we have the values.
int[] numbers = new int[ numbersStr.length ];
// Starts a for loop which iterates through the whole array of the
// numbers as strings.
for ( int i = 0; i < numbersStr.length; i++ )
{
// Turns every value in the numbersStr array into an integer
// and puts it into the numbers array.
numbers[i] = Integer.parseInt( numbersStr[i] );
// OPTIONAL: Prints out each value in the numbers array.
System.out.print( numbers[i] + ", " );
}
System.out.println();
}
}
There is more than one way to do that but simple one is using String.split(" ")
this is a method of String class that separate words by a spacial character(s) like " " (space)
All we need to do is save this word in an Array of Strings.
Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :
for (int i = 0; i < stringsArray.length; i++) {
int x = Integer.parseInt(stringsArray[i]);
// Do what you want to do with these int value here
}
Best way is converting the whole stringArray to an intArray :
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
now do any proses you want like print or sum or... on intArray
The whole code will be like this :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");
int[] intArray = new int[stringsArray.length];
for (int i = 0; i < stringsArray.length; i++) {
intArray[i] = Integer.parseInt(stringsArray[i]);
}
}
}
This works fine ....
int a = nextInt();
int b = nextInt();
int c = nextInt();
Or you can read them in a loop
Using this on many coding sites:
CASE 1: WHEN NUMBER OF INTEGERS IN EACH LINE IS GIVEN
Suppose you are given 3 test cases with each line of 4 integer inputs separated by spaces 1 2 3 4, 5 6 7 8 , 1 1 2 2
int t=3,i;
int a[]=new int[4];
Scanner scanner = new Scanner(System.in);
while(t>0)
{
for(i=0; i<4; i++){
a[i]=scanner.nextInt();
System.out.println(a[i]);
}
//USE THIS ARRAY A[] OF 4 Separated Integers Values for solving your problem
t--;
}
CASE 2: WHEN NUMBER OF INTEGERS in each line is NOT GIVEN
Scanner scanner = new Scanner(System.in);
String lines=scanner.nextLine();
String[] strs = lines.trim().split("\\s+");
Note that you need to trim() first: trim().split("\\s+") - otherwise, e.g. splitting a b c will emit two empty strings first
int n=strs.length; //Calculating length gives number of integers
int a[]=new int[n];
for (int i=0; i<n; i++)
{
a[i] = Integer.parseInt(strs[i]); //Converting String_Integer to Integer
System.out.println(a[i]);
}
created this code specially for the Hacker earth exam
Scanner values = new Scanner(System.in); //initialize scanner
int[] arr = new int[6]; //initialize array
for (int i = 0; i < arr.length; i++) {
arr[i] = (values.hasNext() == true ? values.nextInt():null);
// it will read the next input value
}
/* user enter = 1 2 3 4 5
arr[1]= 1
arr[2]= 2
and soo on
*/
It's working with this code:
Scanner input = new Scanner(System.in);
System.out.println("Enter Name : ");
String name = input.next().toString();
System.out.println("Enter Phone # : ");
String phone = input.next().toString();
A simple solution can be to consider the input as an array.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //declare number of integers you will take as input
int[] arr = new int[n]; //declare array
for(int i=0; i<arr.length; i++){
arr[i] = sc.nextInt(); //take values
}
You're probably looking for String.split(String regex). Use " " for your regex. This will give you an array of strings that you can parse individually into ints.
Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .
Scanner sc = new Scanner(System.in);
List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
while(st.hasMoreTokens()) // iterate until no more tokens
{
l.add(Integer.parseInt(st.nextToken())); // parse each token to integer and add to linkedlist
}
Using BufferedReader -
StringTokenizer st = new StringTokenizer(buf.readLine());
while(st.hasMoreTokens())
{
arr[i++] = Integer.parseInt(st.nextToken());
}
When we want to take Integer as inputs
For just 3 inputs as in your case:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a,b,c;
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
For more number of inputs we can use a loop:
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
int a[] = new int[n]; //where n is the number of inputs
for(int i=0;i<n;i++){
a[i] = scan.nextInt();
}
This method only requires users to enter the "return" key once after they have finished entering numbers:
It also skips special characters so that the final array will only contains integers
ArrayList<Integer> nums = new ArrayList<>();
// User input
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
if (!n.isEmpty()) {
String[] str = n.split(" ");
for (String s : str) {
try {
nums.add(Integer.valueOf(s));
} catch (NumberFormatException e) {
System.out.println(s + " cannot be converted to Integer, skipping...");
}
}
}
//Get user input as a 1 2 3 4 5 6 .... and then some of the even or odd number like as 2+4 = 6 for even number
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int evenSum = 0;
int oddSum = 0;
while (n > 0) {
int last = n % 10;
if (last % 2 == 0) {
evenSum += last;
} else {
oddSum += last;
}
n = n / 10;
}
System.out.println(evenSum + " " + oddSum);
}
}
if ur getting nzec error, try this:
try{
//your code
}
catch(Exception e){
return;
}
i know it's old discuss :) i tested below code it's worked
`String day = "";
day = sc.next();
days[i] = Integer.parseInt(day);`
I'm doing an school exercise and I can't figure how to do one thing.
For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
This is the problem.
The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
I've done this:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
But this is not working properly and I can't figure it out.
Ideally, if the user enters:
This is line one
This is line two
and now press enter, wen printing the array it should give:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String in both cases:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
Here's the typical readline idiom, applied to your code:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}
The code below will automatically stop when you try to input more than 10 strings without prompt an OutBoundException.
String[] text = new String[10]
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++){ //continous until 10 strings have been input.
System.out.println("Please insert text:");
string s = sc.nextLine();
if (s.equals("")) break; //if input is a empty line, stop it
text[i] = s;
}