This is essentially what i have, everything works fine, but for some reason I'm not able to input the characters into the array.
If you could explain to me why it isn't working it would be greatly appreciated.
The purpose of this is to input a series of characters into an array, and to count the number of ' ' (gaps) present within it.
The part in bold is where I'm currently having my issue.
import java.util.*;
public class Test4c{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
Scanner a = new Scanner(System.in);
int size;
System.out.println("Please input the size of the array.");
size = x.nextInt();
char[] test = new char[size];
System.out.println("Please input " + size + " characters.");
//ask user to input number of characters
for(int i = 0; i<size; i++){
**test[i] = a.next().toCharArray();**
}
int s;
int e;
System.out.println("Please input the starting value of the search.");
s = x.nextInt();
System.out.println("Please input the ending value of the search.");
e = x.nextInt();
}
public static int spaceCount(char[]arr, int s, int e){
int count = 0;
if (s<= e) {
count = spaceCount(arr,s+1, e);
/*counter set up to cause an increase of "s" so
* the array is traversed until point "e"*/
if (arr[s] == ' ' ) {
count++;
}
}
return count;// return the number of spaces found
}
}
when you force to run your code, you get such error stack
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - incompatible types: char[] cannot be converted to char
at test4c.Test4c.main(Test4c.java:26) Java Result: 1
It is obviously clear why you get such a message?
you try to insert a char array inside an index of char[] test which accept a char not a char array
This is what you have:
for(int i = 0; i<size; i++){
test[i] = a.next().toCharArray();
}
From what you have, I think you want just to convert to a.next() to char array which is test which you have already defined
char[] test = new char[size];
you can change what you have to
test = a.next().toCharArray();
The issue is that the toCharArray returns an array, and you can't put an array into an array. Try this:
Char[] test = a.next().toCharArray();
Related
I wrote the following code but I can't seem to convert the string to a char and then search the input entry string. My code is below. Any helpful tips would be greatly appreciated. I'm supposed to use a while loop but felt like for was easier to start with.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputEntry;
String inputCharacter;
int length;
int i;
int counter = 0;
System.out.println("Enter a string: ");
inputEntry = in.next();
System.out.println("Enter a letter: ");
inputCharacter = in.next();
length = inputCharacter.length();
if (length == 1) {
for(i = 0; i <= inputEntry.length(); i++){
char c = inputCharacter.charAt(0);
if (inputEntry.charAt(i) == c){
counter++;
}
}
}
else {
System.out.println("The input letter was not a single letter.");
}
}
}
It looks like the only problem in your code is that you are using <= instead of < within your loop. <= is incorrect because it passes string length as an index, but first character resides at charAt(0), and last character resides at charAt(inputEntry.length() - 1)
Replacing your loop declaration with the following will do the trick:
for(i = 0; i < inputEntry.length(); i++){
Then you also need to System.out.println(counter); after the for loop.
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.
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.
I'm trying to use Java to solve a simple challenge but I have unsuccessful and I can't find an answer. The idea is that the user enters a string of text, and the program returns the longest word in that string. I can use Scanner to accept the input from the user, and then the .split() method to split the string at the spaces with .split(" ") but I can't figure out how to store the split sentence in an array that I can iterate through to find the longest word. I always get a console output that looks like this:
[Ljava.lang.String;#401a7a05
I have commented out the code that I think should find the longest word so as to focus on the problem of being unable to use Scanner input to create an array of Strings. My code at the moment is:
import java.util.*;
import java.io.*;
class longestWord {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
//for (int i = 0; i <= b.length(); i++) {
// if (longest < b[i].length()) {
// longest = b[i].length();
// word = b[i];
// }
//}
//System.out.println(word);
System.out.println(c);
}
}
That's because you are iterating over the string, not the array, and trying to output the entire array. Change your for loop to use c instead:
for (int i = 0; i < c.length; i++) //In an array, length is a property, not a function
{
if (longest < c[i].length())
{
longest = c[i].length();
word = c[i];
}
}
That should fix your first output. Then you want to change how you output your array, change that to something like this:
System.out.println(Arrays.toString(c));
Which will display the array like so:
[word1, word2, word3, word4]
So you want to get the input as a string and automatically make it an array? You can do that simply by calling the split function after nextLine on the scanner:
String[] wordArray = n.nextLine().split(" ");
there are many mistakes in you code. such a
you were
iterating over string not on array.
if (longest < b[i].length()) as b is your string not array of string
try this it will work it will print the longest word and its size as well.
class Test {
public static void main(String[] args) {
int longest = 0;
String word = null;
Scanner n = new Scanner(System.in);
System.out.println("enter string of text: ");
String b = n.nextLine();
String c[] = b.split(" ");
for (int i = 0; i < c.length; i++) {
if (longest < c[i].length()) {
longest = c[i].length();
word = c[i];
}
}
System.out.println(word);
System.out.println(longest);
}
}
import java.util.Scanner;
class HistogramChart
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the population of data: ");
int populationOfData = scan.nextInt();
System.out.println("Please enter data separated by spaces: ");
String data = scan.next();
int indexWhiteSpace = data.indexOf(" ");
int[] dataArray = new int[populationOfData];
int tempInt = 0;
for(int index = 0; index < populationOfData; index++)
{
String tempString = data.substring(0, indexWhiteSpace);
data = data.substring(indexWhiteSpace+1, data.length());
tempInt = Integer.parseInt(tempString);
dataArray[index] = tempInt;
indexWhiteSpace = data.indexOf(" ");
}
System.out.println(dataArray[0]);
}
}
I realize there's nothing yet to print out the entire array, as i'm just trying to get it to print anything, but this is continually printing the following errors:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1954)
at HistogramChart.main(HistogramChart.java:22)
"
I cannot figure out why this is saying this.
Please help!
Why not using split ?
class HistogramChart {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter data separated by spaces: ");
String data = scan.nextLine();
String tmpDataArray[] = data.split(" ");
int dataArray[] = new int[tmpDataArray.length];
for (int i = 0; i < dataArray.length; ++i) {
dataArray[i] = Integer.parseInt(tmpDataArray[i]);
}
}
If I remember correctly, using
String data = scan.next();
Like you're doing, you will just scan a single element. Try using scan.nextLine() so that it takes the whole line, and then split by spaces so you get an array of your data. And the problen it is actually giving you is because you look for indexOf(" ") but since you're not reading a full line, that nevers happens and you get a -1. When you try to look for a substring with the index -1, then you get that error.