auto closable not working with Scanner - java.util.scanner

package org.test;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegTest {
public static void main(String[] args) throws InterruptedException {
String str = readLine("Enter String :");
String patternString = readLine("Enter pattern to search :");
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
System.out.print("match positions: "); // matches positions
while(matcher.find()) {
System.out.print(matcher.start() + " ");
}
System.out.println("");
}
static String readLine(String message){
String strLine;
try (Scanner in = new Scanner(System.in)) {
System.out.println(message);
strLine= in.nextLine();
}
return strLine;
}
}
Did not work.
Output is :
Enter String :
wewew
Enter pattern to search :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at org.test.RegTest.readLine(RegTest.java:39)
at org.test.RegTest.main(RegTest.java:22)

When the try-with-resources (autoclosable) closes the scanner it also closes the inputstream making it unavailable for use in the future.
As System.in is a global inputstream it means the second scanner can't read any thing from the inputstream because it has been closed and it throws the exception.
I would change the code to reuse the sanner for both reads.
public static void main(String[] args) throws InterruptedException {
try (Scanner in = new Scanner(System.in)) {
String str = readLine(in, "Enter String :");
String patternString = readLine(in, "Enter pattern to search :");
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
System.out.print("match positions: "); // matches positions
while (matcher.find()) {
System.out.print(matcher.start() + " ");
}
System.out.println("");
}
}
static String readLine(Scanner in, String message) {
String strLine;
System.out.println(message);
strLine = in.nextLine();
return strLine;
}

Related

can anyone explain this error and also about this case too like why I cant equivalate that two values?

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(remove(str));
}
static String remove(String str)
{
int start=0;
if(str.charAt(0)!=str.charAt(1)){
return str;
}
if(str.charAt(0)=str.charAt(1)){
str=str.substring(start+1,str.length());
remove(str);
}
}
}
/Root/src/Main.java:22: error: unexpected type
if(str.charAt(0)=str.charAt(1)){
^
required: variable
found: value
1 error

Using Scanner to take input from two objects of the same class

I have a problem with functionality of my simple program I am making at the moment. I am trying to create two objects, each of them is asking user to provide a name and then choose from few options, by using Scanner. First object, monster of class createMonster, is asking user to provide information through Scanner. However, while creating second object monster2 of class createMonster, program does not asking for user input.
Do I need to do some changes in my class CreateScanner or is it a bigger problem?
public class MainClass {
public static void main(String[] args) {
RandomMonsterGenerator monster = new RandomMonsterGenerator();
monster.createMonster();
RandomMonsterGenerator monster2 = new RandomMonsterGenerator();
monster2.createMonster();
}
}
RandomMonsterGenerator code:
public class RandomMonsterGenerator {
// Objects
Attributes attr = new Attributes();
CreateScanner createScanner = new CreateScanner();
// Variables
String monsterName;
String attributesValues;
int choice;
// Main method for generating monster
public void createMonster() {
attr.generateAttributes();
generateName();
chooseClass();
System.out.println("Generating random stats:");
attributesValues = attr.toString();
System.out.println(attributesValues);
createScanner.closeScanner();
}
// Generating monster name
private void generateName() {
System.out.println("Name your monster: ");
monsterName = createScanner.stringInput();
System.out.println("Name of the monster: " + monsterName);
}
// Choosing a class
private void chooseClass() {
System.out.println("Class descriptions: ");
System.out.println("Warrior has +2 to Strength and +2 to Condititon.");
System.out.println("Thief has +2 to Dexterity and +2 to Charisma.");
System.out.println("Mage has +2 to Intelligence and +2 to Wisdom.");
System.out.println("**************************************************");
System.out.println("Choose your class from following options: ");
System.out.println("Warrior, press '1'");
System.out.println("Thief, press '2'");
System.out.println("Mage, press '3'");
choice = createScanner.intInput();
switch(choice) {
case 1:
Warrior warrior = new Warrior(attr);
System.out.println(monsterName + " is a warrior.");
break;
case 2:
Thief thief = new Thief(attr);
System.out.println(monsterName + " is a thief.");
break;
case 3:
Mage mage = new Mage(attr);
System.out.println(monsterName + " is a mage.");
break;
default:
System.out.println("No option choosen.");
break;
}
}
}
CreateScanner code:
import java.util.Scanner;
public class CreateScanner {
Scanner sc = new Scanner(System.in);
public String stringInput() {
String input = "";
if (sc.hasNextLine()) {
input = sc.nextLine();
}
return input;
}
public int intInput() {
int input2 = 0;
if (sc.hasNextLine()) {
input2 = sc.nextInt();
}
return input2;
}
public void closeScanner() {
sc.close();
}
}
Two things.
First, don't close the scanner until you're done with it. This closes the System.in
as well and as soon as you do that you won't be getting anymore input. This is why it just skips over the second RandomMonsterGenerator input.
Second, only create one Scanner and pass it to your RandomMonsterGenerator as an argument. This keeps things simple.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
RandomMonsterGenerator monster = new RandomMonsterGenerator(scanner);
RandomMonsterGenerator monster2 = new RandomMonsterGenerator(scanner);
}

StackOverFlow - Exception? I can't found the reason :-(

I'm going to write a programm that can save a name and a birthday-date. After closing the programm the data shouldn't be lost. If you open the programm, you are able to add an additional user to the according users. Unfortunately I'm always get a stackoverflow - exception and i didn't found the mistake.
<pre> package geburtstagstool;
import java.io.*;
public class GeburtstagsTool
{
public static void main (String[]args) throws Exception
{
Eintrag eintrag = new Eintrag ("Miller","000000");
}
}
class Eintrag implements Serializable
{
Eintrag [] eintrag = new Eintrag [50];
public String name;
public String gebDatum;
int i=0;
public Eintrag (String name, String gebDatum)
{
eintrag[i] = new Eintrag (name,gebDatum);
++i;
}
public void testSchreiben () throws Exception
{
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("eintrag.dat"));
oos.writeObject(eintrag);
oos.close();
}
public static Eintrag testLesen() throws IOException, ClassNotFoundException
{
ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("eintrag.dat"));
Eintrag eint = (Eintrag) ois.readObject();
ois.close();
return eint;
}
}
<code>
Thanks for your help.
Here is a fully working solution. This should get you started. Good luck.
GeburtstagsTool class:
public class GeburtstagsTool {
List<Eintrag> eintragList;
public static void main (String[] args) throws IOException, ClassNotFoundException
{
GeburtstagsTool geburtstagsTool = new GeburtstagsTool();
geburtstagsTool.loadEintrag();
System.out.println("What's already in the list: \n" + geburtstagsTool.eintragList);
Eintrag eintrag = new Eintrag("Peyton Manning", "03/24/1976");
geburtstagsTool.eintragList.add(eintrag);
geburtstagsTool.writeEintrag();
}
public void loadEintrag() {}
{
ObjectInputStream ois = null;
try
{
ois = new ObjectInputStream(new FileInputStream("eintrag.dat"));
eintragList = (List<Eintrag>) ois.readObject();
}
catch (IOException e)
{
System.out.println("File doesn't exist");
eintragList = new ArrayList<>();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public void writeEintrag() throws IOException
{
ObjectOutputStream oos = null;
try
{
oos = new ObjectOutputStream(new FileOutputStream("eintrag.dat"));
}
catch (IOException e)
{
e.printStackTrace();
}
oos.writeObject(eintragList);
oos.close();
}
Eintrag class:
public class Eintrag implements Serializable{
String name;
String gebDatum;
public Eintrag(String name, String gebDatum) {
this.name = name;
this.gebDatum = gebDatum;
}
#Override
public String toString()
{
return "Eintrag{" +
"name='" + name + '\'' +
", gebDatum='" + gebDatum + '\'' +
'}';
}
Your problem is here
public Eintrag (String name, String gebDatum)
{
eintrag[i] = new Eintrag (name,gebDatum);
++i;
}
It's an endless loop. It's a recursive call without ending.
You call the constructor that call's it self.. so it does that until the whole stack is full.. and then You get the SF exception :)

Using a user input to make an object in Java

Is there a way for me to take a string input from scanner and create a new object with that string entry? Such as:
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String name = input.nextLine();
ListOfNames name = new ListOfNames();
}
Note that in the last line the "ListOfNames name = new ListOfNames();" I want the new object to be the string that the variable "name" holds.
I want to do this so that after the object is made I can add it to an array then be able to search the array later after inputting multiple names in for the one I need.
There is probably a way to do this with the arrays class but I am new and unfimliar with the class. Any help would be fantastic! Thanks!
You could do...
public class Test {
public static void main(String[] args) {
ArrayList<String> listOfNames = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String name = input.nextLine();
listOfNames.add(name);
}
Just add the received input from Scanner to listOfNames array list.
Or if you are really need to use another Object...
public class Name {
String value;
public Name(String value) {
this.value = value;
}
}
public class Test {
public static void main(String[] args) {
ArrayList<Name> listOfNames = new ArrayList<Name>();
Scanner input = new Scanner(System.in);
System.out.println("What is your name: ");
String nameValue = input.nextLine();
Name n = new Name(nameValue);
listOfNames.add(n);
}

reading an object from stream

I'm trying to read an object ChatMassage from the stream and to print a message (which this object contains) with its method getMassage(). It prints a message the first time but next time it always prints the first message. What is wrong?
Here is an example of the code:
while(keepGoing){
System.out.println("Client: " + ((ChatMassage) in.readObject()).getMassage() + "\n" );
}
ChatMassage class:
public class ChatMassage implements Serializable {
String msg, recipientName = null;
String senderName = "None";
public void setMassage(String msg) {
this.msg = msg;
}
public void setRecipientName(String recName) {
recipientName = recName;
}
public String getMassage() {
return msg;
}
public String getRecipientName() {
return recipientName;
}
public void setSenderName(String name) {
senderName = name;
}
public String getSenderName() {
return senderName;
}
}
I think the problem lies in this method:
public void setMassage(String msg) {
this.msg = msg;
}
I don't know if that can be a problem, but try changing the parameter to something like "new_msg". I think it confuses the "this.msg" with "msg".

Resources