I want to input some integers with space delimiter from console, press Enter and then read them into List. (Initially, I don't know the number of the integers and I don't want to parse strings)
Is it possible?
Use a while loop.
public static void main(final String[] args) {
while(true) {
a = scanner.next();
if (a.equals(""))
break;
b = Integer.parseInt(a);
list.add(b);
or:
public static void main(final String[] args) {
while(true) {
try {
a = scanner.nextInt();
list.add(a);
} catch (Exception e) {
break;
}
You can initialize everything yourself. Just a basis to help you :)
Try this:
import java.util.Scanner;
public class help {
public static void main(final String[] args) {
Scanner scnr = new Scanner(System.in);
while (true) {
if (scnr.hasNextInt() == false)
break;
int a = scnr.nextInt();
System.out.println(a);
}
}}
You'll have to figure out a way to detect an empty line in scanner though. I can't think of a way right now.
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int a = 0;
a = scan.nextInt();
scan.close();
int count = String.valueOf(a).length();
for(int i = 0; i< count ; i++){
list.add(Integer.parseInt(String.valueOf(a).substring(i, i+1)));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
Related
so my teacher ordered me to make a program that
ask the user for the size of the array with a scanner
the program is required to understand if there is a scanner with the word "add" it will add the word after it to the array
The commands that are required to exist are ADD, DELETE, VIEW for display index-n and DISPLAY for display all of them
this is an example I've made but it's still far from correct, please help me!!!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String arr[] = new String[a];
for (int i = 0; i < a; i++) {
for (int j=0;j<arr.length;j++){
arr[i] = input.nextLine();
}
}
for( String b : arr ){
System.out.println(b);
}
enter code here
an example of the scanner input is
7
ADD this
ADD IS
ADD not
ADD real
VIEW 2
DELETE not
DISPLAY
and the output will be
not
this is real
There's no reason to ask how long the array should be because we are using ArrayList which is a dynamic array. You can make this code easier to read but here's just an example of what you are looking for:
public final static void main(final String[] args)
{
final List<String> list = new ArrayList<String>();
final Scanner scan = new Scanner(System.in);
while (true)
{
final String command = scan.nextLine().toLowerCase();
if (command.contains("add "))
{
list.add(command.replace("add ", ""));
} else if (command.contains("delete "))
{
final String toDelete = command.replace("delete ", "");
if (!list.remove(toDelete))
System.out.format("\"%s\" didn't exist in the array!", toDelete);
} else if (command.contains("view "))
{
System.out.println(list.get(Integer.parseInt(command.replace("view ", ""))));
} else if (command.equals("display"))
{
for (final String str : list)
{
System.out.println(str);
}
break;
} else
{
System.out.println("Unknown command!");
}
}
scan.close();
}
i have a problem with scanner! i don't know why i can't read the array.
import java.util.Scanner;
public class hotel {
public static void main(String[] args) {
String []name = new String[10]; //first array
double [][]money = new double[12][2];//second array
Scanner input = new Scanner(System.in);
for(int i=0; i<10; i++) {
name[i] = input.next(); //here is my problem
}
for(int k=0; k<12; k++) {
for(int j=0; j<12; j++) {
if ((j==1)||(j==2)||(j==10)) {
money[k][j]=-1;
}
else {
money[k][j]= input.nextDouble(); //and here
}
}
}
}
}
In your loop you're accessing money[12][2] which doesn't exists since you declared money as new double[12][2]. I suspect you might wanted to create money as double[] money = new double[12][12];
so I have being doing this program to verify if the word "bob" is in a string that the user enters. Example: "asddbobasd" -> "here is bob". Also, if there is one character between the bs it should print out "here is bob". Otherwise, it should print "here isn't bob".
tl dr: bxb = here is bob .bob = here is bob. bok = here isn't bob. When I'm executing the program, netbeans throws me an (!) at the if statement of (yed=='b' && zed=='b')
package lab;
import java.util.Scanner;
public class Lab {
public static void main(String[] args) {
char yed,zed;
Scanner sc = new Scanner (System.in);
String x;
System.out.println("Word");
x = sc.nextLine().toLowerCase();
int m=0;
for (int i = 0; i<=x.length(); i++) {
yed = x.charAt(i);
int j=i+2;
zed = x.charAt(j);
if (yed=='b' && zed=='b')
m++;
}
if (m>0){
System.out.println("here is bob");
}
if (m==0) {
System.out.println("here isn't bob");
}
}
}
Try to replace this:
for (int i = 0; i<=x.length(); i++) {
With using i<x.length()-2 instead of i<=x.length():
for (int i = 0; i<x.length()-2; i++) {
I'm trying to split a string and return each sub-string to an array in Java (easier in c#) but the compiler is not having it. I keep getting an index out of bounds error when I try to call the value of any string in the array indexed higher than 0. Here's the code I'm using:
public class hello {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int setter = 3000;
String num = in.next();
String[] numbers = num.split(" ");
int j = numbers.length;
for (int i =0; i < numbers.length ; i++) {
System.out.println(numbers[i]);
}
System.out.println(j);
Even the length of the array being returned is 1.
As David Wallace said in comments: you should use nextLine from Scanner...
But... why read line to split into int?
public static void main(final String[] args) {
final Scanner in = new Scanner(System.in);
String line = null;
List<List<Integer>> all = new ArrayList<>();
while ((line = in.nextLine()) != null) {
final String[] tokens = line.split(" ");
List<Integer> forOneLine = new ArrayList<>();
for (final String token : tokens) {
try {
final Integer value = Integer.valueOf(token);
forOneLine.add(value);
} catch (final NumberFormatException e) {
// Not an Integer
}
}
all.add(forOneLine);
}
Is it ok now?
Ended up parsing to an integer
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String n = in.nextLine();
int ne = Integer.parseInt(n);
String m = in.nextLine();
String[] numbers = m.split(" ");
System.out.println(n);
System.out.println(m);
for (String string : numbers) {
System.out.println(string);
}
}
This question already has an answer here:
Closed 10 years ago.
I run through the entire code. I am able to enter a simple .txt file to search for a word. After it asks for a word, it returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -48
at SearchEngine.main(SearchEngine.java:150)
Line 150 is for (int j = 0; j
Any help debugging?
This is basic search engine program that should be able to search a .txt file for any word.
Assignment link: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
System.out.println("Enter a word to be searched (type quit to exit program)");
Scanner keyboard = new Scanner(System.in);
String searchWord = keyboard.next();
while (!searchWord.equals("quit")) {
int counter = 0;
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
if(invertedIndex[wordPos][j] != 0) {
int number = invertedIndex[wordPos][j];
String printOut = concordanceArray[number];
System.out.print(number);
System.out.print(" :");
System.out.println(printOut);
}
}
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
From what I can see your getNumOfDistinctWords(String[] x) is wrong. This is returning a value of one less than it should be. Here is a modified version of the code:
import java.util.*;
import java.io.*;
public class SearchEngine {
//Counts the number of words in the file
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String[] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i < x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException {
HashSet<String> distinctWords = new HashSet<String>();
for(int i=0; i<x.length; i++){
distinctWords.add(x[i]);
}
String[] distinctWordsArray = new String[distinctWords.size()];
int i = 0;
for(String word : distinctWords){
distinctWordsArray[i] = word;
i++;
}
return distinctWordsArray;
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//Output the number of words in the file
System.out.println("Number of words is: " + NUM_WORDS);
String[] allWordsArray = new String[NUM_WORDS];
readInWords(input, allWordsArray);
Arrays.sort(allWordsArray);
String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray);
//Output the number of distinct words
System.out.println("Number of distinct words is: " + distinctWordsArray.length);
System.out.println("Finished creating distinctWordsArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String[] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[distinctWordsArray.length][10];
int [] wordCountArray = new int[distinctWordsArray.length];
int lineNum = 0;
while (lineNum < concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
//Find the position the word appears on the line, if word not found returns a number less than 0
int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next());
if(wordPos > -1){
wordCountArray[wordPos] += 1;
}
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
I should also point out the fact that Arrays.binarySearch(distinctWordsArray, scan.next()); will return a number less than 0 if the word is not found on that line. This is why you are getting the Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 as wordCountArray is being referenced at index -1 which of course doesn't exist!
The code after this also looks buggy but I'll let you fix that!!
Without knowing exactly where line 126 is, finding this specific bug is just too much hassle. But I've got some advice for the rest of the code:
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
Normally, variables in all-caps are constants that are assigned at compile time. It's a tradition that comes from C days, when it was wonderful to know which "variables" were actually replaced by the preprocessor. But the convention has proven to be useful in other languages, and most programmers would expect NUM_DISTINCT_WORDS to be assigned a specific value at compile time.
This code is simply unreadable:
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
A more idiomatic way to show these nested loops is:
for (int i = 0; i < invertedIndex.length; i++) {
for (int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
}
}
}
Because I use the standard Lindent script to do re-indenting, I get tabs. You don't have to use tabs, but they are convenient to add and delete with a single keystroke, and they are deep enough to be obviously visible even with smallish type faces. You'll find your code far easier to work with if you follow the standard indenting idioms.
The following piece of code is extremely unfortunate:
catch(FileNotFoundException exception) {
System.out.println("File Not Found");
}
It would be better to catch a higher-level exception and include the exception message. You can more easily handle dozens of errors if you catch an exception higher in the hierarchy, and the error messages will be far more informative.
Your main() method performs a lot of detailed work. I think your code would be easier to test, easier to debug, and easier to read, if you break it apart into more methods. Try to get the main() to read practically like a high-level description of your code.
With the line with the bug on it now easily visible, I can spot the problem:
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
You've looked up the wordPos in the vocabArray, but modified content in the wordCountArray. Are you sure they are the same size and have the same meanings?