I'm writing a program that uses java.util.Scanner to take user input. This will be used in multiple methods...
Is it possible to..
public class Main {
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
...
String mainInput = input.nextLine();
...
}
private static void add(){
...
String addInput = input.nextLine();
...
}
}
Or will I have to have Scanner input = new Scanner(System.in); In both
// methods.
public class Main {
public static void main(String[] args) {
...
Scanner input = new Scanner(System.in);
String mainInput = input.nextLine();
...
}
private static void add(){
...
Scanner input = new Scanner(System.in);
String addInput = input.nextLine();
...
}
}
I plan to have this in 3-4 other methods.
EDIT:
In my program I followed the first. I receive an error: Non-static field ‘input’ cannot be referenced from a static context
ANSWERED!
static Scanner input = new Scanner(System.in);
If you read the input right away the first method would be my way to go.
Related
public class ScannerTest {
protected Scanner scan;
public ScannerTest(String s) {
Scanner scan = new Scanner(s);
}
public void getone() {
if (scan.hasNext()) {
String temp = scan.next();
temp = temp.replaceAll("[\\[\\](){}]", "");
System.out.println(temp);
}
}
public static void main(String[] args) {
String s = "(abcd) (defg) (w)";
ScannerTest test = new ScannerTest(s);
Scanner rando = new Scanner(s);
System.out.println(rando.next());
System.out.println(rando.hasNext());
test.getone();
}
}
you are victim of so called variable shadowing.
With line
Scanner scan = new Scanner(s);
you are declaring a local variable scan instead of initialize your member scan inside a your ScannerTest class. Change the mentioned line to
scan = new Scanner(s);
and it will work as desired...
complete source code
import java.util.Scanner;
public class SomeClass {
protected Scanner scan;
public SomeClass(String s) {
scan = new Scanner(s);
}
public void getone() {
if (scan.hasNext()){
String temp = scan.next();
temp = temp.replaceAll("[\\[\\](){}]","");
System.out.println(temp);
}
}
public static void main(String[] args) {
String s = "(abcd) (defg) (w)";
SomeClass test = new SomeClass(s);
Scanner rando = new Scanner(s);
System.out.println(rando.next());
System.out.println(rando.hasNext());
test.getone();
}
}
Apologies for the weird formatting, this is my first post. The null pointer exception is being thrown in the getone() method. First at hasNext(), and if I remove that, at next().
As I understand, the contentEquals() method only accepts one argument to be compared with.
In the following program, what if I wanted to pass in more?
like:
(1)YES
(2)Yes
(3)Y
(4)y
import java.util.Scanner;
public class ifStatement1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Want some pizza?");
String userInput = input.nextLine();
boolean answer = **userInput.contentEquals("yes");**
if(answer) {
System.out.println("so go take a break from all this code");
}
else {
System.out.println("so keep writing code");
}
}
}
Set.of("YES", "Yes", "Y", "y").contains(userInput)
String.equals would be more normal than using String.contentEquals with a String.
import java.util.Scanner;
import java.util.Set;
public class example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine();
boolean answer;
if(Set.of("yes","y").contains(userInput.toLowerCase())){
answer = true;
} else {
answer = false;
}
System.out.print(answer);
}
}
I wanted to create a simple program for user to insert 3 strings to a private string array in a class and then print it back by creating a new object using object reference but I think I am facing problem in the setter/getter.(Pretty new to class and setter/getter) Here is what I have so far:
import java.util.Scanner;
public class Stringtest {
public static void main(String[] args)
{ Scanner input=new Scanner(System.in);
Stringer Strung=new Stringer();
System.out.println("Strings:"+Strung.print());
}
}
class Stringer
{ Scanner input=new Scanner(System.in);
private String[] aa=new String[3];
aa[0]="zero";
aa[1]="one";
aa[2]="two";
Stringer()
{}
{ System.out.println("Please enter 3 strings:");
for(int i=0;i<4;i++)
{
aa[i]=input.next();
}
}
public void setaa(String[] a)
{
aa=a;
}
public String[] getaa()
{
return aa;
}
public void print(String[] a)
{
for(int b=0;b<4;b++)
{
System.out.printf("%s",a[b]);
}
}
}
Due to populating the array while creating a class instance, you don't require any setters. The only getter requires.
Divide the logic from the runner.
Always use array.length() while looping or use a simple for loop otherwise you'll be getting an indexOfBoudException error.
Didn't get why you are using printf() while printing results.
My solution:
import java.util.Scanner;
public class App {
public static void main(String[] args) {
App.run();
}
private static void run() {
Stringer stringer = new Stringer();
stringer.print(stringer.getStrings());
}
}
class Stringer {
private String[] strings = new String[3];
Stringer() {
System.out.println("Please enter 3 strings:");
for (int i = 0; i < 4; i++) {
Scanner scanner = new Scanner(System.in);
strings[i] = scanner.next();
}
}
String[] getStrings() {
return strings;
}
void print(String[] strings) {
System.out.println("Strings are:");
for (String string : strings) {
System.out.println(string);
}
}
}
The JDK compiler says it compiles, but when it runs I get this error:
Static Error: This class does not have a static void main method accepting String[].
I am used to putting my methods class in one file and putting the main class in a sperate file.
How do I go about solving this issue?
import java.util.Scanner;
public class Test{
private final int classSize = 35;
private int numEnrolled, numNeeded;
public void Input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);
// Other parts of code that needs to be coded
}
}
class testRunner{
static void main(String args[]){
Test newTest = new Test();
newTest.Input();
}}
In one file you can have only one public class, and multiple
non-public classes
Your filename has to match with the only public
class
To make your class runnable it should contain a public static
void main(String args[]) method, preferably in the public class
Your TestRunner.java should look like this
class Test{
private final int classSize = 35;
private int numEnrolled, numNeeded;
public void Input(){
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);
// Other parts of code that needs to be coded
}
}
public class TestRunner{
public static void main(String args[]){
Test newTest = new Test();
newTest.Input();
}}
Edit:
If you want to leave the file name Test.java, this works too:
public class Test {
private final int classSize = 35;
private int numEnrolled, numNeeded;
public void Input() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the amount enrolled in your class");
numEnrolled = in.nextInt();
System.out.println("Your input is " + numEnrolled);
// Other parts of code that needs to be coded
}
}
class TestRunner {
public static void main(String args[]) {
Test newTest = new Test();
newTest.Input();
}
}
Change:
class testRunner{
static void main(String args[]){
Test newTest = new Test();
newTest.Input();
}}
to:
public class testRunner {
public static void main(String args[]) {
Test newTest = new Test();
newTest.Input();
}}
main() must always be declared public
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String q = null, s = "nul";
userName(q);
userGender(s);
print(userName(q));
print(userGender(s)); // how to achieve something like this?
}
public static void userName(String x) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
String n = sc.nextLine();
}
public static void userGender(String y) {
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
String v = sd.next().toString();
}
public static void print(String a) {
System.out.println(a);
}
So I was trying to make it so that a method would be used to print another method after they were done executing but I couldn't get the desired result and it gave an error.
The method print works fine, it takes a String and return nothing
public static void print(String a)
{
System.out.println(a);
}
However, your method userGender and userName returns nothing, so when you are feeding print with a method that isn't returning a string, it will produce an compile-time error. You want to do something similar to:
public static String userGender(String y){
Scanner sd = new Scanner(System.in);
System.out.print("Enter Gender: ");
return sd.next().toString();
}
I haven't tested it, as your logic is unclear to me, but this is probably why your IDE is complaining.
Your method needs to return something. You are declaring your method like this: public static void userGender(String y) the void means that your method won't return anything. But since you want that the method returns a String you need to tell this in the method signature.
Your code could look like this:
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
try(Scanner sc = new Scanner(System.in)){ // this is try resource see which will close your resource once you are done in the try block see https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
System.out.print("Enter name: ");
return sc.next();
}
}
public static String userGender() {
try(Scanner sc = new Scanner(System.in)) {
System.out.print("Enter Gender: ");
return sc.next();
}
}
public static void print(String a) {
System.out.println(a);
}
You don't need to use toString() since the next returns already a String. Also you can use the same variable name in different methods. And really important you need to close the Scanner again, otherwise it will consume endless resources.
Like #reebow and #Kerry Gougeon both pointed out that your method is looking to return something so you make it public static String userName() or public static String userName(String s).
If you're wanting to user Scanner then you're going to have to declare Scanner globally, otherwise it will throw a NoSuchElementExcpetion
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
print(userName());
print(userGender());
}
public static String userName() {
System.out.print("Enter name: ");
return sc.next();
}
public static String userGender() {
System.out.print("Enter Gender: ");
return sc.next();
}
public static void print(String a) {
System.out.println(a);
}
If you're not using Scanner then you can just return the String that you passed to the method.
public static void main(String[] args) {
System.out.println("Hello and welcome! Please enter the following: ");
String a = null, b ="nul";
print(userName(a));
print(userGender(b));
}
public static String userName(String a) {
System.out.print("Enter name: ");
return a;
}
public static String userGender(String b) {
System.out.print("Enter Gender: ");
return b;
}
public static void print(String a) {
System.out.println(a);
}