Printing string variable in Java - java

I'm getting some weird output when running (seemingly simple) code. Here's what I have:
import java.util.Scanner;
public class TestApplication {
public static void main(String[] args) {
System.out.println("Enter a password: ");
Scanner input = new Scanner(System.in);
input.next();
String s = input.toString();
System.out.println(s);
}
}
And the output I get after compiling successfully is:
Enter a password:
hello
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=5][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Which is sort of weird. What's happening and how do I print the value of s?

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,
Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);
Please read the tutorial on how to use it as it will explain all.
Edit
Please look here: Scanner tutorial
Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

You could also use BufferedReader:
import java.io.*;
public class TestApplication {
public static void main (String[] args) {
System.out.print("Enter a password: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String password = null;
try {
password = br.readLine();
} catch (IOException e) {
System.out.println("IO error trying to read your password!");
System.exit(1);
}
System.out.println("Successfully read your password.");
}
}

input.next();
String s = input.toString();
change it to
String s = input.next();
May be that's what you were trying to do.

This is more likely to get you what you want:
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);

If you have tried all the other answers, and it still hasn't work, you can try skipping a line:
Scanner scan = new Scanner(System.in);
scan.nextLine();
String s = scan.nextLine();
System.out.println("String is " + s);

Related

I want to take user input in string and write that string in a text file using java. But there is a problem

import java.io.*;
public class FileHandlingReadingWriting {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
FileWriter fWrite = new FileWriter("IOPinJava.txt");
String input = "";
System.out.println("Enter data to be entered in the string\n");
input = sc.next();
String i = input;
fWrite.write(i);
fWrite.flush();
fWrite.close();
}
}
when I execute this code and enter a string, only first word of the string gets written in the file. If the string is "This is a text", then only "This" gets written to the text file.
You aren't reading in the entire line with your scanner. Try input = sc.nextLine()

Compare input to a specific line saved in a text file JAVA

In order to validate a country entered by the user, I'm trying to have that country input compared to a list of countries stored in a text file. If the input matches a country stored in the text file, the validCountry would be set to 'true' and the program would be able to proceed.This is what I've got so far:
Scanner sc = new Scanner (System.in);
String country = "";
boolean validCountry = false;
while (!validCountry)
{
System.out.print("Country: ");
String countryIn = sc.next();
try{
Scanner scan = new Scanner(new File("countries.txt"));
while (scan.hasNext()) {
String line = scan.nextLine().toString();
if(line.contains(countryIn))
{
country = line;
validCountry = true;
}
}
}catch(Exception e)
{
System.out.print(e);
}
}
The above simply loops for me to re-input the country (implying that it is invalid).
This is what the countries.txt file looks like (obviously contains all the countries of the world not just the first few starting with 'A' :
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
Anguilla
...
I'm sure it's a very simple and minor error which I can't seem to find; but I've been trying to detect it for a while but to no avail. I've checked multiple other stackoverflow answers but they didn't seem to work either. I truly appreciate any form of help :)
Please let me know if my question needs further clarification.
I tested the code and it works for me.
I initialized your variable sc like this:
Scanner sc = new Scanner(System.in);
Note that it would be better to load the file outside the while loop (for better performance)
Assuming that in String countryIn = sc.next(); the sc is a scanner that use System.in, change the .next() into nextLine():
String countryIn = sc.nextLine();
then, you should also change if(line.contains(countryIn)) because it will return true even if the given line is a substring of a country (afg will be found in afghanistan even though afg is not in the country list. use equalsIgnoreCase instead:
if (line.equalsIgnoreCase(countryIn)) {
...
}
Try if this class works:
import java.util.Scanner;
import java.io.File;
public class Country {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String country = "";
boolean validCountry = false;
while (!validCountry)
{
System.out.print("Country: ");
String countryIn = sc.nextLine();
try{
Scanner scan = new Scanner(new File("countries.txt"));
while (scan.hasNext()) {
String line = scan.nextLine();
if(line.equalsIgnoreCase(countryIn))
{
country = line;
validCountry = true;
break;
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Problem solved, the countries.txt file I had was encoded in UNICODE. All I had to do was change it to ANSI.

Searching a list of names in a text file from user input

I'm currently in an Introductory Java class at University and I'm having a bit of trouble. Last semester we started with Python and I became very acquainted with it and I would say I am proficient now in writing Python; yet Java is another story. Things are alot different. Anyway, Here is my current assignment: I need to write a class to search through a text document (passed as an argument) for a name that is inputted by the user and output whether or not the name is in the list. The first line of the text document is the amount of names in the list.
The text document:
14
Christian
Vincent
Joseph
Usman
Andrew
James
Ali
Narain
Chengjun
Marvin
Frank
Jason
Reza
David
And my code:
import java.util.*;
import java.io.*;
public class DbLookup{
public static void main(String[]args) throws IOException{
File inputDataFile = new File(args[0]);
Scanner stdin = new Scanner(System.in);
Scanner inFile = new Scanner(inputDataFile);
int length = inFile.nextInt();
String names[] = new String[length];
for(int i=0;i<length;i++){
names[i] = inFile.nextLine();
}
System.out.println("Please enter a name that you would like to search for: ");
while(stdin.hasNext()){
System.out.println("Please enter a name that you would like to search for: ");
String input = stdin.next();
for(int i = 0;i<length;i++){
if(input.equalsIgnoreCase(names[i])){
System.out.println("We found "+names[i]+" in our database!");
break;
}else{
continue;
}
}
}
}
}
I am just not getting the output I am expecting and I cannot figure out why.
Try this
You should trim() your values as they have extra spaces
if(input.trim().equalsIgnoreCase(names[i].trim()))
I have run your example it runs perfectly after using trim(), you have missed to trim()
Create a seperate scanner class to read line by line.You can use BufferedReader also.
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String str= scanner.nextLine();
if(str.contains(name)) {
// Found the input word
System.out.println("I found " +name+ " in file " +file.getName());
break;
}
}
If you use Java 8:
String[] names;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
names = stream.skip(1).toArray(size -> new String[size]);
} catch (IOException e) {
e.printStackTrace();
}

unable to read file in java

I am trying to have user input an interger, based on the integer value, I am calling mix function to read in the file contents as code shows below. I am getting, this error:
Project2.java:43: variable urlScan might not have been initialized
while (urlScan.hasNext())
^
Project2.java:34: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
fileScan = new Scanner (new File("input.txt"));
^
Any ideas, what I might be doing wrong here?
import java.util.Scanner;
import java.io.*;
public class Project2
{
public static void main(String[] args)
{
System.out.println("Select an item from below: \n");
System.out.println("(1) Mix");
System.out.println("(2) Solve");
System.out.println("(3) Quit");
int input;
Scanner scan= new Scanner(System.in);
input = scan.nextInt();
System.out.println(input);
if(input==1) {
mix();
}
else{
System.out.println("this is exit");
}
}
public static void mix()
{
String url;
Scanner fileScan, urlScan;
fileScan = new Scanner (new File("input.txt"));
// Read and process each line of the file
while (fileScan.hasNext())
{
url = fileScan.nextLine();
System.out.println ("URL: " + url);
//urlScan = new Scanner (url);
//urlScan.useDelimiter("/");
// Print each part of the url
while (urlScan.hasNext())
System.out.println (" " + urlScan.next());
System.out.println();
}
}
}
The errors are pretty expressive.
Initialize your urlScan local variable(local variables don't get default values)
Wrap the fileScan = new Scanner (new File("input.txt")); around try/catch. or declare that your method might throw FileNotFoundException in your method signature. (new File(str) might throw FileNotFoundException which is a checked exception and compiler will force your handled it).
First, urlScan isn't initialized.
Second, you should surround fileScan = new Scanner (new File("input.txt")); with an try/catch for FileNotFoundException.
Local variables must be initialized before use, so uncomment this line:
urlScan = new Scanner (url);

Is a scan line escaping?

I've been doing a small project for class, it runs perfectly without problems but when pitted against the class's auto testers it gives back 2 No line found errors. Asking the course's staff they say it's probably because I'm trying to scan a line when none exist, but I tried printing all my scans and didn't discover anything like that.
That's all the scans I have in my code:
Scanner sc = new Scanner(System.in);
String sentence;
int choice;
System.out.println("Please enter a sentence:");
sentence = sc.nextLine();
printMenu(); // calls a function to print the menu.
// gets the require action
System.out.println("Choose option to execute:");
choice = sc.nextInt();
sc.nextLine();
(I tried with and without the last sc.nextLine)
static void replaceStr(String str)
{
String oldWord, newWord;
Scanner in = new Scanner(System.in);
// get the strings
System.out.println("String to replace: ");
oldWord = in.nextLine();
System.out.println("New String: ");
newWord = in.nextLine();
// replace
str = str.replace(oldWord, newWord);
System.out.println("The result is: " + str);
in.close();
}
static void removeNextChars(String str)
{
Scanner in = new Scanner(System.in);
String remStr; // to store the string to replace
String tmpStr = ""; //the string we are going to change.
int i; // to store the location of indexStr
// gets the index
System.out.println("Enter a string: ");
remStr = in.nextLine();
i=str.indexOf(remStr);
in.close(); // bye bye
if (i < 0)
{
System.out.println("The result is: "+str);
return;
}
// Build the new string without the unwanted chars.
/* code that builds new string */
str = tmpStr;
System.out.println("The result is: "+str);
}
Any idea how a line can leak here?
Here is the problem. You are using in.close(); at multiple places(last statement in replaceStr method and around the middle in removeNextChars method). When you close the scnaner using close() method, it closes your InputStream (System.in) as well. That InputStream can't be reopened with-in your program.
public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**
Any read attempts after the scanner close will result into exception NoSuchElementException.
Please close your scanner only once, when your program is done.
EDIT: Scanner Closing/usage:
In yout main function:
Scanner sc = new Scanner(System.in);
....
.....
replaceStr(Scanner sc, String str);
.....
....
removeNextChars(Scanner sc ,String str);
....
....
//In the end
sc.close();
static void replaceStr(Scanner in, String str){
//All the code without scanner instantiation and closing
...
}
static void removeNextChars(Scanner in, String str){
//All the code without scanner instantiation and closing
...
}
You should be all good.

Categories