Java Input not working (Beginner)

为君一笑 提交于 2019-12-01 22:52:54

You need to call in.nextLine() right after the line where you call in.nextInt() The reason is that just asking for the next integer doesn't consume the entire line from the input, and so you need skip ahead to the next new-line character in the input by calling in.nextLine()

customerChoice = in.nextInt();
in.nextLine();

This pretty much has to be done each time you need to get a new line after calling a method that doesn't consume the entire line. Consider using a BufferedReader object instead!

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int integer = Integer.parseInt(reader.readLine());

This will throw the same errors that Scanner.nextInt() does if the input can't be parsed as an integer.

Regarding your comment about errors, there is one:

while (indexCount <= menuCount);
System.out.println("Please enter your item: ");
item = in.nextLine(); {
 theMenu.add(item);
}

}

Should instead be like the following:

while(indexCount <= menuCount){
    System.out.println("Please enter your item: ");
    item = in.nextLine();
    theMenu.add(item);
}

Also, it isn't strictly necessary, but I suggest that you do declare the ArrayList's generic type when instantiating the list, so that further calls to theMenu.get() don't need to be casted to a String.

ArrayList<String> theMenu = new ArrayList<String>();

When comparing strings, ensure that you use the str.equals("string to compare with") method, instead of the equality operator (==). Therefore for example, choice2 == "yes" should instead be choice2.equals("yes"). Using equalsIgnoreCase instead of equals would ignore case differences, which may be useful in this situation.

insted of in.nextLine(); function you just try another scanner functions like 'in.next()'. just R&D with the methods that already give the JVM itself. you just use correct the logic and use equal() or equlIgnoreCase() methods insted of "=" operator.

Your code has three braces missing. Arraylist have to declared like this

 ArrayList<class> list = new ArrayList<class>();

If you want an arraylist of integers

ArrayList<Integers> in = new ArrayList<Integers>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!