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

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);
}
}

Related

Java how to take user input

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);
}
}

How to get the result of another method from another method and print it

i want to get all the result from another method and compile it as one
package labexer1a;
import java.util.Scanner;
public class LabExer1A {
public static void main(String[] args) {
faveNumber();
faveCartChar();
mI();
fullName();
nickName();
}
public static void faveNumber() {
Scanner s = new Scanner(System.in);
System.out.print("Type your Number: ");
int faveNumber = s.nextInt();
}
public static void faveCartChar() {
Scanner s = new Scanner(System.in);
System.out.print("Type your favorite Cartoon or Anime Character: ");
String faveCartChar = s.next();
}
public static void mI() {
Scanner s = new Scanner(System.in);
System.out.print("Type your Middle Initial: ");
String mI = s.next();
}
public static void fullName() {
Scanner s = new Scanner(System.in);
System.out.print("Type your FullName: ");
String fullName = s.next();
}
public static void nickName() {
Scanner s = new Scanner(System.in);
System.out.print("Type your Nickname: ");
String nickName = s.next();
}
public static void result() {
System.out.print(faveNumber + "is my favorite number");
System.out.print("I love" + faveCartChar);
System.out.print("My name is" + fullName);
System.out.print("You can call me" + nickName);
}
}
You can change the fuctions return type from void to String or int for example and the return the result.
Example:
public static String fullName() {
Scanner s = new Scanner(System.in);
System.out.print("Type your FullName: ");
String fullName = s.next();
return fullName;
}
public static int faveNumber() {
Scanner s = new Scanner(System.in);
System.out.print("Type your Number: ");
int faveNumber = s.nextInt();
return faveNumber;
}
If you now want to acces the data just call the fuction and it will return it.
Example:
System.out.println(nickName() + " is my favorite number");
System.out.println("You can call me " + faveNumber());
And also I would recomend naming the functions more like getNickName so anyone can direclty see that it will return the nick name!

How do i convert my users input on my array to base 64?

CODE SAMPLE:
import java.util.Scanner;
import java.util.ArrayList;
public class BaseE {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter text: ");
while (sc.hasNextLine()) {
words.add(sc.nextLine());
if(sc.nextLine().equals("STOP"))
{
break;
}
}
System.out.println(words);
}
}
Use the build in Java method:
Base64.getEncoder().encodeToString(String yourString);
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
System.out.println("Enter text: ");
while (sc.hasNextLine()) {
String userInput = sc.nextLine();
words.add(userInput);
String encodedString = Base64.getEncoder().encodeToString(userInput.getBytes());
System.out.println("User Input encoded: " + encodedString);
if (userInput.equals("STOP")) {
break;
}
}
System.out.println(words);
}
https://www.baeldung.com/java-base64-encode-and-decode
Note: This is not an encryption in any way but just an encoding and should not be used at all for security purposes!

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

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));
}
}

Categories

Resources