英文:
Using same object to take integer input and string input in java
问题
I am new to Java programming. I was reading about Scanner class and I decided to compile a simple program:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
Scanner obj2=new Scanner(System.in);
int n=obj.nextInt();
String s = obj2.nextLine();
System.out.println(n*2);
System.out.println(s);
}
}
By using the object obj, I can only read the integer input and doesn't let me read the String input. Why can't we use the same object of Scanner class for taking the input since the only use of object is to call a method like nextLine().
Whereas if I use this code,
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
Scanner obj2=new Scanner(System.in);
int n=obj.nextInt();
String s = obj2.nextLine();
System.out.println(n*2);
System.out.println(s);
}
}
Using a different object obj2 for string and obj for integer, I get my desired output.
Any help would be appreciated!
英文:
I am new to Java programming. I was reading about Scanner class and I decided to compile a simple program:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
Scanner obj2=new Scanner(System.in);
int n=obj.nextInt();
String s = obj.nextLine();
System.out.println(n*2);
System.out.println(s);
}
}
By using the object obj, I can only read the integer input and doesn't let me read the String input. Why can't we use the same object of Scanner class for taking the input since the only use of object is to call a method like nextLine().
Whereas if I use this code,
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
Scanner obj2=new Scanner(System.in);
int n=obj.nextInt();
String s = obj2.nextLine();
System.out.println(n*2);
System.out.println(s);
}
}
Using a different object obj2 for string and obj for integer,I get my desired output.
Any help would be appreciated!
答案1
得分: 1
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
int n=obj.nextInt();
String s = obj.next();
System.out.println(n*2);
System.out.println(s);
}
}
英文:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
int n=obj.nextInt();
String s = obj.next();
System.out.println(n*2);
System.out.println(s);
}
}
答案2
得分: -3
尝试这个:String s = obj2.next();
英文:
try this: String s = obj2.next();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论