I am trying to scan a line of Integers from a txt file and store them within an ArrayList. My question is simple, how can I do this?
This is what I have
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i ;
File f = new File (args[0]);
Scanner input = new Scanner(f);
i = input.nextInt() ;
input.nextLine();
while(input.hasNextInt()) {
if(input.hasNextLine()) {
coinTypes.add(i);
}
if(input.hasNextLine()) {
change = input.nextInt();
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
}
}
System.out.println(coinTypes);
}
}
Why doesn't what I have work?
INPUT:
java homework5 hwk5sample1.txt
OUTPUT:
Found change
Change: 143
[1]
Txt file:
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
WANT:
Change: 143
[1, 5, 10, 25, 50, 100]
There are different problems in your code
if(input.hasNextLine()) {
coinTypes.add(i);
}
That if is not required since you are checking that in the while before
The main problem is that you are not reading the input inside the loop ie
i = input.nextInt() ;
This should be inside the while loop.
And finally your change should not be put in that loop as change is a single value. If you keep it the loop change will be read every time the loop iterates. But if you keep it outside the loop another problem arise. ie the change will also be read after reading the coins to coinTypes.
Solution
input.nextLine();
while (input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
int change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size() - 1);
System.out.println("Change: " + change);
System.out.println(coinTypes);
After the loop coinTypes will have the change as the last item. I have removed that last item and kept the last item in change using these lines.
int change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size() - 1);
Alternate Solution
ArrayList<Integer> coinTypes = new ArrayList<Integer>();
Integer i;
File f = new File(args[0]);
Scanner input = new Scanner(f);
input.nextLine();
int change;
String[] coinsline = input.nextLine().split("\\s");
for(String coin: coinsline) {
coinTypes.add(Integer.parseInt(coin));
}
change = Integer.parseInt(input.nextLine());
System.out.println("change: " + change);
System.out.println(coinTypes);
I would open the file, read the first line and split it.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
String[] numbers_= br.readLine().split(" ");
int[] numbers = new int[numbers_.length]; //I don't remember if this could be done.
for(int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.parseInt( numbers_[i] );
}
}
finally {
br.close();
}
I think something like that should work =)
Related
I am writing some pretty basic java code. The idea is to use a loop to write up to 20 numbers into an array. I want to exit the loop when there are no values left. Right now, my code will write to the array, but I cannot get it to exit the loop without entering a non-integer value. I have read some other posts, but they tend to use string methods, which would make my code kind of bulky. I feel like there is a simple solution to this, but I can't seem to figure it out....
import java.util.Scanner;
public class getArray{
public static void main (String[] args){
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt()){
newArray[newArraySize] = scnr.nextInt();
newArraySize += 1;
continue;
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:
--> 1
--> 2
--> 10 11 12 13 14 15 16
--> 20
--> 21
Enter nothing to end data entry and view array contents:
Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
System.out.println("Enter all the Integer values you would like");
System.out.println("stored into your int[] array. You can enter");
System.out.println("them either singular or multiple values on a");
System.out.println("single line spaced apart with a single white");
System.out.println("space. To stop numerical entry and view your");
System.out.println("array contents just enter nothing.");
System.out.println("============================================");
System.out.println();
String inputLine = "";
while (inputLine.isEmpty()) {
System.out.print("Enter a numerical value: --> ");
inputLine = scnr.nextLine().trim();
// If nothing is supplied then end the 'data entry' loop.
if (inputLine.isEmpty()) {
break;
}
//Is it a string line with multiple numerical values?
if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
String[] values = inputLine.split("\\s+");
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
//Is it a string line with a single numerical value?
else if (inputLine.matches("\\d+")) {
valuesList.add(Integer.valueOf(inputLine));
}
// If entry is none of the above...
else {
System.err.println("Invalid numerical data supplied (" + inputLine + ")! Try again...");
}
inputLine = "";
}
System.out.println("============================================");
System.out.println();
// Convert List<Integer> to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i < valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// Display the int[] Array
for (int i = 0; i < newArray.length; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
If I understand correctly, then you want the input of numbers to be limited to the size of the array?
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length && scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
Your while loop condition should be as long as newArraySize is less than the actual size. Here is a fix with some modifications:
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
A solution using Java Stream API:
Scanner sc = new Scanner(System.in);
System.out.println("Input 20 numbers: ");
int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance
.limit(20) // take only 20 values from stream
.toArray(); // put them into array
System.out.println(Arrays.toString(arr)); // print array contents at once
Also, there's a utility method Arrays.setAll allowing to set array values via IntUnaryOperator:
int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());
While loop should have condition for Array Length, kindly try below code which will stop taking inputs after 21st input and array elements will be displayed.
import java.util.Scanner;
public class AarrayScanner {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt() && newArraySize < newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
I have been stuck for some time now. In my code, I want to read all of the names I have from a separate file, and I want to allow the user to select how many names they want to save to a new separate file and allow them to select which names they want to save to the file (by selecting the number in-front of the names printed to the screen).
I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file. My idea was to use the array "select" and check what number was in that array (eg select[0] = 1) and print out number[1].
Any help would be much appreciated, thankyou!
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter writefile;
BufferedReader readfile;
Scanner scan = new Scanner(System.in);
readfile = new BufferedReader(new FileReader("names.txt"));
writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
String names[] = new String[10];
System.out.println("Here are the list of names:");
System.out.println();
for (int i = 0; i < 10; i++) {
names[i] = readfile.readLine();
System.out.println(i + ". " + names[i]);
}
System.out.println();
System.out.println("Please enter the number of names you want to select:");
int choice = scan.nextInt();
System.out.println("Enter the number infront of the names you want to select: ");
int select[] = new int[choice];
for (int j = 0; j < choice; j++) {
select[j] = scan.nextInt();
}
}
}
Your Question: "I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file."
There is nothing wrong with the way you have already opted to do this other than perhaps letting the User know what selection they happen to be currently on and trapping for invalid entries such as values too high or too low and of course alpha characters where numerical characters are required. Without taking care of this business you leave things open to specific Error Exceptions. When asking the User for input a good solution would be for you to take care of what can go wrong and if it does, allow the User to re-enter the required data.
The biggest problem you have is that you have no mechanism in place to write the desired data to file. You've started by declaring a BufferedWriter object but you have yet to implement it. This would of course entail iterating through the select array which ultimately each element holds the index of the names desired to save to file. Simply iterate through the select array and write each name to file:
for (int i = 0; i < select.length; i++) {
writefile.write(name[select[i]] + System.lineSeparator());
writefile.flush();
}
// Close the file when all writing is done.
writefile.close();
With what is discussed above you might have a solution that would look something like this:
try {
BufferedWriter writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
BufferedReader readfile = new BufferedReader(new FileReader("names.txt"));
Scanner scan = new Scanner(System.in);
String allNames = "", fileLine = "";
while((fileLine = readfile.readLine()) != null) {
// Using a 'Terary Operator' to fill the allNames variable
// with a comma delimited string of all the names in file. It
// doesn't matter how many names are in file.
allNames+= (allNames.equals("")) ? fileLine : "," + fileLine;
}
// Split the string in allNames to the names array.
String names[] = allNames.split(",");
// Display the names in console:
// Use the System.out.format() method
// to create a columnar display.
System.out.println("Here are the list of names:");
for (int i = 0; i < names.length; i++) {
// Use the modulus operator to ensure 4 columns
if (i % 4 == 0){
// Print a new line
System.out.print("\n");
}
System.out.format("%-15s", (i+1) + ". " + names[i]);
}
readfile.close(); // Close the reader. Don't need to leave it open.
System.out.println();
// Get the number of names the User wants to save...
int choice = 0;
while (choice == 0) {
System.out.println("\nPlease enter the number of names you want to select:");
try {
choice = scan.nextInt();
}
catch (InputMismatchException ex) {
System.err.println("Invalid Entry! Numerical value Only!\n");
scan.nextLine(); // Clear the scanner buffer
choice = 0;
}
}
// Get the actual names the User wants to save...
System.out.println();
int j = 0;
int select[] = new int[choice];
System.out.println("Enter the numbers in front of the names you want to select: ");
while (j < choice) {
System.out.println("Enter the number for name #" + (j+1) + ": ");
try {
int index = scan.nextInt();
if (index < 1 || index > names.length) {
throw new InputMismatchException();
}
select[j] = index;
j++;
}
catch (InputMismatchException ex) {
System.err.println("Invalid Entry! Numerical value Only (1 to " +
names.length + ")!\n");
scan.nextLine(); // Clear the scanner buffer
}
}
//Write choices to file and Console...
System.out.print("\nSaving Names: ");
for (int i = 0; i < select.length; i++) {
String save = names[select[i]-1] ;
System.out.print(save + "\t");
writefile.write(save + System.lineSeparator());
writefile.flush();
}
writefile.close(); // close the writer
System.out.println("\nDONE! File Created!");
}
catch (IOException ex) { ex.printStackTrace(); }
In this example invalid entries are taken care of and the User is given the chance to enter valid data.
When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}
You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");
Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.
You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}
I'm attempting to take an input from the user, then if it matches one of the existing files, read the file and put the words, letters, or number into an array. The "words", and "alphabet" files seem to work fine, but the "numbers" is giving me an issue. It finds the file, reads it, puts it into an array, and gives the summation of the numbers; however, the output of the array is every other number, as opposed to all numbers, like it should be doing.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class fileIO
{
public static void main (String[] args) throws FileNotFoundException
{
String filename;
System.out.println("Please enter name of file (alphabet,words,numbers): ");
Scanner input = new Scanner(System.in);
filename = input.nextLine();
if(filename.equals("numbers"))
{
int sum = 0;
Scanner reader = new Scanner(new File("/home/ninjew/workspace/FileIO/src/" + filename + ".txt"));
ArrayList<Integer> arr = new ArrayList<Integer>();
while(reader.hasNext())
{
arr.add(reader.nextInt());
sum = sum + reader.nextInt();
}
System.out.println(arr);
System.out.println("The summation is: " + sum);
reader.close();
}
else if(filename.equals("words") || filename.equals("alphabet"))
{
Scanner reader = new Scanner(new File("/home/ninjew/workspace/FileIO/src/" + filename + ".txt"));
// This is for words and letters within the file. Print words and letters.
ArrayList<String> arr = new ArrayList<String>();
while(reader.hasNext())
{
String line = reader.next();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNext()){
arr.add(scanner.next());
}
scanner.close();
}
System.out.println(arr);
reader.close();
}
}
}
In if(filename.equals("numbers")) you are doing two reads from your file in this block, which is why it is skipping numbers
while(reader.hasNext())
{
arr.add(reader.nextInt());
sum = sum + reader.nextInt();
}
Should be
while(reader.hasNext())
{
int val = reader.nextInt();
arr.add(val);
sum = sum + val;
}
Your numbers reader loop is adding first number to the array and the next number to the sum.
If input is 1 2 3 4 5 6, your array is [1, 3, 5] and your sum is 2 + 4 + 6 = 12.
You are reading next two integers in one go. Every time you call scanner.nextInt() it will read a next int. You need to store nextInt in a temp variable and use it in both the places.
while(reader.hasNext())
{
int next = reader.nextInt();
arr.add(next);
sum = sum + next;
}
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);`