-2

So I am doing this thing that asks you to enter how many numbers you want and then ask you to enter one more number. The code is supposed to check if that number was one of the numbers first submitted, if it was, a message will pop up saying it was and then exit the program. Can someone help me how to use the scanner correctly, or if that isn't the issue in my code, help me correct my code?

  package individuellt_val;

    import java.util.Scanner;
    import javax.swing.JOptionPane;


    public class InlKap9test2 {

        public static void main(String[] args) {
            String s = JOptionPane.showInputDialog("Ange några tal");
            Scanner sc = new Scanner(s);
            int x = 0, y = 0;
            boolean fortsätt = true;

            while(fortsätt){
                while(sc.hasNextInt()){
                    x = sc.nextInt();

                String s2 = JOptionPane.showInputDialog("Ange ett tal till");
                Scanner sc2 = new Scanner(s2);
                while(sc2.hasNextInt())
                y = sc.nextInt();

                if(x == y){
                    JOptionPane.showMessageDialog(null, "Detta tal fanns bland de första!");
                    fortsätt = false;
                }
               } 
            }
    System.exit(0);
        }

    }
  • 1
    1) *"I can't seem to get it working though."* Can you manage to ask a question? 2) Please use code formatting for code and code snippets, structured documents like HTML/XML or input/output. To do that, select the text and click the `{}` button at the top of the message posting/editing form. – Andrew Thompson Nov 25 '17 at 19:42
  • use `new Scanner(System.in)` – Damien Flury Nov 25 '17 at 19:43

2 Answers2

1

Explanation

new Scanner(s) is incorrect. s is a string, while a Scanner needs a PrintStream. You probably want it from the keyboard, aka System.in.

How to fix

Change Scanner sc = new Scanner(s); to Scanner sc = new Scanner(System.in).

IMustBeSomeone
  • 422
  • 2
  • 14
0

String s = JOptionPane.showInputDialog("Ange några tal"); Scanner sc = new Scanner(s)

Here you cant pass reference in Scanner. Use new Scanner(System.in);

It will take input from console i.e keyboard now.

Neeraj Yadav
  • 422
  • 6
  • 13