Why won't my string hold spaces? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
import java.util.Scanner;
public class TestEditor {
public static void main(String[] args){
String input;
char[] words = new char[100];
int choice=0;
int start=0;
int end=0;
LineEditor myEditor = new LineEditor();
LineEditor myEditor2 = new LineEditor();
String input2 = null;
System.out.println("+++++++ LineEditor starts... +++++++\n");
System.out.println("* Write the text you want (maximum length: 100): ");
Scanner in = new Scanner(System.in);
input = in.next();
while(input.length()>100){
System.out.println("* Operation failed: You exceeded the maximum length.");
System.out.println("* Write the text you want (maximum length: 100): ");
input = in.next();
System.out.println("\n");
}
System.out.println("--------------------------------------\n");
do{
System.out.println("*Choose the menu:\n1. Insert\n2. Delete\n3. Replace\n4. Quit");
choice=in.nextInt();
System.out.println("\n");
if(choice==1){
System.out.println("* Enter the starting position:");
start = in.nextInt();
System.out.println("* Enter the text you want to replace:");
input2=in.next();
myEditor.insert(input, start, input2);
}
if(choice ==2){
System.out.println("* Enter the starting and ending position for deletion.");
start=in.nextInt();
end=in.nextInt();
myEditor.delete_text(input, start,end);
}
if(choice==3){
System.out.println("* Enter the starting and ending position for insertion.");
start=in.nextInt();
end=in.nextInt();
System.out.println("* Enter the text you want to replace:");
input2=in.next();
myEditor.replace(input, input2, start, end);
}
}while(choice !=4);
System.out.println("Good Bye!");
}
}
public class LineEditor {
private static char [] text;
private static char [] text2;
public LineEditor(){
text=new char[100];
text2=new char[100];
}
public void insert(String input, int start, String input2){
start = start-1;
int j=0;
for(int i=0;i<input.length();i++){
text[i]=input.charAt(i);
}
for(int i=0; i<input2.length();i++){
text2[i]=input2.charAt(i);
}
for(int i=start; i<input.length();i++){
text[i]=text[i+start];
}
for(int i=start; i<input.length();i++){
text[i]=text2[j];
j++;
}
for(int i=0; i<text.length;i++){
System.out.print(text[i]);
}
}
public void delete_text(String input, int start, int end){
for(int i=0;i<input.length();i++){
text[i]=input.charAt(i);
}
start=start-1;
int num = end-start;
for(int i=start; i<end;i++){
text[i]=text[i+num];
}
for(int i=end;i<text.length;i++){
if((i+end)<100){
text[i]=text[i+end];
}else{
text[i]=text[i-end];
}
}
for(int i=0; i<text.length;i++){
System.out.print(text[i]);
}
}
public void replace(String input, String input2, int start, int end){
start = start-1;
int j=0;
for(int i=0;i<input.length();i++){
text[i]=input.charAt(i);
}
for(int i=0; i<input2.length();i++){
text2[i]=input2.charAt(i);
}
for(int i=start; i<input.length();i++){
text[i]=text[i+start];
}
for(int i=start; i<input.length();i++){
text[i]=text2[j];
j++;
}
for(int i=0; i<text.length;i++){
System.out.print(text[i]);
}
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at TestEditor.main(TestEditor.java:29)
So those are my two classes and I keep getting this error when I put a space in my initial input. The error doesn't even happen when I transfer it to an array. Can someone shed some light? Also here is a link for the exact prompt if you would like to look at it.

Rather than in.next(), try using in.nextLine() instead. See if that makes a difference.

Replace next() to nextLine()
next() takes space as delimiter, so when you enter e.g. "Hello test", it take "Hello" only as first input, remaining string goes as input for next scanner call ( in your case this is choice=in.nextInt();) and it will fail to parse string to int.

From Docs:
public class InputMismatchException
extends NoSuchElementException
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

Change next() to nextLine()
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Use the nextLine() method to read all of what is on the current line. It is possible for the current line to only have a newline character which would return an empty string.

Related

user input to a Char Array

I am trying to create a program that takes a user's answer for a test and puts it in a char array, and then compares it to an array with the answers.
I have a problem with input the user's Answers into the char array. I keep getting an EE saying that in.nextLine(); - there is no line found and it throws a no such element exception.
import java.util.Scanner;
public class driverExam {
public static void main(String[] args) {
System.out.println("Driver's Test. Input your answers for the following
10 Q's. ");
System.out.println();
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =9;
String userInput;
for (int i =0; i<uA;i++) {
Scanner in = new Scanner(System.in);
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();
int len = userInput.length();
char[] userAnswers = new char [len];
for(int x =0;x<len;x++) {
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
System.out.println(userAnswers);
}
System.out.println("Your answers have been recorded.");
System.out.println();
}
}
Shouldn't userAnswers array be of size 10?
Your program has quite redundant and unnecessary steps, according to me. So I have modified it to meet your need.
There is no need to put the "Scanner in...." inside the loop.
This loop is full of mistakes. Not discouraging, just saying.
for (int i =0; i<uA;i++)
{
Scanner in = new Scanner(System.in);//scanner inside loop
System.out.print("Question #"+(i+1)+": ");
userInput = in.nextLine();
in.close();//already mentioned by someone in the comment
int len = userInput.length();
char[] userAnswers = new char [len];//no need to declare array inside loop
for(int x =0;x<len;x++)
{
userAnswers[i] = userInput.toUpperCase().charAt(i);
}
}
System.out.println(userAnswers);//this will not print the array,it will print
//something like [I#8428 ,[ denotes 1D array,I integer,and the rest of it has
//some meaning too
Now here is the code which will get the work done
char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =testAnswers.length;//to find the length of testAnswers array i.e. 10
char[] userAnswers = new char [uA];
char userInput;
int i;
Scanner in = new Scanner(System.in);
for (i =0; i<uA;i++)
{
System.out.print("Question #"+(i+1)+": ");
userInput = Character.toUpperCase(in.next().charAt(0));
}
for(i=0;i<ua;i++)
{
System.out.println(userAnswers[i]);
}
System.out.println("Data has been recorded");
I am not demeaning, just trying to help.

Not a Statement Error - Where did I go wrong?

So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.

Creating a random output from an user input array [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 6 years ago.
Improve this question
public class decisionMaker {
public static void main(String args[]) {
String option[] = new String[10];
// Output
for (int i = 0; i <= 9; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the next option:");
option[i] = input.next();
System.out.println(" ");
}
for (int i = 0; i <= 9; i++) {
System.out.println("option: ");
System.out.println("option[i]+" ");
}
// Output
}
I'm trying to figure out how to add a count to the options, exit and end the program after entering a certain letter or number, and how to create a random output from the user input. I want it to give me one option that I had input at random. Can anyone help me with one or a few of these things. I'm trying to learn to code on my own, and I'm stuck on these.
Randomness
You can generate random numbers using java.util.Random;:
import java.util.Random;
public class SomeClass{
static Random rand = new Random();
public static void main(String args[]){
System.out.println(rand.nextInt());
}
}
About some broken code:
If you want to print out the value of a variable with System.out.println() then you need only type the variable without any quotation marks. The code you've written below will not compile:
System.out.println("option: ");
System.out.println("option[i]+" ");
Assuming that's what you want to do, it should instead be written as:
System.out.println("option: ");
System.out.println(option[i]);
Or even System.out.println("option: \n"+option[i]);
(The escape sequence \n when placed inside of quotation marks just indicates to the console to add a new line.)
Scanner:
Additionally, as nick zoum pointed out, your Scanner object should be initialized outside of the for loop, such as right underneath of the main() method.
Please comment below if you need clarification or if I misunderstood what you were looking for. It was very hard to understand your question.
You could try something like this:
public class DecisionMaker {
public static void main(String[] args) {
// output
Scanner scanner = new Scanner(System.in);
int size = getInt(scanner);
String option[] = new String[size];
for (int index = 0; index < size; index++) {
System.out.print("Enter the next option:");
option[index] = scanner.next();
}
int index = (int) (Math.random() * size);
System.out.println(option[index]);
scanner.close();
// output
}
public static int getInt(Scanner scanner) {
int size = 0;
while (size <= 0) {
if (scanner.hasNext()) {
if (scanner.hasNextInt()) {
size = scanner.nextInt();
}
}
if (size <= 0) {
System.out.println("The input: " + scanner.next() + " is not a valid value.");
}
}
return size;
}
}
How the program works:
The Scanner is initialized in the beginning and there is only
one instance of it.
Then the program will wait until the user inserts a valid number for
the size of options.
The next 5 lines were essentially copied from your code.
Finally we get a random Integer in the range of 0 - (size - 1) and print
the String of the array with that index.

java while loop throwing exception

the first line takes the size of the array to follow.The array's digits are checked to see if they can form a ambiguous permutation.
public class Codechef2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int intnum=10;
intnum=input.nextInt();
input.nextLine();
String a[]=new String[100000];
int count=0;
int i=0;
While(intnum>0)
{
a[i]=input.nextLine();
String arr[]=a[i].split(" ");
int aj[]=new int[arr.length];
int k=0;
for(int j=0;j<arr.length;j++)
{
aj[Integer.parseInt(arr[k])]=j+1;
k++;
}
for(int l=0;l<arr.length;l++)
{
if(aj[l]==Integer.parseInt(arr[l]))
count++;
}
if(count==arr.length)
System.out.println("ambiguous permutation");
else
System.out.println("Not ambiguous permutation");
intnum=input.nextInt();
}
}
}
EDIT:
Again: pleas post a compilable code:
//wrong
//While(intnum>0)
while(intnum>0)
Also:
//you need to print a msg so the user knows that he / she
//needs to input and tell the user what to input
System.out.println("Please enter ....");
input.nextLine();
The code has many errors.
For example :
String aj[]=new aj[arr.length]; //will not compile
While(intnum>0) //will not compile
a[i]=input.nextLine(); //will not compile. i is defined later.
aj[arr[k]]=i+1; //wrong : aj[] is a String. i+1 is an int.
Fix them and post a compilable code.
Code below the while loop is not executed until the conditions of the while loop are met.

The toLowerCase() Method appears to not work [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been writing a program that is supposed to count the occurrence of a letter in a String array. In order to do so I've made every input lower case, so that when the search for the specified letter is being done it is all done in lower case. The program works when the letter being searched for is inputted in lower case, but wont work when in upper case. I'm confused about this because I've used the toLowerCase() method to make the inputted letter lower case despite what is inputted. Any help would be greatly appreciated.
import java.util.Scanner;
public class RunStringArray
{
public static void main (String [] args){
int arrayLength;
int count = 0;
String word;
String letter;
int letterCount = 0;
int x = 0;
//Asks user for length of array
Scanner kbInput = new Scanner(System.in);
System.out.println("Enter a positive integer");
arrayLength = kbInput.nextInt();
//Makes sure array length is a valid number
while (arrayLength <= 0){
System.out.println("Invalid input (not positive)");
System.out.println("Enter a positive integer");
arrayLength = kbInput.nextInt();
}
//Creates array of the user specified length
String words [] = new String [arrayLength];
//Asks user to input all strings in the array and makes them lower case.
kbInput.nextLine();
while (count < words.length){
System.out.println("Enter a string");
word = kbInput.nextLine();
word = word.toLowerCase();
words[count] = word;
count++;
}
//Asks user what letter he/she wants to count in the array
System.out.println("What letter do you want to count?");
letter = kbInput.nextLine();
letter.toLowerCase();
//Error trap making sure the user inputs a letter.
while (letter.length() > 1){
System.out.println("Invalid input (not a letter)");
System.out.println("What latter do you want to count?");
letter=kbInput.nextLine();
letter.toLowerCase();
}
char c = letter.charAt(0);
//While loop which will count the occurrence of the letter in each
//string in the array, and then adds all of the occurrences together
//in order to find the total occurrences of the letter.
while (count > 0){
letterCount = RunStringArray.count(words[count-1], c);
x += letterCount;
count--;
}
System.out.println(x);
} //End of main
private static int count (String str, char searchLetter){
int occurrences = 0;
for (int k = 0; k < str.length(); k++){
if (str.charAt(k) == searchLetter)
{
occurrences++;
} //End of if
} //End of for loop
return occurrences;
} //End of method
} //End of class
You are not storing the output of letter.toLowerCase().
Change
letter.toLowerCase();
to
letter = letter.toLowerCase();
Methods that are executed on Strings, Integers, Long etc will produce new objects. Thats why you need to assign those values. The reason: Strings and all those types are immutable, you cannot change its value, when you do java creates new object.
letter = kbInput.nextLine().toLowerCase();

Categories