Java how to take user input - java

Can anyone please tell me what is wrong with my code, i was just trying to add scanner in java and it was showing me an error on package line
import java.util.Scanner;
package scaner;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner (System.in);
System.out.println("enter your number");
int number;
number = in.nextInt();
System.out.println("your number is" + " " + number);
}
}

First of all, the main method must be inside a class.
Also, delete the "package scaner;" line.
If you want, you can also simplify the code:
import java.util.Scanner;
public class className{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
System.out.println("Your number is: " + number);
}
}

Related

How to take input as String with spaces in java using scanner

I need to read spaces (present before string and after String) given as input using Scanner
Note : if there is no spaces given in input it should not add space in output
Please find the below code:
package practise;
import java.util.Scanner;
public class scanccls {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String name= scan.nextLine();
name+=scan.nextLine();
scan.close();
System.out.println("Enter your name"+name);
}
}
I am expecting output like:
Input :Enter Your name:Chandu Aakash
Output:chandu Aakash
Input: Enter Your name: (Space..)Chandu Aakash(Space..)
Output: (space.. )chandu Aakash(Space..)
Your code work fine. I just add little modification:
package practise;
import java.util.Scanner;
public class scanccls {
public static void main(String[] args) {
System.out.println("Enter your name:");
Scanner scan = new Scanner(System.in);
String name="";
name+=scan.nextLine();
scan.close();
System.out.println("Your name is :"+name);
}
}
One can use the delimiter function to segregate your input as shown below.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
String input = scanner.next();
System.out.println(input);
scanner.close();
}
}
import java.util.*;
public class Str{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s=" ";
s= scan.nextLine();
s+=scan.nextLine();
scan.close();
System.out.println("String: "+s);
System.out.println("Double: "+d);
System.out.println("Int: "+i);
}
}
/#esprittn solution didn't work./
my solution:
while(scan.hasNext()){
name+=scan.nextLine();
}
I use this function below, to read from all user input format, text inclusive spaces, then parse to specific datatype after.
package practice;
import java.io.*;
public class readInputSample{
public static void main(String[] args) {
String strVal = getInput("Enter string value: "); // Direct as string
Integer intVal = Integer.parseInt(getInput("Enter integer value: "));
Double dblVal = Double.parseDouble(getInput("Enter double value: "));
Float fltVal = Float.parseFloat(getInput("Enter float value: "));
System.out.println("String value: " + strVal);
System.out.println("Integer value: " + intVal);
System.out.println("Double value: " + dblVal);
System.out.println("Float value: " + fltVal);
}
// Special Function to read all user input
private static String getInput(String prompt){
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try{
return stdin.readLine();
} catch (Exception e){
return "Error: " + e.getMessage();
}
}
}
I have done a few changes in your code, it will run just fine for this code
package practise;
import java.util.Scanner;
public class scanccls {
public static void main(String[] args) {
//// TODO Auto-generated method stub
System.out.println("Enter your name:");
Scanner scan = new Scanner(System.in);
String name="";
name+=scan.nextLine();
scan.close();
System.out.println("Your name is :"+name);
}
}
package practise;
import java.util.Scanner;
public class scanccls
{
public static void main(String[] args)
{
System.out.println("Enter your name:");
Scanner scan = new Scanner(System.in);
String name = "";
name += scan.nextLine();
// Can also be done like
// String name=scan.next();
// name+=scan.nextLine();
// They Both Work as same
System.out.println("Your name is :" + name);
}
}
package practise;
import java.util.Scanner;
public class scanccls {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String name= scan.nextLine();
scan.close();
System.out.println("Enter your name"+name);
}
}

How can I check if a file contains a certain number that the user has input? (java)

Hi I'm trying to write a program that will check a designated file for a number that a user has input, however if the number is not present in the file I want the program to loop back to the beginning, how could I do this?
Here is the mess I've made so far:
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
String keyWord = number, word;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(myScanner.nextLine().trim())) {
System.out.println("The number "+number+ " is there");
break;
} else {
// not found
}
} // main
} // class
all you need to do is take input from user and then check is it exist in file .you shouldn't use myScanner.nextLine().trim() inside while loop because then it waits to get user input every loop time .ones you get a number from user ,you should check it in the file .what you did is get user input and then again wait for user to input value again and again
fixed code
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
// //1. class
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine() ;
int lineNum = 0;
while(sc.hasNextLine()) {
word = sc.next();
if(word.equals(number.trim())) { //here was the problem
System.out.println("The number "+number+ " is there");
return;
} else {
}
}
System.out.println("not found"); // not found
}
the best approach
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine();
if(isFound(number)){
System.out.println("The number "+number+ " is there");
}else{
System.out.println("The number "+number+ " doesn't exist");
}
}
public static boolean isFound(String number) {
Scanner sc = new Scanner(Classtest2.class.getResourceAsStream("trombones.txt"));
String word="";
while (sc.hasNextLine()) {
word = sc.next();
if (word.equals(number.trim())) {
return true;
}
}
return false;
}
}
This works for me, hope is useful for you:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Classtest2 {
public static void main(String[] args) throws IOException {
File f = new File("trombones.txt");
f.createNewFile();
Scanner myScanner = new Scanner(System.in);
boolean numExiste = menu(new Scanner(f), myScanner);
while (!(numExiste)){
numExiste = menu(new Scanner(f), myScanner);
}
myScanner.close();
}
private static boolean menu(Scanner fileScanner, Scanner myScanner) throws FileNotFoundException{
String word = "";
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine().trim();
while(fileScanner.hasNextLine()){
word = fileScanner.nextLine();
if(word.trim().equals(number)){
System.out.println("The number "+number+ " is there");
return true;
}else{
//Not the number
}
}
System.out.println("The number "+ number+ " is not in the file\n\n");
return false;
}
} // main } // class

Prevent input error

import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
How do I loop a piece of code like the one above until an int is entered instead of giving an error when a non-int is entered?
The Scanner class has a lot of stuff built in so that you don't need to do try-catches unless you are explicitly looking to catch the errors.
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
This tries to run the scanner, if a input is one that is not expected it will simply restart. You can add a message to it, my code was for brevity.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}

problems importing scanner class

I am trying to execute the following code but keep getting this error:
Error: Main method not found in class ScannerDemo, please define the main method as:
public static void main(String[] args)
import java.util.Scanner;
class ScannerDemo
public class Main {
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String userName;
System.out.println("Enter a number");
username = sc.nextLine();
System.out.println("your number is" + username + "enter your next number");
username2 = sc.nextline();
System.out.println("your total is" + username2 );
}
}
I think I must be importing the Scanner class wrong, I have tried different methods but nothing has worked for me yet.
You have two class declarations in a row at the top! This is wrong. Your import is fine. Try:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
...
}
}
Your class definition is wrong. You are trying to define two classes, ScannerDemo and Main. Replace:
class ScannerDemo
public class Main
With just:
public class ScannerDemo
Also, in your main method, you should be referring to the userName variable, instead of username, and you are not defining username2. Note that Java identifiers are case sensitive:
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
String userName = sc.nextLine();
System.out.println("your number is" + username + "enter your next number");
String username2 = sc.nextline();
System.out.println("your total is" + username2 );
}
import java.util.Scanner;
public class ScannerDemo {
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String userName;
System.out.println("Enter a number");
username = sc.nextLine();
System.out.println("your number is" + username + "enter your next number");
username2 = sc.nextline();
System.out.println("your total is" + username2 );
}
}
import java.util.Scanner;
public class ScannerDemo {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
String userName;
System.out.println("Enter a number");
int userName = sc.nextInt();
System.out.println("your number is " + userName);
System.out.println("enter your next number");
int userName2 = sc.nextInt();
System.out.println("your total is " + (userName2 + userName));
}
}
Hope this helps
import java.util.Scanner;
public class ScannerDemo {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
String userName;
System.out.println("Enter a number");
int username = sc.nextInt();
System.out.println("your number is " + username);
System.out.println("enter your next number");
int username2 = sc.nextInt();
System.out.println("your total is " + (username2 + username));
}
}

How would I return x and y from different classes to main in Java?

How would I return my x and y variable into main in order to perform the addition?
Thanks in advance for the help!
import java.util.Scanner;
public class calling {
public static int x;
public static int y;
public static void num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
}
public static void num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
}
public static void main(String[] args){ **//place to return variables.**
num1();
num2();
System.out.print("The sum of the two numbers is: " + (x+y));
}
}
public static int getInput() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
public static void main(String[] args){
System.out.println("Please enter a number: ");
int x = getInput();
System.out.println("Please enter a second number: ");
int y = getInput();
int sum = x + y;
System.out.print("The sum of the two numbers is: " + sum);
}
or a more OO (Object Orientated) approach might look like
public class Calculator {
private Scanner scanner;
public Calculator() {
scanner = new Scanner (System.in);
}
public int getInput() {
return scanner.nextInt();
}
public int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Please enter a number: ");
int x = calculator.getInput();
System.out.println("Please enter a second number: ");
int y = calculator.getInput();
int sum = calculator.add(x, y);
System.out.print("The sum of the two numbers is: " + sum);
}
Note that Java naming conventions state classes should have uppercase first letters.
You shouldn't be using static data members or methods - those should only be used when the member of method applies to all instances of a class.
In this case the only static method should be main and that should only create a single instance of the current class. main should almost never do any real work - although in this trivial example I suppose an exception could be made.
You should ideally also only create a single Scanner object - the Scanner class is perfectly capable of reading a continuous stream of numbers without you needing to create a new one over and over for each number to be read.
In the code below I just create one and use it twice directly.
import java.util.Scanner;
public class calling {
public calling() {
Scanner scanner = new Scanner (System.in);
System.out.print("Please enter a number: ");
int x = scanner.nextInt();
System.out.print("Please enter a second number: ");
int y = scanner.nextInt();
System.out.println("The sum of the two numbers is: " + (x + y));
}
public static void main(String[] args) {
new calling();
}
}
Alternatively the scanner object could have been stored as a member variable, as in this example:
import java.util.Scanner;
public class calling {
private Scanner scanner = null;
private int getInt(String prompt) {
System.out.print(prompt);
return scanner.nextInt();
}
public calling() {
scanner = new Scanner(System.in)
int x = getInt("Please enter a number: ");
int y = getInt("Please enter a second number: ");
System.out.println("The sum of the two numbers is: " + (x + y));
}
public static void main(String[] args) {
new calling();
}
}
Simply change the return types of num1 and num2 to int and save the result of both functions in variables in main. Then perform your addition with the new variables, or just change the addition to (num1() + num2()).
In addition to that, grab a book and try to understand how to use functions because what you're asking is pretty basic.
if you are looking for a way to return the values to main function, read the code below
import java.util.Scanner;
public class test {
public static int x;
public static int y;
public static int num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
return y;
}
public static void main(String[] args){
int a = num1();
int b = num2();
System.out.print("The sum of the two numbers is: " + (a+b));
}
}

Categories

Resources