This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I have to get a string input and an integer input, but there order of input should be that integer comes first then user should be asked for string input
Scanner in = new Scanner(System.in);
input = in.nextLine();
k = in.nextInt();
in.close();
The above code works fine but if I take an integer input first like in the following code
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
then it throws the java.lang.ArrayIndexOutOfBoundsException.
Here's the complete code of my source file:
import java.util.Scanner;
public class StringSwap {
public static void main(String args[]) {
String input;
int k;
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
int noOfCh = noOfSwapCharacters(input);
originalString(input, noOfCh, k);
}
public static int noOfSwapCharacters(String s) {
char cS[] = s.toCharArray();
int i = 0, postCounter = 0;
while (cS[i] != '\0') {
if (cS[i] != '\0' && cS[i + 1] != '\0') {
cS[cS.length - 1 - postCounter] = '\0';
postCounter++;
}
i++;
}
return postCounter;
}
public static void originalString(String s, int noOfCh, int k) {
int counter = 1, chCounter = 0;
char cArray[] = s.toCharArray();
String post = "";
String pre = "";
String finalString = "";
char temp;
for (int i = 1; i <= k; i++) {
chCounter = 0;
counter = 1;
post = "";
pre = "";
for (int j = 0; j < cArray.length; j++) {
if (counter % 2 == 0 && chCounter <= noOfCh) {
temp = cArray[j];
post = temp + post;
cArray[j] = '\0';
chCounter++;
}
counter++;
}
for (int h = 0; h < cArray.length; h++) {
if (cArray[h] != '\0')
pre = pre + cArray[h];
}
finalString = pre + post;
for (int l = 0; l < finalString.length(); l++) {
cArray[l] = finalString.charAt(l);
}
}
System.out.println(finalString);
}
}
Kindly point out what I am doing wrong here.
The problem is the '\n' character that follows your integer. When you call nextInt, the scanner reads the int, but it does not consume the '\n' character after it; nextLine does that. That is why you get an empty line instead of the string that you were expecting to get.
Let's say your input has the following data:
12345
hello
Here is how the input buffer looks initially (^ represents the position at which the Scanner reads the next piece of data):
1 2 3 4 5 \n h e l l o \n
^
After nextInt, the buffer looks like this:
1 2 3 4 5 \n h e l l o \n
^
The first nextLine consumes the \n, leaving your buffer like this:
1 2 3 4 5 \n h e l l o \n
^
Now the nextLine call will produce the expected result. Therefore, to fix your program, all you need is to add another call to nextLine after nextInt, and discard its result:
k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();
Related
This question already has answers here:
How to read integer value from the standard input in Java
(7 answers)
Closed 3 years ago.
I'm trying to have the user input 2 strings into this function so that they can be compared.
I am not too familiar with java more familiar with c++ and I'm not a dev.
public class Levenshtein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
// j == 0; nw = lev(i -1, j)
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static void main(String [] args) {
String [] data = { "kitten", "Mitten" };
for (int i = 0; i < data.length; i += 2)
System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
}
}
just use the args in main
public static void main(String [] args) {
for (int i = 0; i < args.length; i += 2)
System.out.println("distance(" + args[i] + ", " + args[i+1] + ") = " + distance(args[i], args[i+1]));
}
and run it with java -jar app.jar kitten mitten
Here's an example of how to use Scanner to read inputs in Java.
Scanner s = new Scanner(System.in);
String first = s.nextLine();
String second = s.nextLine();
String[] nextTwo = s.nextLine().split(" ");
System.out.println(first);
System.out.println(second);
System.out.println(nextTwo[0]);
System.out.println(nextTwo[1]);
s.close();
Sample input
I am a teapot
Short and stout
Here is my handle
Sample output
I am a teapot
Short and stout
Here
is
As for how to apply this in your program, simply do the following:
public static void main(String [] args) {
// Using this construct, the "try-with-resources" block, will automatically
// close the Scanner resource for you
try(Scanner s = new Scanner(System.in) {
System.out.println("Enter first word:");
String first = s.nextLine();
System.out.println("Enter second word:");
String second = s.nextLine();
System.out.println(String.format("The distance is: %d",distance(first, second)));
}//Scanner s is automatically closed here
}
Note that you should generally NOT close the System.in stream, as it will disallow you from reading input in the rest of the program. However, as your program terminates in the scope of the try-with-resources block, it is acceptable to do so in this scenario.
One approach you can take to close Scanners linked to your System.in stream is to wrap System.in in a CloseShieldInputStream, as seen here.
You can use the scanner object:
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
I use Scanner for inputs from the Console.
U can do:
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sx.nextLine();
System.out.println("distance(" + s1 + ", " + s2 + ") = " + distance(s1, s2));
sc.close();
I am trying to make a program in java which would give a pattern for an inputted string as follows
C O M P U T E R
O E
M T
P U
U P
T M
E O
R E T U P M O C
Here is my program code
import java.util.Scanner;
class pandapattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a word : ");
String s=sc.nextLine();
System.out.println();
int l=s.length();
for(int i=0;i<+l;i++)
{
System.out.print(s.charAt(i)+" ");
}
char[][] frwd = new char[l][1];
char[][] bcwd = new char[l][1];
for(int f=1;f<l;f++)
{
frwd[f][0]=s.charAt(f);
}
for(int b=l-2;b>=0;b--)
{
bcwd[b][0]=s.charAt(b);
}
for(int p=1;p<l;p++)
{
System.out.print("\n"+frwd[p][0]);
}
for(int p1=l-1;p1>=0;p1--)
{
System.out.print(bcwd[p1][0]+" ");
}
}
}
I get this pattern:
C O M P U T E R
O
M
P
U
T
E
R E T U P M O C
How would I get the whole pattern printed out?
Please help me to figure it out.
You onle need one char[] array, not more.
The trick is to take the problem "row-by-row".
See below:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter word for Panda Pattern: ");
String word = scanner.nextLine();
String wspace = " ";
//convert user input from String to char[]
char[] wordLetters = word.toCharArray();
//define array's length, for ease of reference
int length = wordLetters.length;
//initially print the sentence in a horizontal line
for (char wordLetter : wordLetters) {
System.out.print(wordLetter + wspace);
}
//insert new line to start printing for the pattern
System.out.print("\n");
/*A for loop that will print the left-most letters vertically
We start the loop from 1, because the first letter was already printed*/
for(int i=1; i<length; i++){
System.out.print(wordLetters[i]);
/*now we have an inner loop that will print the spaces and the
rest of the letters in reverse order*/
for(int j=1; j<length; j++){
//conditional for IF we are at final line
if(i == length-1 && j != length-1)
System.out.print(wspace + wordLetters[i-j]);
//conditional for printing right-most letters
else if(j == length-1) {
System.out.print(wspace + wordLetters[j-i]+"\n");
}
//THIS WILL PRINT 2 WHITE-SPACES.
else
System.out.print(wspace + wspace);
}
}
}
Why didn't I need a second array ?
Since this pattern requires only one word, then printing in reverse, means that there is still the same amount of letters to process, so any additional arrays would have the same length.
Ergo, we can omit creating new arrays altogether!
Why not manipulate the power that for-loops & arrays give us?
Firstly, for this task you need one-dimension arrays frwd and bcwr
Secondly, you fill array bcwd in the same way as frwd.
Rewritten part of your method correctly for the task:
int length = s.length();
//printing first line
for (int i = 0; i < +length; i++) {
System.out.print(s.charAt(i) + " ");
}
System.out.println();
//filling arrays
char[] frwd = new char[length];
char[] bcwd = new char[length];
for (int f = 1; f < length; f++) {
frwd[f] = s.charAt(f);
}
for (int b = 0; b < length; b++) {
bcwd[b] = s.charAt(length-1 - b);
}
for (int p = 1; p < length-1; p++) {
System.out.print(frwd[p]);
//filling spaces to line by length of input string
for (int p3 = 1; p3 < frwd.length-1; p3++) {
System.out.print(" " + " ");
}
System.out.print(" " + bcwd[p]);
System.out.println();
}
for (int p = 0; p <= length - 1; p++) {
System.out.print(bcwd[p] + " ");
}
System.out.println();
And you can use just input string without extra char arrays. Just get characters from string (s.charAt(i)) in straight and backwar loops.
*
import java.util.*;
class Word{
void main(){
char ch='\u0000',firstc,lastc;
int c=0,lw; String w="",s1="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();n=n+"";
for (int i=0;i<n.length();i++){
ch = n.charAt(i);
if(ch!=' '){
w=w+ch;
}else{
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if(firstc==(lastc))
s1=s1+w;
System.out.println(""+s1);
}
}
w=" ";
}
}
*
Now the output comes for one string like if I give MADAM HAVE A MODEM as input it only gives me MADAM as output.
You have to split your "in" string by spaces " ".
After that, if both characters at the start and at the end.
Notice String.charAt() method will get characters from position 0 (start) to the string lenght - 1.
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
String[] parts = n.split(" ");
for(String part : parts) {
if(part.charAt(0)==part.charAt(part.length()-1)) {
System.out.println(part);
}
}
Your code is overly complicated. It would be much simpler to either split the string on space or just read one word at a time:
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
// Get next word
String s = in.next();
if (Character.toLowerCase(s.charAt(0)) == Character.toLowerCase(s.charAt(s.length() - 1))) {
System.out.println(s);
}
}
But back to your code, I see these issues.
It will always skip the last word
You reset w outside of the for and it should be w = "";
Your indentation is really bad
Your code fixed (well, at least working):
char firstc, lastc;
String w = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a String");
String n = in.nextLine();
for (int i = 0; i < n.length(); i++) {
ch = n.charAt(i);
if (ch != ' '){
w = w + ch;
}
if (ch == ' ' || i == n.length()-1) {
firstc = w.charAt(0);
lastc = w.charAt(w.length()-1);
if (firstc == lastc) {
System.out.println(w);
}
w="";
}
}
I am trying to convert the input of a Int directly to a String.
I am also trying to make it so the program will find the correct number in a credit card sequence to make it correct.
For example if I input a incorrect credit card number, the program finds a way to change the numbers so it becomes correct.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input a credit card number to validate");
String cc = in.nextLine();
validateCreditCardNumber(cc);
String convertedCC = (cc);
}
private static void validateCreditCardNumber(String str) {
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum += ints[i];
}
if (sum % 10 == 0) {
System.out.println(str + " is a valid credit card number");
} else {
System.out.println(str + " is an invalid credit card number");
}
}
That is all my code, but what i am trying to fix is when I initialize cc, i can convert to a string to be later used.
My issues:
int to string has been fixed,
converting to correct CC number has not been fixed.
Can you just get it as a string directly?
String cc = in.nextLine();
Use following code instead of int cc = in.nextInt();
String cc = in.next();
You never use the int version of the scanned input. Instead of making cc an int then converting to a string, just initially make it a string... something like this:
String cc = in.nextLine();
12.9 ; I # 13 jav
3.8 ; can # 6 aru
4.0 ; read # 109 les
The program is supposed to read this in as a string and then add all the doubles, integers, and then to add the first string together and the last string together. So the program should provide
Double total : 20.7
Integer total : 128
Line : I can read
Word: javarules
This is what I have so far , I know that I have to use scanner to skip over the tokens .
public class Test {
public static void main (String args[]) throws FileNotFoundException {
Scanner sc = new Scanner(Test4.class.getResourceAsStream("week2inputdata.txt"));
double doubletotal = 0;
int inttotal = 0;
String line = " ";
String word;
Scanner scanLine;
while (sc.hasNextLine()){
scanLine = new Scanner (sc.nextLine());
scanLine.next();
line += sc.hasNextLine();
inttotal += sc.nextInt();
// scanLine = new Scanner (sc.nextLine());
// scanLine.next();
// line += sc.next() + " ";
// inttotal += sc.nextInt();
doubletotal += sc.nextDouble();
}
System.out.println(inttotal);
System.out.println(doubletotal);
System.out.println(line);
}
}
This is rather ugly but it will work,
String[] weirdLookingString = new String[] { "12.9 ; I # 11 jav", "3.8 ; can # 11 aru"
,"4.0 ; read # 109 les" };
double doubleValue = 0.0;
String strValue1 = "";
String strValue2 = "";
int integerValue = 0;
for (int i = 0; i < weirdLookingString.length; i++) {
String array[] = weirdLookingString[i].split("[;\\#]\\s+");
String lastString[] = array[2].split("\\s");
integerValue += Integer.parseInt(lastString[0]);
doubleValue += Double.parseDouble(array[0]);
strValue2 += lastString[1];
strValue1 += array[1];
}
System.out.println("Integer value: " + integerValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Words: " + strValue2);
System.out.println("Line: " + strValue1);
output,
Integer value: 131
Double value: 20.7
Words: javarules
Line: I can read
You can create an arraylist of double, Integers and then create a sb builder for the first set of string and a stringBuilder for the second set of strings.
String line = "12.9 ; I # 13 jav";
String str[] = line.split("[;\\#\\s+]");
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
ArrayList<Double> doubleArray = new ArrayList();
ArrayList<Integer> intArray = new ArrayList();
for(int i =0; i < str.length; i++){
if(i == 0){
doubleArray.add(Double.parseDouble(str[i]));//convert to double and add it to the list
}else if(i == 1){
sb.append(str[i]);
}else if(i == 2){
doubleInt.add(Integer.parseInt(str[i]));//convert it to integer and add to the list
}else if(i == 3){
sb2.append(str[i]);
}
}
you can put everything in a loop so you won't have to rewrite everything. after everything has been added you can build a string using the stringBuilder and add everything using the array from arrayList