Scanner in new scanner system in ошибка

This is my Code

public class Workshop3
{
    public static void main (String [] args)
    {
        System.out.println ("please enter radius of circle");
        double radius;
        Scanner keyboard = new Scanner (System.in);
        keyboard.nextDouble (radius);
    }
}

The error I recieve is

cannot find symbol — class scanner

on the line

Scanner keyboard = new Scanner (System.in);

gunr2171's user avatar

gunr2171

16k25 gold badges61 silver badges87 bronze badges

asked May 11, 2011 at 3:56

James Blundell's user avatar

0

As the OP is a new beginner to programming, I would like to explain more.

You wil need this line on the top of your code in order to compile:

import java.util.Scanner;

This kind of import statement is very important. They tell the compile of which kind of Scanner you are about to use, because the Scanner here is undefined by anyone.

After a import statement, you can use the class Scanner directly and the compiler will know about it.

Also, you can do this without using the import statement, although I don’t recommend:

java.util.Scanner scanner = new java.util.Scanner(System.in);

In this case, you just directly tell the compiler about which Scanner you mean to use.

answered May 11, 2011 at 4:08

lamwaiman1988's user avatar

lamwaiman1988lamwaiman1988

3,71715 gold badges55 silver badges87 bronze badges

0

You have to import java.util.Scanner at first line in the code

import java.util.Scanner;

answered May 11, 2011 at 4:00

Eng.Fouad's user avatar

Eng.FouadEng.Fouad

115k70 gold badges312 silver badges416 bronze badges

0

You need to include the line import java.util.Scanner; in your source file somewhere, preferably at the top.

micsthepick's user avatar

answered May 11, 2011 at 3:58

dlev's user avatar

dlevdlev

48k5 gold badges125 silver badges132 bronze badges

You can resolve this error by importing the java.util.* package — you can do this by adding following line of code to top of your program (with your other import statements):

import java.util.*;

micsthepick's user avatar

answered Jul 15, 2016 at 9:25

Nimesh's user avatar

sometimes this can occur during when we try to print string from the user so before we print we have to use

eg:
Scanner scan=new Scanner (System.in);

scan.nextLine();
// if we have output before this string from the user like integer or other dat type in the buffer there is /n (new line) which skip our string so we use this line to print our string

String s=scan.nextLine();

System.out.println(s);

answered May 7, 2020 at 18:01

fasika's user avatar

Please add the following line on top of your code

*import java.util.*;*

This should resolve the issue

Jim Simson's user avatar

Jim Simson

2,7643 gold badges22 silver badges30 bronze badges

answered Sep 5, 2020 at 12:58

Maitreya Dwivedi's user avatar

Add import java.util.Scanner; at the very top of your code. Worked for me.

answered Dec 15, 2020 at 18:51

Audrey Mengue's user avatar

Возможно ошибка

com/javarush/task/task03/task0318/Solution.java:12: error: cannot find symbol
Scanner scanner = new Scanner(System.in);
^
symbol: class Scanner
location: class com.javarush.task.task03.task0318.Solution
com/javarush/task/task03/task0318/Solution.java:12: error: cannot find symbol
Scanner scanner = new Scanner(System.in);
^
symbol: class Scanner
location: class com.javarush.task.task03.task0318.Solution

Вот ошибка которую выдаёт компилятор.Подскажите какой import нужно добавить что бы компилятор мог закомпилировать или может у меня тут ошибка буду рад если исправите меня

package com.javarush.task.task03.task0318;

/*
План по захвату мира
*/

import java.io.*;

public class Solution {
public static void main(String[] args) throws Exception {

Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int age = scanner.nextInt();
System.out.println(name + «захватим мир через » + age+ » лет. Му-ха-ха!»);
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

Java scanner.nextLine() Method Call Gets Skipped Error [SOLVED]

There’s a common error that tends to stump new Java programmers. It happens when you group together a bunch of input prompts and one of the scanner.nextLine() method calls gets skipped – without any signs of failure or error.

Take a look at the following code snippet, for example:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("What's your name? ");
        String name = scanner.nextLine();

        System.out.printf("So %s. How old are you? ", name);
        int age = scanner.nextInt();

        System.out.printf("Cool! %d is a good age to start programming. nWhat language would you prefer? ", age);
        String language = scanner.nextLine();

        System.out.printf("Ah! %s is a solid programming language.", language);

        scanner.close();

    }

}

The first scanner.nextLine() call prompts the user for their name. Then the scanner.nextInt() call prompts the user for their age. The last scanner.nextLine() call prompts the user for their preferred programming language. Finally, you close the scanner object and call it a day.

It’s very basic Java code involving a scanner object to take input from the user, right? Let’s try to run the program and see what happens.

If you did run the program, you may have noticed that the program asks for the name, then the age, and then skips the last prompt for the preferred programming language and abruptly ends. That’s what we’re going to solve today.

Why Does the scanner.nextLine() Call Get Skipped After the scanner.nextInt() Call?

This behavior is not exclusive to just the scanner.nextInt() method. If you call the scanner.nextLine() method after any of the other scanner.nextWhatever() methods, the program will skip that call.

Well, this has to do with how the two methods work. The first scanner.nextLine() prompts the user for their name.

When the user inputs the name and presses enter, scanner.nextLine() consumes the name and the enter or the newline character at the end.

Which means the input buffer is now empty. Then the scanner.nextInt() prompts the user for their age. The user inputs the age and presses enter.

Unlike the scanner.nextLine() method, the scanner.nextInt() method only consumes the integer part and leaves the enter or newline character in the input buffer.

When the third scanner.nextLine() is called, it finds the enter or newline character still existing in the input buffer, mistakes it as the input from the user, and returns immediately.

As you can see, like many real life problems, this is caused by misunderstanding between the user and the programmer.

There are two ways to solve this problem. You can either consume the newline character after the scanner.nextInt() call takes place, or you can take all the inputs as strings and parse them to the correct data type later on.

How to Clear the Input Buffer After the scanner.nextInt() Call Takes Place

It’s easier than you think. All you have to do is put an additional scanner.nextLine() call after the scanner.nextInt() call takes place.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("What's your name? ");
        String name = scanner.nextLine();

        System.out.printf("So %s. How old are you? ", name);
        int age = scanner.nextInt();

        // consumes the dangling newline character
        scanner.nextLine();

        System.out.printf("Cool! %d is a good age to start programming. nWhat language would you prefer? ", age);
        String language = scanner.nextLine();

        System.out.printf("Ah! %s is a solid programming language.", language);

        scanner.close();

    }

}

Although this solution works, you’ll have to add additional scanner.nextLine() calls whenever you call any of the other methods. It’s fine for smaller programs but in larger ones, this can get very ugly very quick.

How to Parse Inputs Taken Using the scanner.nextLine() Method

All the wrapper classes in Java contain methods for parsing string values. For example, the Integer.parseInt() method can parse an integer value from a given string.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("What's your name? ");
        String name = scanner.nextLine();

        System.out.printf("So %s. How old are you? ", name);
        // parse the integer from the string
        int age = Integer.parseInt(scanner.nextLine());

        System.out.printf("Cool! %d is a good age to start programming. nWhat language would you prefer? ", age);
        String language = scanner.nextLine();

        System.out.printf("Ah! %s is a solid programming language.", language);

        scanner.close();

    }

}

This is a cleaner way of mixing multiple types of input prompts in Java. As long as you’re being careful about what the user is putting in, the parsing should be alright.

Conclusion

I’d like to thank you from the bottom of my heart for taking interest in my writing. I hope it has helped you in one way or another.

If it did, feel free to share with your connections. If you want to get in touch, I’m available on Twitter and LinkedIn.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

При вводе нескольких значений с консоли выходит данная ошибка.

import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
       Scanner scanner = new Scanner(System.in);
       int c = Integer.parseInt(scanner.nextLine());
       int b = Integer.parseInt(scanner.nextLine());
        System.out.println(c+b);
    }
}

1
1
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:678)
    at java.base/java.lang.Integer.parseInt(Integer.java:784)
    at Main.main(Main.java:9)


  • Вопрос задан

    более года назад

  • 287 просмотров

Добрый день.
Проблема заключается в следующем:
Вы сперва с вводите первое число и нажимаете на перевод строки (Enter).
Когда вы нажимаете на перевод строки срабатывает ввод числа b, который и принимает собственно говоря знак перевода строки и так как он не является числом, то выбрасывается исключение.
Чтобы этого не было:

int c = Integer.parseInt(scanner.nextLine());
Scanner.nextline();
int b = Integer.parseInt(scanner.nextLine());

И как отметил коллега — используйте nextInt() вместо nextLine()
Вот, аналогичная проблема — https://stackoverflow.com/questions/13102045/scann…

Пригласить эксперта

Если используете класс Scanner, то для считывания чисел из потока удобнее использовать пару методов hasNextInt и nextInt.

Возможно в вашем случае первый вызов scanner.nextLine() вычитал весь поток и при втором вызове вернулась пустая строка.

В ошибке все написано. Ты пытаешься пустую строку привести к числу


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

Scanner is a utility class that provides methods to read command-line input. It is a very useful class, but you need to be aware of its unexpected behavior while reading numeric inputs.

Consider the following example.

try (Scanner in = new Scanner(System.in)) {
	System.out.print("Enter Item ID: ");
	String itemID = in.nextLine();
	System.out.print("Enter item price: ");
	double price = in.nextDouble();
	System.out.println("Price of item " + itemID + " is $" + price);
} catch (Exception e) {
	e.printStackTrace();
}

As expected the output from this code will look something like:

Enter Item ID: XY1234
Enter item price: 99.99
Price of item XY1234 is $99.99

Everything worked as expected. The program prompted the user to enter an item ID and price. It read the values and then displayed them on console correctly.  Now, let’s see what happens if we ask the user to enter the price first followed by item ID.

try (Scanner in = new Scanner(System.in)) {
	System.out.print("Enter item price: ");
	double price = in.nextDouble();
	System.out.print("Enter Item ID: ");
	String itemID = in.nextLine();
	System.out.println("Price of item " + itemID + " is $ " + price);
} catch (Exception e) {
			e.printStackTrace();
}

This version resulted in a bizarre output.

Enter item price: 85.79
Enter Item ID: Price of item  is $ 85.79

What happened here? The program didn’t wait for the user to enter item ID. After prompting the user to enter the item ID, it right away printed the final message with a blank item ID.

Understanding Scanner.getDouble() and Scanner.getInt()

What caused this behavior? To solve this mystery we have to understand how Scanner.getDouble() or Scanner.getInt() methods work.  Basically, Scanner’s get methods read the input character by character instead of reading the entire line at once. getDouble and getInt methods read input until they reach a non-numeric character. In this example, the user entered 99.99 and then hit enter (“n“). So the character sequence would be 99.99n.  The method getDouble() reads the characters up to the last “9”. Since the next character is a non-numeric value (n), the method stopped and returned the value 85.79 to be saved in the price variable. That left n character in the buffer. Next, the program called nextLine() method. This method reads the input until it reaches the newline character (n). Since the input stream had the n character from the last input, the method reads it and returns immediately without allowing the user to input the ID.

To overcome this issue you have two options.

  1. Always call nextLine() method after calling nextInt() or nextDouble() method to consume line feed.
  2. Always read command line input using nextLine() method and then converts numeric values from String to appropriate numeric type.
try (Scanner in = new Scanner(System.in)) {
			System.out.print("Enter item price: ");
			double price = in.nextDouble();
			in.nextLine();
			System.out.print("Enter Item ID: ");
			String itemID = in.nextLine();
			System.out.println("Price of item " + itemID + " is $ " + price);
		} catch (Exception e) {
			e.printStackTrace();
		}

Which gives correct results.

Enter item price: 85.79
Enter Item ID: XY1234
Price of item XY1234 is $ 85.79
try (Scanner in = new Scanner(System.in)) {
			System.out.print("Enter item price: ");
			String priceStr = in.nextLine();
			double price = Double.valueOf(priceStr);
			System.out.print("Enter Item ID: ");
			String itemID = in.nextLine();
			System.out.println("Price of item " + itemID + " is $ " + price);
		} catch (Exception e) {
			e.printStackTrace();
		}
Enter item price: 85.99
Enter Item ID: AB2314
Price of item AB2314 is $ 85.99

Personally, I prefer the first approach.

Понравилась статья? Поделить с друзьями:
  • Scanmaster elm как сбросить ошибку
  • Scania ошибка неисправность коробки передач
  • Scanf в с при ошибке
  • Scan windows 10 на ошибки
  • Scad ошибка при разложении матрицы 99