Do while loop condition not matching with variables inputted through scanners [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 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("================================");
}
}

Related

InvocationTargetException while setting values in Java [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 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.

Can someone tell me why am I getting java.lang.ArrayIndexOutOfBoundsException error in my code? [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 2 years ago.
Improve this question
I am working on a Java program to iterate through two arrays and compare the first one to the second for any matches. It should return all the numbers/strings that DON'T MATCH as an array list. I am done, but I am not sure why I am getting an ArrayIndexOutOfBoundsException error. This is my code:
package test;
import java.awt.List;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArrayComparer {
public static ArrayList<String> ArrayComparer(String[] arrayOne, String[] arrayTwo){
// if one is bigger than start by comparing the smaller one to the bigger one
// as if it were the other way the bigger one would run out over numbers to compare
// declaring the array for holding all the non-matching telephone numbers to be returned
ArrayList<String> nonMatchingTelephoneNumbers = new ArrayList<String>();
for(int i = 0; i<arrayOne.length; i++){
int strikes = 0;
// for each value of the first one it should go through all the values of the second and compare each
for(int i2 = 0; i<arrayTwo.length; i2++){
if(arrayOne[i] != arrayTwo[i2]){
strikes++;
if(strikes == arrayTwo.length){
// meaning it has gone through ALL of arrayTwo and couldn't find a match
nonMatchingTelephoneNumbers.add(arrayOne[i]);
}
}
}
}
return nonMatchingTelephoneNumbers;
}
public static void main(String[] args) throws IOException {
// declaring the first list of telephone number
String[] ArrayListOne;
// declaring the second list of telephone numbers
String[] ArrayListTwo;
// splitting up the user input of telephone numbers by commas
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your first array of telephone numbers, split by commas");
ArrayListOne = myObj.nextLine().split(","); // Read user input
// once it has iterated through all of the telephone numbers in the first list, ask for the second list
Scanner myObj2 = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter your second array of telephone numbers, split by commas");
ArrayListTwo = myObj2.nextLine().split(","); // Read the second user input
// once it has collected and sorted all the user input, the ArrayCOmparer method should be called
// to compare them and return the telephone numbers that DON'T MATCH
ArrayComparer(ArrayListOne, ArrayListTwo);
}
}
The error is on line 22, where it says if(arrayOne[i] != arrayTwo[i2]){.It also doesn't say there is an error on line 22 until I run it. Can someone please tell me why I am getting this:console error?
Hi i think this is causing the error
for(int i2 = 0; i<arrayTwo.length; i2++){
You should replace it with:
for(int i2 = 0; i2<arrayTwo.length; i2++){

How to count the amount of space delimiters in a string using the for loop?

I am new to Java and am working on an assignment where you need to count the amount of delimiters or spaces in a string that the user inputs.
I have to use a method that prompts the user to input a string using the Keyboard class. However, I am using BlueJ and Keyboard is not compatible with the BlueJ library thing. I do know that Scanner could be as an alternative with Keyboard but I am not sure how to read a string using Scanner.
Furthermore, I am not sure how I am suppose to structure my for loop to count the delimiters in a string. I am sorry for my high misunderstanding with this and I know that I am asking a lot but please don't feel obligated to answer everything, just whatever you want to or what you can easily answer. Here is my code below:
import cs1.keyboard;
import java.util.StringTokenizer;
public class Counting_Chars
{
public static void main (String []args)
{
int spaceCount = 0, characterCount = 0;
String line, word;
StringTokenizer tokenizer;
System.out.println("Please enter text (type DONE to quit):");
line = scan.nextLine();
String phrase = line;
for (String ch = phrase.charAt(line);; ch <= line; count++)// I don't really know what I am doing here
{
System.out.println (count);
}
}
}
it sounds like you are having multiple issues here. Perhaps it would be good to break the problem down into smaller parts and build your way back up again.
I would suggest something like:
write a program that just prints out some text (like 'Hello World')
write a program that asks the user to type in a line of text and
then just prints out that exact same text again
then worry about counting the spaces in the string

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.

Output accumulates each iteration instead of resetting [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The code runs properly the first time then run it again using the while loop and lets say the first time I entered AA and it becomes CC then it runs again I enter AA again it will come out with CCCC do it again it comes out with CCCCCC I don't want that I need it to not keep the data from the string each time it loops.
import java.util.*;
public class SecretCypher {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
StringBuffer e = new StringBuffer();
System.out.println("Welcome to Secret Cypher!");
char loop = 'Y';
while(loop == 'Y' || loop == 'y') {
System.out.println("");
System.out.println("Enter your cypher in upper case.");
String s = kb.nextLine();
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
e.append((char)('A' + (cs[i] - 'A' + 2) % 26));
}
if(s == s.toLowerCase()) {
System.out.println("Remember to use upper case letters!");
System.exit(0);//Also I was bored of using break and this works any where in the code.
}
System.out.println(e.toString());
System.out.println("Do you want to enter another cypher? > ");
String again = kb.nextLine();
if(again.charAt(0) == 'N') {
System.out.println("Hope you come back again!");
break;
}
}
}
}
You're reusing the same string buffer. If you keep putting things into the same buffer without clearing it, you're obviously going to get extraneous stuff from previous iterations.
Simply declare the StringBuffer inside the while loop so that it is created on each iteration.
Anyway, you should learn to use your debugger, instead of asking here for us to debug. If anything, using the debugger can offer extremely valuable insight into the troubles that you are having here.

Categories

Resources