VIkmaestre VIkmaestre - 17 days ago 5
Java Question

Java: Scanning string, then search for integer

I am programing in java and have also very little programming experience.

I am trying to make a program there you first write in a number of integers in a scanner. In the next window you are supposed to write only one integer and that integer the program will search for and tell if it is or isn't in the "Scanner numbers"

My problem is that when i for example write

1 2 3
and in the next window write
it doesn't recognize there is a
in the scanner but if I instead write a
it works nicely.
Heres the code:

public class Inlämningsuppgift_kap9 {

public static void main(String[] args) {
String s1 = JOptionPane.showInputDialog("Write any number of integers!");
Scanner sc1 = new Scanner(s1);

String s2 = JOptionPane.showInputDialog(
"Chose a integer that the program will search for!"
int a = Integer.parseInt(s2);

if(a == sc1.nextInt()){
JOptionPane.showMessageDialog(null, "The integer can be found");
else {
JOptionPane.showMessageDialog(null, "The integer cannot be found");

Thanks for any help!


Not going to do your homework for you, but a hint there: it is not a good idea to mix Swing UIs and a scanner that reads from stdin.

In other words: either use a graphical UI for all input/output; or just read/write from/to stdin (using out.println and that scanner code).

And then: assuming that the user first enters a string such as "1 2 3 4 5"; you need some further processing. You have to split that string (for example on spaces); and then turn each of that substrings ... into a real number. As your next step is to ask the user to input a number. And when you want to know if one number is in a list of other numbers, then you need to turn your initial string into that list of numbers!

So, you want to study javadoc for: