Scanners method "nextLine" doesn`t allow to input line - java.util.scanner

import java.io.IOException;
import java.util.Scanner;
public class MainTraining {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int countOfStrangers = scanner.nextInt();
String[] name = new String[countOfStrangers];
System.out.println(scanner.nextLine());
}
}
It will output nothing.
Why?
that is only first part of my programm, so that separately this code has no sense

As i undersood, there are some troubles if you use nextLine after nextInt. To solve this problem you can read int with nextLine and after that parse it to int. Also you can create two scanners: one for ints and one for Strings
Full answer is here: Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Related

How do you call a variable from another class's methods in java?

I'm currently trying to print a variable from one class in another class.
import java.util.HashMap;
import java.util.Random;
class Word{
Random r = new Random();
int low = 0;
int high = 25;
int result = r.nextInt(high-low) + low;
String word;
public void Mapski(){
HashMap<Integer, String> map = new HashMap<>();
map.put(0,"apple");
map.put(1,"banana");
map.put(2,"cantaloupe");
map.put(3,"durian");
map.put(4,"elderberry");
map.put(5,"fig");
map.put(6,"grapefruit");
map.put(7,"hashbrown");
map.put(8,"ice cream");
map.put(9,"jackfruit");
map.put(10,"kale");
map.put(11,"lettuce");
map.put(12,"mango");
map.put(13,"nachos");
map.put(14,"oatmeal");
map.put(15,"plum");
map.put(16,"quesadilla");
map.put(17,"raspberry");
map.put(18,"strawberry");
map.put(19,"tangelo");
map.put(20,"udon noodles");
map.put(21,"venison");
map.put(22,"watermelon");
map.put(23,"xigua");
map.put(24,"yogurt");
map.put(25,"zucchini");
String word = map.get(result);
this.word = word;
}
public void setWord(String word){
this.word = word;
}
public String getWord(){
return word;
}
}
I've tried using setters and getters but I just keep getting back that word is null. I know that the word variable in my Mapski() method is correct because when I add System.out.println(word) to the method Mapski(), it prints a random food from my list when I call the method in my main class with word.Mapski() after creating Word word = new Word();.
How can I make it so that when I'm in my main class I can call Mapski()'s word from class World with a food as the value instead of null? All help is appreciated. Thank you!

Java: input from Scanner behaves weirdly

Just for testing, I have written this very short program:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
if (input == "y" ) {
System.out.println("Test");
}
}
}
When I enter y, it does not print anything and just normally finishes with exit code 0.
Is this just the case on my machine? If so, why might this be the case?
Or am I making a mistake here? If so, what do I need to do to fix it?
Thank you very much in advance.
Your comparison of strings is where the issue is. Use input.equals("y") instead. See here for details

The correct way to use FileVisitor in java

I am trying to step through an entire path and its single layer of sub directories. For each file, I need to read five data fields and output them to a delimited text file. I'm able to read from a single text file and validate my output on screen; after that I'm stuck. I cannot seem to to find the right parameters for FileVisit. Some specific questions are comments in my code posted below. And although I'm no nearly that far yes, I'd like to get some idea for writing to an output file, namely whether the place I wish to put it is the most logical one.
I've reviewed the https://stackoverflow.com/questions/9913/java-file-io-compendium and JavaDocs' info on the File Visitor
http://docs.oracle.com/javase/7/docs/api/index.html?java/nio/file/FileVisitor.html .
However, I'm still not able to get FileVisitor working properly.
#Bohemian suggested changing interface to class which I've done.
import java.nio.files.*;
public class FileVisitor<T>
{
Path startPath = Paths.get("\\CallGuidesTXT\\");
Files.walkFileTree(startPath, new SimpleFileVisitor(startPath))
\\ ^^^^^^
\\ errors out, <identifier expected>
{
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.list(file);
return FileVisitResult.CONTINUE;
}
// do my file manipulations here, then write the delimited line
// of text to a CSV fle...is this the most appropriate place for that
// operation in this sample?
}
}
SSCCE below...but comments in the version above point to specific questions I'm having.
import java.nio.*;
import java.util.*;
public class FileVisitor<T>
{
Path startPath = Paths.get("\\CallGuidesTXT\\");
}
Files.walkFileTree(startPath, new SimpleFileVisitor(startPath) {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.list(file);
return FileVisitResult.CONTINUE;
}
});
I'm a little rusty in Java but here's a rough idea of where I think you're going:
import java.nio.files.*;
public class MyDirectoryInspector extends Object
{
public static void main(String[] args) {
Path startPath = Paths.get("\\CallGuidesTXT\\");
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
String firstLine = Files.newBufferedReader(file, Charset.defaultCharset()).readLine();
System.out.println(firstLine);
return FileVisitResult.CONTINUE;
}
}); // <- you were missing a terminating ");"
}
}
That should walk through the directories and print the first line of each file to std out. I haven't touched Java since 1.6 so the JDK7 stuff is a little new to me too. I think you are getting confused as to what's a class and what's an interface. In my example we start with a basic class called MyDirectoryInspector to avoid confusion. It's enough to give us a program entry point, the main method where we start the inspection. The call to Files.walkFileTree takes 2 parameters, a start path and a file visitor which I have inlined. (I think the inlining can be confusing to some people if you're not used to this style.) This is a way of defining the actual class right in the place where you wish to use it. You could have also defined the SimpleFileVisitor separately and just instantiated it for your call as follows:
import java.nio.files.*;
public class MyDirectoryInspector extends Object
{
public static void main(String[] args) {
Path startPath = Paths.get("\\CallGuidesTXT\\");
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>());
}
}
public class SimpleFileVisitor<Path>()) {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
String firstLine = Files.newBufferedReader(file, Charset.defaultCharset()).readLine();
System.out.println(firstLine);
return FileVisitResult.CONTINUE;
}
}
It may make more sense, if you are just getting started, to keep things all separated. Define your classes without inlineing, take it one step at a time and make sure you understand each piece in isolation. My 2nd example gives you 2 individual pieces, a custom file visitor that can be used to print the 1st line of each file it visits and a program that uses it with the JDK Files class. Now let's look at another approach that omits the syntax:
import java.nio.files.*;
public class MyDirectoryInspector extends Object
{
public static void main(String[] args) {
Path startPath = Paths.get("\\CallGuidesTXT\\");
Files.walkFileTree(startPath, new SimpleFileVisitor());
}
}
public class SimpleFileVisitor()) {
#Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
throws IOException
{
String firstLine = Files.newBufferedReader((Path)file, Charset.defaultCharset()).readLine();
System.out.println(firstLine);
return FileVisitResult.CONTINUE;
}
}
With the generics left off you have to declare file parameter as an Object type and cast it later when you choose to use it. In general, you don't want to replace an interface definition with a class definition or confuse the two as they are used for entirely different purposes.
Java interface can not have any implementations (ie code) - only method signatures.
Try changing interface to class:
public class FileVisitor<T> {
...
Now to answer your revised post...
You have a bracket in the wrong place:
Files.walkFileTree(startPath, new SimpleFileVisitor(startPath) {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Files.list(file);
return FileVisitResult.CONTINUE;
}
});
I moved the bracket after new SimpleFileVisitor(startPath) to enclose the visitFile method. What you have here is an anonymous class - that's where you provide an implementation "on the fly".

Special character escaping

All groovy special character #{\'}${"}/', needs to be replaced by \ in front in a groovy string dynamically
input : anish$spe{cial
output : anish\$spe\{cial
input : anish}stack{overflow'
output : anish\}stack\{overflow\'
I have written a sample program in Java, that i want in groovier way
import java.util.regex.*;
import java.io.*;
/**
*
* #author anish
*
*/
public class EscapeSpecialChar {
public static void main(String[] args) throws IOException {
inputString();
}
private static void inputString() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter string to find special characters: ");
String string = in.readLine();
// Escape the pattern
string = escapeRE(string);
System.out.println("output: -- " + string);
}
// Returns a pattern where all punctuation characters are escaped.
static Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
public static String escapeRE(String str) {
return escaper.matcher(str).replaceAll("\\\\$1");
}
}
Enter string to find special characters: $Anish(Stack%1231+#$124{}
output: -- \$Anish\(Stack\%1231\+\#\$124\{\}
This does what your Java code does:
System.console().with {
def inStr = readLine 'Enter string to find special characters: '
def outStr = inStr.replaceAll( /([^a-zA-Z0-9])/, '\\\\$1' )
println "Output: $outStr"
}
I am still dubious that what I think you are doing is a good idea though... ;-)

Can extension methods modify extended class values?

I was just trying to code the following extension method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _4Testing
{
static class ExtensionMethods
{
public static void AssignMe(this int me, int value)
{
me = value;
}
}
}
But it is not working, i mean, can I use an extension method to alter values from extended classes? I don't want to change void return type to int, just changing extended class value. Thanks in advance
Your example uses int, which is a value type. Classes are reference types and behaves a bit differently in this case.
While you could make a method that takes another reference like AssignMe(this MyClass me, MyClass other), the method would work on a copy of the reference, so if you assign other to me it would only affect the local copy of the reference.
Also, keep in mind that extension methods are just static methods in disguise. I.e. they can only access public members of the extended types.
public sealed class Foo {
public int PublicValue;
private int PrivateValue;
}
public static class FooExtensions {
public static void Bar(this Foo f) {
f.PublicValue = 42;
// Doesn't compile as the extension method doesn't have access to Foo's internals
f.PrivateValue = 42;
}
}
// a work around for extension to a wrapping reference type is following ....
using System;
static class Program
{
static void Main(string[] args)
{
var me = new Integer { value = 5 };
int y = 2;
me.AssignMe(y);
Console.WriteLine(me); // prints 2
Console.ReadLine();
}
public static void AssignMe(this Integer me, int value)
{
me.value = value;
}
}
class Integer
{
public int value { get; set; }
public Integer()
{
value = 0;
}
public override string ToString()
{
return value.ToString();
}
}
Ramon what you really need is a ref modifier on the first (i.e. int me ) parameter of the extension method, but C# does not allow ref modifier on parameters having 'this' modifiers.
[Update]
No workaround should be possible for your particular case of an extension method for a value type. Here is the "reductio ad absurdum" that you are asking for if you are allowed to do what you want to do; consider the C# statement:
5.AssignMe(10);
... now what on earth do you think its suppose to do ? Are you trying to assign 10 to 5 ??
Operator overloading cannot help you either.
This is an old post but I ran into a similar problem trying to implement an extender for the String class.
My original code was this:
public static void Revert(this string s)
{
char[] xc = s.ToCharArray();
s = new string(xc.Reverse());
}
By using the new keyword I am creating a new object and since s is not passed by reference it will not be modified.
I changed it to the following which provides a solution to Ramon's problem:
public static string Reverse(this string s)
{
char[] xc = s.ToCharArray();
Array.Reverse(xc);
return new string(xc);
}
In which case the calling code will be:
s = s.Reverse();
To manipulate integers you can do something like:
public static int Increment(this int i)
{
return i++;
}
i = i.Increment();

Resources