InvocationTargetException while setting values in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have problem with InvocationTargetException.
I am setting values of object using scanner and it became to return such strange exception for me. I did read doc and i was searching internet to find solution, but I can't figure out what's wrong.
Also don't read println strings, they are in my native language.
public Person SignPerson() {
Scanner scanner = new Scanner(System.in);
System.out.println("Tworzymy twoje konto użytkownika, podaj dane osobowe");
System.out.println("Podaj swoj pesel");
String id = setPersonalId();
Person person = new Person(id);
System.out.println("Podaj swoje imie");
person.setFirstName(scanner.nextLine()); // the line taht causes problem (other
// scanners also throws exceptions)
System.out.println("Podaj drugie imie");
//tutaj powinien byc wgrany drugi kod do odczytu imienia
System.out.println("Podaj nazwisko");
person.setLastName(scanner.nextLine());
System.out.println("Podaj nazwisko panienskie matki");
person.setMotherMaidensName(scanner.nextLine());
return person;
}
public static String setPersonalId() {
String id;
try (
Scanner scanner2 = new Scanner(System.in);
) {
id = scanner2.next();
char[] chars = id.toCharArray();
for (char aChar : chars) {
if (!(aChar >= '0' && aChar <= '9'))
throw new InvalidStringException();
}
return id;
} catch (InvalidStringException e) {
System.out.println("Wprowadziles niepoprawny pesel");
}
return null;
}

There might be at least two issues here:
Don't close a Scanner wrapping System.in, as this will also
close the underlying stream. (see
Close a Scanner linked to System.in)
To fix this, remove the the creation of the second Scanner from
the try-with-resource block, to avoid it getting closed
automatically. You may also not create a second scanner, but pass
the first one to the method where it will be used.
String id = setPersonalId(scanner);
and in your setPersonalId:
public static String setPersonalId(Scanner s) { ...
Calling nextLine() after calling next() will also cause
problems, explained here:
Scanner is skipping nextLine() after using next() or nextFoo()?:
To fix the second issue, you may simply call nextLine() everytime,
instead of next() (or consume the linefeed as shown in the link):
id = s.nextLine();

Print e.printStackTrace() inside of Exception e block and then it points to the actual stack trace in the JDK Library. Go inside of it in the library and figure out which line is throwing error and figure out the solution based on line number in JDK Library.

Related

Do while loop condition not matching with variables inputted through scanners [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 hours ago.
Improve this question
I am a beginner in Java and this issue arose when I was working on a HackerRank problem that I have solved but it still confuses me why it wouldn't work the first iteration of code I made to solve it. This code function is to separate a string and an integer into two columns with the integer being limited to three digits and string having 10 chr limit, covered by "========". Also, I intend the code only ends when the user has inputted "nothing" or white spaces.
However, the do while loop keeps going as its condition does not match the inputted variables created by the scanner, being white spaces. I had a clue that it might be when I used an integer scanner as it interfered with the string scanner, but I tried clearing the scanner by using nextLine(), and it wouldn't work with the loop. I tried using scanner.reset() and also declaring the integer first as a string and then converting it back to an integer but the loop keeps going. I tried simplifying it, and I found out that the loop ends when I use "word = scanner.nextLine();" but it wouldn't work with the loop. Hope you guys can educate me and possible ways to fix this issue.
package hackerRankTestCode;
import java.util.Scanner;
import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
public class TestCode {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word = "";
Integer number = 0;
String baruNumber = "";
System.out.println("================================");
do {
word = scanner.next();
number = scanner.nextInt();
String blank = new String(new char[15 - word.length()]).replace("\0", " ");
if(number<100 && number>=10){
baruNumber = "0"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=0 && number<10) {
baruNumber = "00"+number;
System.out.println(word+blank+baruNumber);
}
else if(number>=100) {
System.out.println(word+blank+number);
}
}
while(!word.isBlank() && number != 0);
scanner.close();
System.out.println("================================");
}
}

How do I check for an empty string in a Boolean statement? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an assignment where I have to attach the letters "un" to any word that the user inputs (unless the inputted word already has "un" in front of it, in which case I just return the inputted word). I'm testing my method but I encountered one problem: my program keeps returning an error if I were to test for an empty input. Here is my code:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter: ");
String input = keyboard.nextLine();
if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else if(input.equals(""))
{
System.out.println("un");
}
else
{
System.out.println("un" + input);
}
So I wanted to ask how I can test for an empty input/blank string since, evidently, the "" quotations do not work.
There's nothing wrong with checking input.equals("") per-se. The problem is that you have another test beforehand that throws an exception if input is shorter than 2 characters.
There are several ways to solve this, but I'd just simplify things and use startsWith. An empty string doesn't really need a special case of its own - just slap un before it, and you'll get un:
if (input.toLowerCase().startsWith("un")) {
System.out.println(input);
} else {
System.out.println("un" + input);
}
You are having this problem because you are trying to get the substring of string that doesnt have the required length. Put the empty string check first.
if(input.equals("")||input.length==1)
{
System.out.println("un");
}
else if(input.substring(0,2).equalsIgnoreCase("un"))
{
System.out.println(input);
}
else
{
System.out.println("un" + input);
}
If this weren't homework, and the library could be used for other things ( using it in this single purpose may be overkill ), you could use StringUtils.PrependIfMissing().
It does exactly this and handles nulls as well.

How can I re-arrange my code to produce the output I want? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Please could you help me re-arrange my already working code to give me this output described in the bullet points underneath:
'Type your text' window appears
The user enters the text, for example 'hey'
The code prints out the text entered by the user (hey), underneath the code prints out the number of characters (3) and finally another scanner window 'Type your text' appears. So the program loops back to 2 and waits for another line to be typed.
This would look like this:
hey
3
another scanner for the text to be typed in
My code already works and calculates everything, i just ran out of ideas how to re-arrange it to make its output exactly what i want:
System.out.println("Type your text...");
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextLine());
System.out.println(sc.nextLine().length());
System.out.println("Length of String: " + lengthOfString("hey"));
sc.close();
}
private static int lengthOfString(String string) {
int length = -1;
while (true) {
try {
string.charAt(++length);
} catch (StringIndexOutOfBoundsException exception) {
break;
}
}
return length;
}
I am a beginner and I have weak understanding of java so please be clear with your answers and all your answers will be much appreciated, thank you!
The main problem is that you are calling nextLine() twice when you only want to be calling it once. Instead of these two lines:
System.out.println(sc.nextLine());
System.out.println(sc.nextLine().length());
Use this:
String input = sc.nextLine();
System.out.println(input);
System.out.println(input.length());
Another problem is that you are closing sc. This will close the underlying stream (System.in), which you don't want to do. Finally, you need to invoke this code in a loop so that the process is repeated. You don't show the context for this code, but I'm assuming that it's in a method that is being called in a loop or is part of the body of a loop. In either case, it would be better to create a Scanner once and use it repeatedly, rather than creating and disposing of a Scanner for each transaction with the user.
while (true)
{
System.out.println("Type your text...");
String str = sc.nextLine();
System.out.println("Length of String: " + str.length());
}
Have removed unncessary complexity from your code,Try this code:
Scanner sc=new Scanner(System.in);
String s;
while(true) //have created infinite loop as you want to continuously take inputs,
{
System.out.println("Enter value:");
s=sc.next();
if(s.equals("quit")) //if enterd value is "quit" than it comes out of loop ,termination condition to come out
{
break;
}
System.out.println(""+s); //to Print string
System.out.println(""+s.length()); //to print Entered string's length
}
Try out this:
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
count++;
str.substring(count);
}
System.out.println("Length :"+count);
}
}
Use a loop, calling nextLine() twice reads two lines (and throws them away) and don't close your Scanner. System.in is a global, if you close() your Scanner that will close System.in and it will not reopen.
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Type your text...");
// System.out.println(sc.nextLine()); // <-- thrown away!
// System.out.println(sc.nextLine().length()); // <-- Second next line call
String line = sc.nextLine();
System.out.println("Length of String: " + lengthOfString(line)); // <-- not "hey"
// sc.close();
}
Edit
Just read lengthOfString(String), let's fix that -
private static int lengthOfString(String string) {
return string.trim().length();
}

New to java. Error using scanner class in while loop?

So my first assignment involves making a simple question and answer program. The user asks a question, and I generate an answer. I've never done java before. Here is my input class:
//msg is the msg I output (answer to their question).
//Function returns inputStr which is the question the user asks.
public String getInput(String msg) {
System.out.println(msg);
Scanner theInput = new Scanner(System.in);
String inputStr = theInput.nextLine(); //ERROR HERE ON 2nd ITERATION!
theInput.close();
if (inputStr.equals("exit")) {
System.out.println("GoodBye!");
System.exit(0);
}
return inputStr;
}
The function that calls this in the while loop is as follows:
//inputSource is an object that has the getInput method. It is an argument for this function.
String userQuestion = inputSource.getInput(firstLine);
String initMsg = processMessage(userQuestion);
while(!initMsg.equalsIgnoreCase("GoodBye")){
userQuestion = inputSource.getInput(initMsg);
//Doesn't get to here.
initMsg = processMessage(userQuestion);
}
System.out.println(initMsg);
Error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
So basically, what happens is that it asks a question once, and then it gives back an answer once, but when it enters the while loop, it gets stuck at the indicated point.
Little help. Thank you.
One thing that I noticed: you should probably not call close() on the scanner. You're closing the underlying input stream (standard input), according to the JavaDocs.

if i entered numbers separated with commas, how could i extract the numbers? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
for example....
26, 15, 37
how could i get the numbers from a Scanner , ( lets say for instance i want to add or subtract,,,?)
Take a look at String.split().
If you want to use the Scanner API:
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
for (;;) {
integers.add(scanner.nextInt());
if (scanner.hasNext(COMMA_PATTERN)) {
// Read and discard comma token, and continue parsing list.
scanner.next();
} else {
// Number is not followed by comma, stop parsing.
break;
}
}
return integers;
}
More error handling is needed, but hopefully, this example illustrates the approach.
You can also use Scanner.useDelimiter():
private static final Pattern COMMA_PATTERN = Pattern.compile("\\s*,\\s*");
public List<Integer> getIntegerList() {
// Assumes scanner is positioned at first integer in list.
List<Integer> integers = new ArrayList<Integer>();
Pattern oldDelimiter = scanner.delimiter();
scanner.useDelimiter(COMMA_PATTERN);
while (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
// Reset delimiter
scanner.useDelimiter(oldDelimiter);
return integers;
}
Use Scanner.useDelimiter. It actually takes regex, so you'd want to learn some basics.
String text = "1 , 2 3, 4,5";
Scanner sc = new Scanner(text).useDelimiter("\\s*,?\\s*");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
} // prints "1", "2", "3", "4","5"
See also
http://www.regular-expressions.info/ -- the best tutorial resource
Related questions
How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
Using hasNextInt() to prevent exception is much better than Integer.parseInt and catch NumberFormatException
String.split() is OK, but StringTokenizer works everywhere and in every version of Java.
StringTokenizer st = new StringTokenizer("26, 15, 37", ", ");
int sum = 0;
while (st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}
Try to set a delimiter for your scanner object:
Scanner s = new Scanner(System.in).useDelimiter(", *");
int first = s.nextInt();
int second = s.nextInt();
...
More examples can be found in Scanner documentation.
Look at useDelimiter. You need a regex that will match either whitespace or commas.

Categories

Resources