String input in java - java

I am trying to take string input in java using Scanner, but before that I am taking an integer input. Here is my code.
import java.util.*;
class prc
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=1;i<=n;i++)
{
String str=input.nextLine();
System.out.println(str);
}
}
}
The problem is that if I give a number n first, then the number of string it is taking as inputs is n-1.
e.g if the number 1 is entered first, then it is taking no string inputs and nothing is printed.
Why is this happening ?
Thanks in Advance!

nextLine() reads everything up to and including the next newline character.
However, nextInt() only reads the characters that make up the integer, and if the integer is the last (or only) text in the line, you'll be left with only the newline character.
Therefore, you'll get a blank line in the subsequent nextLine(). The solution is to call nextLine() once before the loop (and discard its result).

Information regarding the code is mentioned in the comments written next to each line.
public static void main(String[] args) {
int num1 = sc.nextInt(); //take int input
double num2 = sc.nextDouble(); //take double input
long num3 = sc.nextLong(); //take long input
float num4 = sc.nextFloat(); //take float input
sc.nextLine(); //next line will throw error if you don't use this line of code
String str = sc.nextLine(); //take String input
}

import java.util.*;
class prc
{
public static void main(String[] args)
{
String strs[];
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine();
strs = new String[n];
for(int i = 1; i < n; i++)
{
strs[i] = input.nextLine();
System.out.println(strs[i]);
}
}
}

Related

Prevent going to next line after input in console

I have problem with my Java program. I am running the program on the console (CMD).
I would like, after I entered input, that the console stays on the same line (currently it goes to the next line automatically).
This is my current program:
int data[];
Scanner in = new Scanner(System.in);
data = new int[10];
System.out.println("Please Insert Numbers : ");
for(int i=0;i<5;i++)
{
data[i] = in.nextInt();
System.out.print("/t");
}
How can I return to the start of the line instead of going to the next?
Scanner in = new Scanner(System.in);
System.out.println("Please Insert Numbers Separated By Comma: ");
String input = in.nextLine();
input = input.replaceAll("\\s",""); //remove whitespaces
String[] numbers= input.split(","); //build string array using ',' as delimiter between numbers
int data[]= Arrays.asList(numbers).stream().mapToInt(Integer::parseInt).toArray(); //Available since Java8
Like Oscar Martinez said, you could read a string of numbers delimited by white space and build your integer array like this example (before parsing the string to int, I verify if the string can be converted to int or not using a regex ) :
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int data[];
Scanner in = new Scanner(System.in);
data = new int[10];
System.out.println("Please Insert Numbers : ");
String line = in.nextLine();
String[] stringsNumber = line.split("\\s");
for(int i=0;i<stringsNumber.length;i++){
if(stringsNumber[i].matches("^\\d+$") && i<10){// \\d is a regex to verify if s is a number
data[i]= Integer.parseInt(stringsNumber[i]);
}
}
System.out.println(Arrays.toString(data));
}
}

How to take array elements as input

My program is to accept words (given as number of test cases) and print them out in reversed order. The problem is that whatever input of array size I may give, it only accepts just one word (and rest as blank). Can anyone help me figure out why? Here's the code:
import java.util.*;
public class terrible {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int test = input.nextInt();
while(test>0){
String str = input.nextLine();char c[] = str.toCharArray();
for(int i=0;i<str.length();i++){
System.out.print(c[str.length()-i-1]);
}
System.out.println();
test--;
}
}
}
Certain versions of Java don't let you take an int and then a string as input from the same Scanner. You can create another Scanner, like
Scanner input2 = new Scanner(System.in);
and then do
String str = input2.nextLine();

Java Scanner delimiter and System.in

I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}

How to make my code accepts an input

I would just like to ask on how can I make my code to just get the input instead of declaring it? Here's my program. I want to input different atomic numbers and not just "37" like what's in my code. Don't mind my comments, it's in my native language. Thanks!
public class ElectConfi {
public static void main(String s[]) {
int atomicNumber = 37;
String electronConfiguration = getElectronConfiguration(atomicNumber);
System.out.println(electronConfiguration);
}
public static String getElectronConfiguration(int atomicNumber) {
int[] config = new int[20]; //dito nag store ng number of elec. in each of the 20
orbitals.
String[] orbitals = {"1s^", "2s^", "2p^", "3s^", "3p^", "4s^", "3d^", "4p^", "5s^",
"4d^", "5p^", "6s^", "4f^", "5d^", "6p^", "7s^", "5f^", "6d^", "7p^", "8s^"};
//Names of the orbitals
String result="";
for(int i=0;i<20;i++) //dito ung i represents the orbital and tapos ung j
represents ng electrons
{
for(int j=0;(getMax(i)>j)&&(atomicNumber>0);j++,atomicNumber--) //if atomic
number > 0 and ung orbital ay kaya pa magsupport ng more electrons, add
electron to orbital ie increment configuration by 1
{
config[i]+=1;
}
if(config[i]!=0) //d2 nagche-check to prevent it printing empty
orbitals
result+=orbitals[i]+config[i]+" "; //orbital name and configuration
correspond to each other
}
return result;
}
public static int getMax(int x) //returns the number of max. supported electrons by each
orbital. for eg. x=0 ie 1s supports 2 electrons
{
if(x==0||x==1||x==3||x==5||x==8||x==11||x==15||x==19)
return 2;
else if(x==2||x==4||x==7||x==10||x==14||x==18)
return 6;
else if(x==6||x==9||x==13||x==17)
return 10;
else
return 14;
}
}
You can use either a Scanner or BufferedReader and get the user input
Using Scanner
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Using BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int atomicNumber = Integer.parseInt(reader.readLine());
public static String getElectronConfiguration(int atomicNumber) {}
This method accepting any int value and will return String result. so you only need to provide different number as input. There is no change required in this method.
How to provide different inputs?
You can use Scanner to do that.
Scanner scanner = new Scanner(System.in);
System.out.println("Please input atomic number");
int atomicNumber = scanner.nextInt();
Now call your method
String electronConfiguration = getElectronConfiguration(atomicNumber);
What are the other ways?
You can define set of values for atomicNumber in your code and you can run those in a loop
You can get input from command line arguments by doing below :
Scanner scanner = new Scanner(System.in);
String inputLine = scanner.nextLine(); //get entire line
//or
int inputInt= scanner.nextInt();//get an integer
Check java.util.Scaner api for more info - http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Hope this helps!
You can get the user input from a command line argument:
public static void main(String s[]) {
if (s.length == 0) {
// Print usage instructions
} else {
int atomicNumber = Integer.parseInt(s[0]);
// rest of program
}
}

Scanner only reading first set of input

This is a code I have developed to separate inputs by the block (when a space is reached):
import java.util.Scanner;
public class Single {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Three Numbers:");
String numbers = in.next();
int length = numbers.length();
System.out.println(length);
int sub = length - length;
System.out.println(sub);
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
System.out.println(getNumber(numbers, length, sub));
}
public static double getNumber(String numbers, int length, int sub){
boolean gotNumber = false;
String currentString = null;
while (gotNumber == false){
if (numbers.substring(sub, sub + 1) == " "){
sub = sub + 1;
gotNumber = true;
} else {
currentString = currentString + numbers.substring(sub, sub);
sub = sub + 1;
}
}
return Double.parseDouble(currentString);
}
}
However, it only reads the first set for the string, and ignores the rest.
How can I fix this?
The problem is here. You should replace this line
String numbers = in.next();
with this line
String numbers = in.nextLine();
because, next() can read the input only till the first space while nextLine() can read input till the newline character. For more info check this link.
If I understand the question correctly, you are only calling in.next() once. If you want to have it process the input over and over again you want a loop until you don't have any more input.
while (in.hasNext()) {
//do number processing in here
}
Hope this helps!

Categories