I'm trying print a given String char by char:
public static void main(String[] args) {
char c;
Scanner scaner = new Scanner(System.in);
int length = scaner.next().length();
System.out.println(length);
int i = 0;
while (i < length) {
c = scaner.next().charAt(i);
System.out.println(c);
i++;
}
}
Once this code has reached int length = scaner.next().length(); it doesn't continue. What's causing this?
You should store the scanned value in the temporary variable.
char c;
Scanner scaner = new Scanner(System.in);
// Storing scanned value
String nextStr = scaner.next();
int length = nextStr.length();
System.out.println(length);
int i = 0;
while(i < length){
c = nextStr.charAt(i);
System.out.println(c);
i++;
}
In your original code you call next repeatedly in a loop, but this does not return the original scanned value, but the next line of input.
You need to enter something after calling next().
As addition too Alexander's answer.
The line: int length = scaner.next().length(); gets the next line and then checks the length.
So you already got the next line and calling next() again asks for different input.
That's the reason why you should always store the return value of next() in a variable!
Related
I need to see when a given variable value in an array is first occurred and once occurred change that variable to the number when it first occurs, and if it does not occur than change the value to -1.
For example 32 appears first in the array so it should print 1 but 100 never appears in the array so it should print -1 but how do I make a second if statement in my loop so that the variable will be -1 but it test the original value to find it appears. Sorry if I did not explain it well enough.
here is the code for the loop and the first if statement
public static int occurrence(int[] a) {
Scanner scnr = new Scanner(System.in);
int occurrence = scnr.nextInt();
for (int i = 0; i < a.length; i++)
if (a[i] == occurrence)
occurrence = i + 1;
return occurrence;
The JDK library comes with an Arrays class just for things like this.
First, import the class:
import java.util.Arrays;
Now all you have to do is this:
System.out.println(Arrays.binarySearch(a, occurrence));
And that's basically it. The "binarySearch()" method takes two parameters, those being the name of the array you're referencing (a), and the value you are searching for in that array (occurrence). It then returns the index of the value. If the value is not found in the array, it returns -1.
Take a look at this. Try to separate your input code (scanner) from the function logic. That will make the occurrence method reusable.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int data[] = { 2,5,7};
Scanner scnr = new Scanner(System.in);
int inputValue = scnr.nextInt();
int index = occurrence( data, inputValue);
System.out.println("value at index: " + index);
}
//
// find first match, then exit the loop if found.
//
public static int occurrence(int[] a, int inputValue) {
int result = -1;
for (int i = 0; i < a.length; i++)
if (a[i] == inputValue) {
result = i;
break;
}
return result;
}
}
I've got a problem, because there's somewhere a problem in my code I can't resolve.
I have to make a method that searches indexes of largest digit from table made of txt file. Here's my code
public static void findIndexOfLargestDigit() throws IOException {
File file = makeNewFile();
scanner = new Scanner(file);
int digit;
int largestDigit = 0;
int n = scanner.nextInt();
for(int i=0; i<n; i++) {
digit = scanner.nextInt();
if(digit>largestDigit) {
largestDigit = digit;
}
}
String tableToString = table.toString();
int result = tableToString.indexOf(largestDigit);
Integer resultInteger = new Integer(result);
String resultToString = resultInteger.toString();
System.out.println(resultToString);
}
It gives -1 result, but I can't explain why. Any ideas? thanks.
tableToString.indexOf(largestDigit) fails because that is a call to String.indexOf(int ch), but the parameter the not a char value but an int number.
Maybe you meant tableToString.indexOf(Integer.toString(largestDigit)), or if you prefer, you can write the same as tableToString.indexOf(String.valueOf(largestDigit)).
Other comments:
You must close the Scanner after use. Best way is using try-with-resources.
You should declare digit where used, to limit the scope to inside the loop.
The last 3 lines is a very long way to say System.out.println(result).
I tried to count the occurrence of alphabets in a string, but I substitue them with numbers to make it clearer. Then when I run that code, it doesnt display the results I want.I dont really know why...Please help!! Thank you so much!!
Scanner Scanner1 = new Scanner(System.in);
out.println("Please type in a string below.");
String UserInput = Scanner1.nextLine();
String Index = "12345";
int length = 2;//Modified
int[] count = new int[length];
int length2 = 5; //Modified
int n1 = 0;
int n2 = 0;
out.println(UserInput.charAt(n1));//Modified
out.println(Index.charAt(n2));//Modified
for (int i = 0; i < length; i++) {
if (UserInput.charAt(n1) == Index.charAt(n2)) {
n1++;
count[length - (length - n1)]++;
} else {
n2++;
if(n2==length2)
{
n2 = n2-length2;
}
}
}
A relatively short and neat way to count a specific character in a string is using the return value of the replaceAll method:
public static int countChar(final String str, final char c) {
return str.replaceAll("[^" + c + "]","").length();
}
The pattern [^x] (x can be replaced with any char (or amount of different chars)) will match everything in a given String except x. So [^T] of TEST would replace E and S with the given replacement (which is "" (nothing)) and keeps the Ts. The method would return TT. If you count that length, you'll receive the count of the searched character of the given string.
The example
System.out.println(countChar("TEST", 'T'));
System.out.println(countChar("TEST", 'E'));
System.out.println(countChar("TEST", 'S'));
prints
2
1
1
(keep in mind that is method is case sensitive)
use collections like Hashmap. Here Character stores every unique character encountered and Integer stores the count of every character whenever it is encountered.
I am getting this error when I enter the String "s" after entring an integer.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at oneB.change(oneB.java:4)
at oneB.main(oneB.java:26)
Following is the code: (Please note that the code is still complete and I have entered some print statements for checking)
import java.util.Scanner;
public class oneB {
public static String change(int n, String s, String t) {
if (s.charAt(0) == 'R') {
return onetwo(s);
}
return s;
}
private static String onetwo(String one) {
int c = one.indexOf('C');
System.out.print(c);
char[] columnarray = new char[one.length() - c - 1];
for (int i = c + 1; i < one.length(); i++) {
columnarray[i] = one.charAt(i);
}
int columnno = Integer.parseInt(new String(columnarray));
System.out.print(columnno);
return one;
}
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int n = in .nextInt();
String s = in .nextLine();
String t = in .nextLine();
System.out.print(change(n, s, t));
}
}
The call in.nextInt() leaves the endline character in the stream, so the following call to in.nextLine() results in an empty string. Then you pass an empty string to a function that references its first character and thus you get the exception.
Here's how I debugged it:
You are getting a StringIndexOutOfBoundsException with index zero at line 4.
That means that the String you are operating on when you call s.charAt(0) is the empty String.
That means that s = in.nextLine() is setting s to an empty String.
How can that be? Well, what is happening is that the previous nextInt() call read an integer, but it left the characters after the integer unconsumed. So your nextLine() is reading the remainder of the line (up to the end-of-line), removing the newline, and giving you the rest ... which is an empty String.
Add an extra in.readLine() call before you attempt to read the line into s.
One another solution to the problem would be instead of nextLine(), use just next().
int n = in .nextInt();
String s = in .next();
It looks like s is an empty String "".
for (int i = c + 1; i < one.length(); i++) {
columnarray[i] = one.charAt(i); // problem is here.
}
You need to start array index from 0. But you are starting from c + 1
for (int i = c + 1,j=0; i < one.length(); i++,j++) {
columnarray[j] = one.charAt(i);
}
The problem is that when you hit enter, your int is followed by a '\n' character. Just modify the code like this :
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
int n = in .nextInt();
in.nextLine(); //This line consume the /n afer nextInt
String s = in .nextLine();
String t = in .nextLine();
System.out.print(change(n, s, t));
}
I got an Java ArrayIndexOutOfBoundsException when getting String input in Java. Please help me. This is my code: I edited my code to split using : it says
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at solution2.Solution.main(Solution.java:27)
public class Solution {
static String search;
public static void main(String[] args){
String[] fn,ln,tp;
boolean[] isSet;
Scanner sc=new Scanner(System.in);
int no=sc.nextInt();
String[][] temp=new String[no][3];
fn=new String[no];
ln=new String[no];
tp=new String[no];
isSet=new boolean[no];
boolean flag=false;
for(int i=0;i<no;i++){
temp[i]=sc.nextLine().split(":");
fn[i]=temp[i][0];
ln[i]=temp[i][1];
tp[i]=temp[i][2];
isSet[i]=true;
}
System.out.println(temp.length);
search=sc.nextLine();
The exception is occurring on this line:
ln[i] = temp[i][1];
so it appears
temp[i] = sc.nextLine().split(":");
is not receiving enough tokens in the :-delimited string to have create String array of size 3.
You will need to ensure temp[i].length == 3 to ensure that you can assign these tokens.
An example of valid input (note: no newline) is:
1 test:foo:bar
The ArrayIndexOutOfBoundsException occurs when you are accessing non-existent indexes on the array created from split(":").
In this piece of code, temp[i] is not ensured to have values at index 0, 1, or 2, because if the nextLine() is something such as "dog", there are no colon characters to split around.
temp[i]=sc.nextLine().split(":");
fn[i]=temp[i][0];
ln[i]=temp[i][1];
tp[i]=temp[i][2];
To fix the issue, you should verify that the array indeed has the index before trying to access it.
temp[i]=sc.nextLine().split(":");
if (temp[i].length >= 3) {
fn[i]=temp[i][0];
ln[i]=temp[i][1];
tp[i]=temp[i][2];
}
I insert sc.nextLine(). below int no = sc.nextInt(); line.
import java.util.Scanner;
public class Solution {
static String search;
public static void main(String[] args) {
String[] fn, ln, tp;
boolean[] isSet;
Scanner sc = new Scanner(System.in);
int no = sc.nextInt();
sc.nextLine(); // **********
String[][] temp = new String[no][3];
fn = new String[no];
ln = new String[no];
tp = new String[no];
isSet = new boolean[no];
boolean flag = false;
for (int i = 0; i < no; i++) {
temp[i] = sc.nextLine().split(":");
fn[i] = temp[i][0];
ln[i] = temp[i][1];
tp[i] = temp[i][2];
isSet[i] = true;
}
System.out.println(temp.length);
search = sc.nextLine();
}
}
You problem is, that sc.nextLine() return new line String (e.g. "\n") after you press [Enter]. Second time it's wait for you input. SeeJava String Scanner input does not wait for info, moves directly to next statement. How to wait for info?
In your case try to invoke sc.nextLine() before you processing:
sc.nextLine()
temp[i]=sc.nextLine().split(":");
EDIT: you are right, you must insert it after nextInt(), because nextLine() consume complete line.