Array/ArrayList to make order with scanner input - java

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();
}

Related

How properly convert char to String and pass String in method?

I need to pass the String in the end of method in order to print String directly in main method, but when I did below, I receive just this one
[Ljava.lang.String;#135fbaa4
public static String businessLogic(String[] words) {
for (String word : words) {
char[] arrayWordInChar = word.toCharArray();
int wordLength = word.length();
for (int i = 0, j = wordLength - 1; i < j; ) {
if (!Character.isAlphabetic(arrayWordInChar[i]))
i++;
else if (!Character.isAlphabetic(arrayWordInChar[j]))
j--;
else
swapLetters(arrayWordInChar, i++, j--);
}
arrayWordInChar.toString();
}
return Arrays.toString(words);
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().split(" ");
businessLogic(words);
System.out.println(words);
}
}
I have been confused with this question for almost 2 days, what's the problem?
You get "[Ljava.lang.String;#135fbaa4" because words is String[], you can change the code as below.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] words = scanner.nextLine().split(" ");
//businessLogic(words);
System.out.println(businessLogic(words));
}
Arrays.toString(str)
String Constructor
String.valueOf() or String.copyValueOf()
First, add assignment to words array by words = businessLogic(words);
To print your arraylist elements, you can do one of the following :
System.out.println(Arrays.toString(words));
or
for(String word : words){
System.out.println(word);
}
businessLogic method returns a string but you are not assigning it to any String variable and in your System.out you are printing array words as a string.
System.out.println(businessLogic(words));
above line will print your desired output.

How can I make a java program that takes an input of words, finds certain words, replaces them and then prints out everything again?

I am not sure what to do, I have found all this online and I am trying to change it to do what I explained above but I am stuck. Basically what I want to do is copy and paste an essay into the code somewhere, the have it look through the essay for any words i tell it to look for, and if it finds them then to replace it with the word or words I want it to.
/**
*
import java.util.Arrays;
public class Main {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String words = "test words tesing";
String[] arr = wordList(words);
for(words i=0; i<words.length; i++)
for (String s: arr)
System.out.println(s);
}
}
*/
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
To read from the keyboard use
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (isr);
String cadena = br.readLine();
And all the words you introduced form the keyboard will be in "cadena".
To separte all the words you introduced you could use the method split from String.class.
String[] words = cadena.split(" ");
To find a specific word you could use a method and the code would be in your method would be:
String yourWord = "";
for(int i = 0; i < words.length; i++)
{
if(words[i].equals("your word"))
{
yourWord = words[i];
break;
}
}
To replece a word use the method replce(theWord, "the replacement")
You can prints all the words using a loop for with System.out.println(yourWord);

Java scanner array input until end of line

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));
}

Java - string split error

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);
}
}

Java: Count duplicate tokens on line using Scanner object

Yes this is an exercise from "Building Java Programs", but its not an assigned problem.
I need to write a method that reads the following text as input:
hello how how are you you you you
I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge
bow wow wow yippee yippee yo yippee yippee yay yay yay
one fish two fish red fish blue fish
It's the Muppet Show, wakka wakka wakka
And produces the following as output:
how*2 you*4
I*3 Jack's*2 smirking*4
wow*2 yippee*2 yippee*2 yay*3
wakka*3
Now I know I have to use Scanner objects to first read a line into a String, the to tokenize the string. What I don't get is how I read a token into a string, then immediately compare it to the next token.
CONSTRAINT -> This is from the chapter before arrays so I'd like to solve without using one.
Here is the code I have so far:
public class Exercises {
public static void main(String[] Args) throws FileNotFoundException {
Scanner inputFile = new Scanner(new File("misc/duplicateLines.txt"));
printDuplicates(inputFile);
}
public static void printDuplicates(Scanner input){
while(input.hasNextLine()){
//read each line of input into new String
String lineOfWords = input.nextLine();
//feed String into new scanner object to parse based on tokens
Scanner newInput = new Scanner(lineOfWords);
while(newInput.hasNext()){
//read next token into String
String firstWord = newInput.next();
//some code to compare one token to another
}
}
}
No need to use arrays...you just need a little bit of state in the while loop:
public class Exercises {
public static void main(String[] Args) throws FileNotFoundException {
// scanner splits on all whitespace characters by default, so it needs
// to be configured with a different regex in order to preserve newlines
Scanner inputFile = new Scanner(new File("misc/duplicateLines.txt"))
.useDelimiter("[ \\t]");
printDuplicates(inputFile);
}
public static void printDuplicates(Scanner input){
int lastWordCount = 0;
String lastWord = null;
while(newInput.hasNext()){
//read next token into String
String nextWord = newInput.next();
// reset counters on change and print out if count > 1
if(!nextWord.equals(lastWord)) {
if(lastWordCount > 1) {
System.out.println(lastWord + "*" + lastWordCount);
}
lastWordCount = 0;
}
lastWord = nextWord;
lastWordCount++;
}
// print out last word if it was repeated
if(lastWordCount > 1) {
System.out.println(lastWord + "*" + lastWordCount);
}
}
}
How about this? I'm allocating an extra string to keep track of the previous word.
while(input.hasNextLine()){
//read each line of input into new String
String lineOfWords = input.nextLine();
//feed String into new scanner object to parse based on tokens
Scanner newInput = new Scanner(lineOfWords);
String previousWord = "";
String currentWord = "";
while(newInput.hasNext()){
//read next token into String
previousWord = currentWord;
currentWord = newInput.next();
if (currentWord.equals(previousWord)) {
// duplicate detected!
}
}
}
public class test2 {
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(new File("chinese.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String currentLine;
String lastWord="";
String currentWord="";
int count=1;
while (input.hasNextLine()){
currentLine=input.nextLine();
Scanner newInput = new Scanner (currentLine);
//System.out.println(currentLine);
while(newInput.hasNext()){
currentWord=newInput.next();
if (!currentWord.equals(lastWord)&& count>1){
System.out.print(lastWord+"*"+count+" ");
count=1;
}
else if (currentWord.equals(lastWord)){
count++;
}
lastWord=currentWord;
}
if (count>1){
System.out.print(lastWord+"*"+count+" ");
}
System.out.println();
count=1;
}
input.close();
}
}

Categories

Resources