I am making a program that takes the user his 3 number input and then compares these individual numbers to numbers I have.
How do I split and save these use input numbers to individual integers?
String.split() and Integer.parseInt() are your friends.
String input = "1 2 3";
String[] spl = input.split(" "); //Or another regex depending on the input format
for (String s : spl) {
System.out.println(Integer.parseInt(s)); // or store them as you like
}
String input = "12 23 12";
String[] split = input.split(" "); // or "\t" according to need
int[] arr = new int[split.length];
int count = 0;
for(String s:split)
{
arr[count] = Integer.parseInt(s).intValue();
count++;
}
There is very convenient class added to Java 1.5 called Scanner.
Here is my sample program that reads String, finds all decimal numbers and prints them to console. Delimiter by default is whitespace.
public static void main(String[] args) {
String userInput = "1 2 3 4 5 6";
try (Scanner scanner = new Scanner(userInput)) {
scanner.useRadix(10);
while (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.println(i);
}
}
}
E.g. String userInput = "1 2 3 4 5 df 6"; // output 1 2 3 4 5
There are couple of advantages:
There is no need to call parseInt method, that can throw unchecked exception NumberFormatException if user input was incorrect.
Returns value of primitive type int (or any other on your choice)
Input source can be easily changed to File, InputStream, Readable, ReadableByteChannel, Path.
Related
I want to read multiple words into a string called input. The words can be casted into numeric values like "1 14 5 9 13". After the user input, the string will be converted into a string array separated by spaces.
public class ArraySum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.next());
System.out.println("Please enter "+n+" numbers");
String input = scanner.next(); // ERROR: only the first word is read
String[] inputs = input.split("\\s+");
int sum=0;
for (int i =0; i<inputs.length; i++){
if (!inputs[i].equals(""))
sum+= Long.parseLong(inputs[i]);
}
System.out.print(sum);
}
}
However only the first word is read into the string.
This answer suggests using nextLine() to read a multi-word string, but if I change it, an error was thrown.
java.lang.NumberFormatException: null
Apparently an empty/null string was inputted before I entered any word.
You have to use nextLine after nextInt to clear your Scanner like this :
int n = scanner.nextInt();//read your int
scanner.nextLine();//clear your Scanner
System.out.println("Please enter " + n + " numbers");
String input = scanner.nextLine();//read your String example 12 55 66
First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!
EDIT: This is the input:
1st number is m, followed by m numbers. Next entry is n followed by n lines, each with varying and unknown number of elements.
5
1 2 3 4 5
3
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
How can I read this input in Java using the scanner class? nextInt doesn't seem to take the next line character into account.
One way is to take the whole line as input and get the integers from it but am looking for something faster.
My code works for the following constraints:
1 ≤ M ≤ 10
1 ≤ N ≤ 100
The number of elements in the n lines ranges between 1 and 100
but times out for the following(takes more than 3s):
1 ≤ M ≤ 100
1 ≤ N ≤ 9 x 103
The number of elements in the n lines ranges between 1 and 1000
Here's what am doing:
public static void main(String[] str) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> qualities = new ArrayList<Integer>();
int m = in.nextInt();
in.nextLine();
for(int i=0;i<m;i++)
qualities.add(in.nextInt());
int n = in.nextInt();
in.nextLine();
for(int j=0;j<n;j++) {
HashSet<Integer> qua = new HashSet<Integer>();
String[] strng = in.nextLine().split(" ");
for(String x: strng)
qua.add(Integer.parseInt(x));
solve(qua);
}
System.out.print(count);
}
Just wanted to know if there is a way I can avoid using in.nextLine() while reading the line with multiple integers and just use in.nextInt() instead.
The number of integers in each line varies and is unknown.
How can I read this input in Java using the scanner class?
To detect new line with Scanner, you need to have 2 things.
1)Grasp the first line say L.
2)Feed L into a new Scannerand get your Ints.
Something like:
Scanner scan=new Scanner(new File("input.txt"));
while(scan.hasNext())
{
String s=scan.nextLine();
Scanner inscan=new Scanner(s);
while(inscan.hasNext())
System.out.print(" "+inscan.nextInt());
System.out.println("");
inscan.close();
}
scan.close();
Try this:
String contents =
"3\n" +
"1 2 3 4 5 6\n" +
"1 2 3 4 5\n" +
"1 2 3 4\n";
int[][] result = null;
try (BufferedReader reader = new BufferedReader(new StringReader(contents))) {
int i = 0;
int count = 0;
String line;
while ((line = reader.readLine()) != null)
if (result == null)
result = new int[count = Integer.parseInt(line)][];
else if (i < count)
result[i++] = Stream.of(line.split(" "))
.mapToInt(s -> Integer.parseInt(s))
.toArray();
else
break;
}
for (int[] line : result)
System.out.println(Arrays.toString(line));
// result:
// [1, 2, 3, 4, 5, 6]
// [1, 2, 3, 4, 5]
// [1, 2, 3, 4]
If you are using Scanner you don't need to do anything other than use it. This code works for both a string input and direct input from the system input. As you can see it is a simple use of Scanner, the only change is to decide which way you want to instantiate the scanner, i.e. to select either a String or System.input source.
public static void main(String[] args)
{
System.out.println("\nInput some numbers (end by typing a non number)"); //$NON-NLS-1$
String contents =
"1 2 3 4 5\n" +
"1 3 5 7 9\n" +
"5 4 3 2 1\n" +
"100 33 -146\n";
// scanner form string
Scanner sc = new Scanner(contents);
// scanner from system input
// Scanner sc = new Scanner(System.in);
List<Integer> li = new LinkedList<>();
while (true)
{
try
{
Integer i = sc.nextInt();
li.add(new Integer(i));
}
catch(InputMismatchException e)
{
break;
}
catch(NoSuchElementException e)
{
break;
}
}
Integer sum = 0;
for (Integer i : li)
{
sum += i;
}
StringBuilder sb = new StringBuilder("sum = ").append(sum); //$NON-NLS-1$
System.out.println(sb.toString());
sc.close();
}
running with the Scanner linked to the String or the System input produces the same result
42
No special handling of \n is required due to the whitespace rules employe din java.
EDIT:
The InputMismatchException exception is thrown when the System.input source is used and you enter a non number, like an X. The NoSuchElementException exception is thrown when the source is a String and the input is exhausted.
This is just an example, you woul dhave to handle end of System.input better for production code.
In an interview they asked me this question.There is a string like "12 computer 5 7". You need to add integers within that string and answer should be 24.How can i solve this can anyone help me please.
string s="12 computer 5 7"
output should be:24
Can i use sub-string or some other process to solve it
Try this,
String input = "12 computer 5 7";
String[] splittedValue = input.split(" "); // splitted the values by space
int result = 0;
for (String s : splittedValue)
{
if (s.matches("\\d+")) // check while the input is number or not
{
result = result + Integer.parseInt(s); // parse it and add it to the count
}
}
System.out.println("Result : "+result);
Use split("[ ]") to convert the string into an array of strings separated by space and then add the integers present in each position of the array. Add it to sum if it is an integer like :-
String ar[] = s.split("[ ]");
int sum = 0;
for(int i=0;i<ar.length;i++){
try{
sum += Integer.parseInt(ar[i]);
}catch(NumberFormatException){
//not an integer.
}
}
System.out.println("Sum of integers : "+sum);
public class Main{
public static void main(String []args){
String s="12 computer 5 7";
String [] candidateNumbers = s.split(" ");
int sum = 0;
for (String num:candidateNumbers) {
try {
sum+=Integer.parseInt(num);
} catch (Exception e) {
//
}
}
System.out.println(sum);
}
}
Using Java 8 you could also write:
int sum = Arrays.stream(s.split("\\D+"))
.mapToInt(Integer::parseInt)
.sum();
Splitting on non digit characters returns an array containing the 3 numbers as strings. Note that this assumes that the input string is well formed.
Input (white space delimited):
1 1 2 3
2 1 7
3 3 7
4 1 5
5 3 6
I would like to process these input as like:
For each line in the text file :: (first_element, e.g. 1) into an int variable (say, m) and the following (next_elements, e.g. 1 2 3) into an ArrayList (say, N)
I tried the below:
Scanner file_scanner = new Scanner(filename);
while (file_scanner.hasNextLine()) {
String[] line = file_scanner.nextLine().split("\\s+");
String str1 = line[0];
String str2 = line[1];
m = Integer.parseInt(str1);
Scanner line_scanner = new Scanner(str2);
while(line_scanner.hasNext()) {
int n = line_scanner.nextInt();
N.add(n);
}
}
But I am not able to parse the inputs as I intended to. Any kind suggestions on how to handle two parts of an input line using Scanner? or, even how to check the end of the current line (EOL) as well as how to parse the first element more easily?
try this String[] line = file_scanner.nextLine().split("\\s+",2); in your code. It will split each line into 2 tokens only.
EDIT: line[1] will contain the rest of the numbers, you do not need to parse it again.
Sorry it might not be the most efficient since it's 4:39 am:
Scanner s = new Scanner(file);
int m = 0;
List<Integer> list = null;
while(s.hasNextLine())
{
Scanner s2 = new Scanner(s.nextLine());
int count = 0;
list = new ArrayList<Integer>();
while (s2.hasNextInt())
{
if(count == 0)
{
m = s2.nextInt();
}
else
{
list.add(s2.nextInt());
}
count++;
}
System.out.println(m + " " + list);
}