I was trying to solve a question for Java Hashmaps where we need to search if key is present or not. If yes, print the String value otherwise print -1.
public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Map<Integer,String> hmap=new HashMap<Integer,String>();
Scanner in=new Scanner(System.in);
int length= in.nextInt();
for(int i=0;i<length;i++) {
hmap.put(in.nextInt(),in.nextLine());
}
while(in.hasNext()) {
int number= in.nextInt();
if(hmap.containsKey(number)) {
String value=hmap.get(number);
System.out.println(value);
}
else {
System.out.println(-1);
}
}
in.close();
}
But all test cases are not passing. Can anyone please help with what is wrong?
Scanner has a problem interpreting your input if you use in.nextLine() after in.nextInt(). It is because the newline (\n) of your int input (e.g. 4 ENTER => 4\n) remains after returning the int via in.nextInt() and is recognized by the in.nextLine().
As workaround you could use an additional in.nextLine().
for(int i=0;i<length;i++) {
Integer key =in.nextInt();
in.nextLine();
String line = in.nextLine ();
hmap.put(key,line);
}
Related
I am running into a problem, that everytime the do{...} while(...) loop runs the second time, the first iteration of for(...) loop does not execute the following statement
array[o] = scan1.nextLine();.
This is what i have tried so far:
import java.util.Scanner;
public class test
{
public static void main(String args[]) throws Exception
{
int columns=2;
String array[]=new String[10];
char ins_check='y';
Scanner scan1=new Scanner(System.in);
do {
System.out.println("Enter the value");
for (int o = 1; o <= columns; o++) {
System.out.println("Enter the value");
array[o] = scan1.nextLine();
}
System.out.println("record inserted");
System.out.println("Do you want to insert again?(y/n)");
ins_check= (char) System.in.read();
}while(ins_check != 'n');
}
}
While several commenters told you what to do and what not to do, they didn't answer your question about the reason why this is occuring.
the first time of for loop does not execute this statement: array[o] = scan1.nextLine();
You are mistaken - the statement is well executed, it's only that an empty line is read. And this is because after the prompt "Do you want to insert again?(y/n)" you entered a line consisting of the two characters y \n, and System.in.read() read only one byte of data (the y), leaving the newline character \n in the input stream. The subsequent scan1.nextLine() gets this \n and returns the empty line.
Here is still someone who post answer faster then me. Take a look on reply from Amali, thats right answer :) this should work fine:
import java.util.Scanner;
public class test
{
public static void main(String args[]) throws Exception
{
Scanner scan1=new Scanner(System.in);
String array[]=new String[10];
String ins_check="y";
int columns=9;
do {
for (int o = 0; o <= columns; o++) {
System.out.printf("Enter the value for array[%s]",o);
array[o] = scan1.nextLine();
}
System.out.println("record inserted");
System.out.println("Do you want to insert again?(y/n)");
ins_check= scan1.nextLine();
}while(ins_check.equals("y"));
System.out.println("end");
}
}
the first line takes the size of the array to follow.The array's digits are checked to see if they can form a ambiguous permutation.
public class Codechef2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int intnum=10;
intnum=input.nextInt();
input.nextLine();
String a[]=new String[100000];
int count=0;
int i=0;
While(intnum>0)
{
a[i]=input.nextLine();
String arr[]=a[i].split(" ");
int aj[]=new int[arr.length];
int k=0;
for(int j=0;j<arr.length;j++)
{
aj[Integer.parseInt(arr[k])]=j+1;
k++;
}
for(int l=0;l<arr.length;l++)
{
if(aj[l]==Integer.parseInt(arr[l]))
count++;
}
if(count==arr.length)
System.out.println("ambiguous permutation");
else
System.out.println("Not ambiguous permutation");
intnum=input.nextInt();
}
}
}
EDIT:
Again: pleas post a compilable code:
//wrong
//While(intnum>0)
while(intnum>0)
Also:
//you need to print a msg so the user knows that he / she
//needs to input and tell the user what to input
System.out.println("Please enter ....");
input.nextLine();
The code has many errors.
For example :
String aj[]=new aj[arr.length]; //will not compile
While(intnum>0) //will not compile
a[i]=input.nextLine(); //will not compile. i is defined later.
aj[arr[k]]=i+1; //wrong : aj[] is a String. i+1 is an int.
Fix them and post a compilable code.
Code below the while loop is not executed until the conditions of the while loop are met.
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);
}
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
}
}
I've created an array 8 elements long using the scanner class. I'm trying to accept user inputs via scanner and print out the value at that index location. eg if the user enters '2', it prints out the value at the second element. I've searched on google but all the resources are how to use the scanner to input data into an array, not using the scanner to retreive data back. the only way I thought of is by using a ridiculous amount of if else statements but there must be a cleaner way to do it in a loop?
This is my array, I've used the scanner to fill my array. Now, on prompt, the user must input a number from 1 to 8. If they input 1, print out solution[0]. Input 8, print out solution[7] etc. Hope its easier to understand now
String[] solution = new String[8];
Scanner scan = new Scanner( System.in );
for( int i = 0; i < solution.length; i++ ){
System.out.println( "Enter solution:" );
solution[ i ] = scan.next();
}
scan.close();
Scanner scan1 = new Scanner( System.in );
String selection;
System.out.println("Enter an int between 0 and 7 to retrieve the Selection: ");
selection = scan1.next();
int i = Integer.parseInt(selection);
System.out.println( "The Selection is: " + solution[i] );
This is difficult without any code, but basically, use the scanner to get the input into string selection, get the integer value into int i with int i = Integer.parseInt(selection);, then myArray[i].
Scanner input = new Scanner(System.in);
then output:
urArray[input.nextInt()];
You have to read an int, and use this when getting the value stored at the specified index.
A way to do this is the following:
yourArray[scanner.nextInt()];
Where scanner is the Scanner object.
To catch the excpetions you may receive when reading things you assume are numbers, you could do this:
Scanner scanner = new Scanner(System.in);
try {
yourArray[scanner.nextInt()];
} catch(IllegalStateException | NoSuchElementException e) { // <--- Java 1.7 syntax, in case you wonder
e.printStackTrace();
}
import java.util.Scanner;
public class array1
{
public static void main(String args[])
{
int arr[]=new arr[100];
int i;
Scanner sc=new Scanner(System.in);
System.out.pritln("Enter the Number of Element less than 100");
int a=sc.nextInt();
System.out.println("Enter the Number");
for(i=0;i<a;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("List of Elements in array");
for(i=0;i<a;i++)
{
System.out.println(arr[i]);
}
}
}