Scanner throwing null pointer when trying to get next - java

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().

Related

Is there any public/global variable in java?

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.

Illegal start of expression2

I am trying to write a method to capitalize words ending with an "s" in an arrayList
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("speech.txt"));
ArrayList<String> myList = new ArrayList<String>();
public void input() {
while (input.hasNext()) {
myList.add(input.next());
}
}
public void capPlurals() {
for (int i = 0; i < myList.size(); i++) {
String element = myList.get(i);
if (element.endsWith("s")) {
System.out.println(element.toUpperCase());
}
}
}
}
Test.java:12: error: illegal start of expression
public void input() {
^
Just remove those useless method declarations inside your main() method - as mentioned in the comments you cannot define methods inside other methods.
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("speech.txt"));
ArrayList<String> myList = new ArrayList<String>();
while (input.hasNext()) {
myList.add(input.next());
for (int i = 0; i < myList.size(); i++) {
String element = myList.get(i);
if (element.endsWith("s")) {
System.out.println(element.toUpperCase());
}
}
}
}
}
You can't declare a method inside another method. Declare them outside the main and pass proper arguments.
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("speech.txt"));
ArrayList<String> myList = new ArrayList<>();
addToList(input, myList);
capPlurals(myList);
}
public static void addToList(Scanner input, ArrayList<String> myList) {
while (input.hasNext()) {
myList.add(input.next());
}
}
public static void capPlurals(ArrayList<String> myList) {
for (int i = 0; i < myList.size(); i++) {
String element = myList.get(i);
if (element.endsWith("s")) {
System.out.println(element.toUpperCase());
}
}
}
}

Java string array with setter getter

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);
}
}
}

I'm trying to use a method to print another method

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);
}

Is it possible in java to get multiple inputs in a single line??

I am trying to get multiple inputs in a single code of line..
for example in c++, we could have it like -
int a,b,c;
cin>>a>>b>>c;
is it possible in java also??
You can use an array for this purpose, like:
public static void main(String[] args) {
int[] values = new int[3];
Scanner in = new Scanner(System.in);
for(int i = 0; i < values.length; i++) {
values[i] = in.nextInt();
}
System.out.println(Arrays.toString(values));
}
UPDATE 2
In java 8 the above solution can have a shorter version:
Scanner in = new Scanner(System.in);
Integer[] inputs = Stream.generate(in::nextInt).limit(3).toArray(Integer[]::new);
UPDATE 1
There is another way, which is closer to cin:
public class ChainScanner {
private Scanner scanner;
public ChainScanner(Scanner scanner) {
this.scanner = scanner;
}
public ChainScanner readIntTo(Consumer<Integer> consumer) {
consumer.accept(scanner.nextInt());
return this;
}
public ChainScanner readStringTo(Consumer<String> consumer) {
consumer.accept(scanner.next());
return this;
}
}
public class Wrapper {
private int a;
private int b;
private String c;
public void setA(int a) {
this.a = a;
} /* ... */
}
public static void main(String[] args) {
ChainScanner cs = new ChainScanner(new Scanner(System.in));
Wrapper wrapper = new Wrapper();
cs.readIntTo(wrapper::setA).readIntTo(wrapper::setB).readStringTo(wrapper::setC);
System.out.println(wrapper);
}

Categories