there It has been a while cense I wrote a java program. I have a problem convert
ID: 3639480 • Letter: T
Question
thereIt has been a while cense I wrote a java program. I have a problem converting a string into char array. Although I used the toCharArray method, the array saves only the first character.
Can you please correct my code?
Also, I need the program to take an integer from the user as a increment number of the array position the. For example: if the array was {'I',' ','a','m',' ','s','t','u','d','y','I','n,'g'}, and the increment is 3, the loop starts from index 0 and go to index 3 and prints 'm'. Then, it adds the current index to the increment….etc.
Below is my code, can you please correct it?
import java.util.*;
import javax.swing.*;
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
System.out.println("enter a sentece");
String sentence = in.next();
char[] letters = new char[sentence.length()];
letters = sentence.toCharArray();
for(int i=0; i<letters.length; i++){
System.out.print(letters[i]);
}
System.out.println("enter the increment number: ");
int increment= in.nextInt();
for(int j=0;j<=letters.length;j+=increment){
System.out.println(letters[j]+ " ");
}
}
}
## in the run time, an InputMismatchException
apperars after i enter the sentence......please the due date of this assigment is omorrow
Explanation / Answer
please rate - thanks
in addition to using nextLine, instead of next. just use charAt
import java.util.*;
import javax.swing.*;
public class main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
System.out.print ("enter a sentece: ");
String sentence = in.nextLine();
System.out.println("You entered: "+sentence);
System.out.println("enter the increment number: ");
int increment= in.nextInt();
for(int j=increment ;j<=sentence.length();j+=increment){
System.out.println(sentence.charAt(j));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.