Adding .split into my code - java

I'm creating a console program in Java with an array, I need to enter all of my code on one line in the following format up to 100 times.
car_make_name : car_model_name : car_model_tax : car_model_price
It's two strings and two int variables, I have code written out but I don't know how to use .split to enter the correct information into the corresponding variable.
This is my code:
public class Main {
public static void main (String[] args)
{
//Arrays declared
String[] cars = new String[20];
String[] car_model_name = new String[20];
int[] car_model_tax = new int[20];
String[] car_make_name = new String[20];
int[] car_model_price = new int[20];
Scanner scan = new Scanner (System.in);
//Loop??
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("quit", "QUIT", "Quit")) {
}
}
break;
for (int x = 0; x < cars.length; x++){
System.out.println("Enter details, separating each with a ':' ");
cars[x] = System.console().readLine();
}
}
}

First, you may prefer List but not array to store your information if you read input from console and you can't control the input length of your user.
Second, you may want to use String#split to split and convert it if necessary.
System.out.println("Enter details, separating each with a ':' ");
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("quit")) {
break;
}
final String[] split = line.split(":");
// handle it
}
Third, A good book can improve your programming level so much.If you have no experience of programming, I recommend Head First Java. Otherwise, I recommend Thinking In Java.

Related

Storing user input in a string array

I am a beginner to java. I try to write a program to read a series of words from the command-line arguments, and find the index of the first match of a given word. Like user can enter "I love apple", and the given word is "apple". The program will display "The index of the first match of ‘apple’ is 2".
What I did so far does not work. Is it my way of storing the input into the string array not correct?
import java.util.Scanner;
public class test {
public static void main(String [] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int num=1;
String sentence[]=new String[num];
for(int i=0; i< num; i++) {
sentence[i] = input; // store the user input into the array.
num = num+1;
}
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for(int j=0; j<num; j++) {
while (sentence[j].equals(key)) {
System.out.println("The index of the first match of "+key+" is "+j);
}
}
}
}
String array is not required in your solution.
Try this :-
System.out.println("enter sentence ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("enter the given word to fin the index ");
sc = new Scanner(System.in);
String toBeMatched = sc.nextLine();
if (input.contains(toBeMatched)) {
System.out.println("index is " + input.indexOf(toBeMatched));
} else {
System.out.println("doesn't contain string");
}
I have made the following changes to make your code work. Note you were storing the input string incorrectly. In your code, the entire code was being stored as the first index in the array. You don't need the first for-loop as we can use the function .split() to distinguish each word into a different index in the array. Rest of the code stays as it is.
public class ConfigTest {
public static void main(String[] args) {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// Use this to split the input into different indexes of the array
String[] sentence = input.split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].equals(key)) {
System.out.println("The index of the first match of " + key + " is " + i);
}
}
}
}
I think you have a scope problem. sentence[] is declared and instantiated in your first forloop. Try moving the declaration outside of the loop and you should do away with the error.
I also noticed a couple of errors. You could try this
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Enter Sentence");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String sentence[] = input.split("\\s");
System.out.println("Enter Word");
Scanner sc2 = new Scanner(System.in);
String key = sc2.next();
int index = 0;
for(String word : sentence)
{
if(word.equals(key))
{
System.out.println("The index of the first match of " + key + " is " + index);
break;
}
index++;
}
}
Turtle
sentence variable is only defined inside the for loop, it needs to be declared outside it
You can use the first Scanner (sc) declared variable again instead of declaring another one (sc2)
sentence[i] = input -- will mean -- sentence[0] = "I love apple"
Scanner variable can do all the work for you for the input into the array instead of a for loop
String[] a = sc. nextLine(). split(" ");
This will scan an input of new line and separate each string separated by a space into each array.
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String[] sentence = sc. nextLine(). split(" ");
System.out.println("Enter the given words to find the index of its first match: ");
String key = sc.nextLine();
for(int j=0; j<num; j++) {
if (sentence[j].matches(key)) {
System.out.println("The index of the first match of "+ key +" is "+ j);
}
}
Declare the String [] sentence outside the for loop. It is not visible outside the first for block.
The sentence array is created over and over again during the iteration of the for loop. The loop is not required to get the String from the command line.
Edited my answer and removed the use of any for loops, Arrays.asList() will take the words array and fetch the index of the word from the resulting List.
public static void main(String[] args) throws IOException {
System.out.println("Enter sentence: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("Enter the given word to find the index of its first match: ");
Scanner wordInput = new Scanner(System.in);
String key = wordInput.next();
String[] words = input.split(" ");
int occurence = Arrays.asList(words).indexOf(key);
if(occurence != -1){
System.out.println(String.format("Index of first occurence of the word is %d", occurence));
}
}
You just need to declare sentence array outside the for loop, as for now, the issue is of scope.For more on the scope of a variable in java . Also, this is not you intend to do, you intended to take input as a command line.
So, the input which you will get will come in String[] args. For more on command line arguments check here.

Why are all the numbers print out when I want only the largest?

I want to display only the largest number (price) from a text file. Every time it shows me the whole numbers instead of the highest value. I've been using a lot of methods like the for loop and others. But I think the problem is about something else.
package practice;
import java.util.Scanner;
import java.io.*;
public class Practice {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String fileName = "C:\\Users\\Work\\Desktop\\Prices.txt";
File inFile = new File(fileName);
Scanner inPut = new Scanner(inFile);
String line = inPut.nextLine();
while(inPut.hasNext()){
String[] Company = new String[3];
int[] Price = new int[3];
int[] Quality = new int[3];
int count = 0;
count++;
Company[count] = inPut.next();
Price[count] = inPut.nextInt();
Quality[count] = inPut.nextInt();
int HighestPrice = Price[0];
int counter = 1;
while(counter<Price.length-1){
if(Price[counter]>HighestPrice){
HighestPrice = Price[counter];
int hi = counter;
}
counter++;
}
System.out.println(HighestPrice);
}
}
}
Close the loop body after taking input in the arrays.
You should create your arrays outside the loop as their reference gets lost each time you recreate them.
String line = inPut.nextLine();
String[] Company = new String[3];
int[] Price = new int[3];
int[] Quality = new int[3];
int count = 0;
while(inPut.hasNext()){
Company[count] = inPut.next();
Price[count] = inPut.nextInt();
Quality[count] = inPut.nextInt();
count++;
}
You put the code to find the largest number inside the while(inPut.hasNext()){ Block. because of that the while(counter<Price.length-1){ loop gets executed on every line and therefore only has one value to handle, which of course is everytime the largest.
Skip the second loop and only execute the code inside, put the System.out.println(HighestPrice); outside the outer loop and it should work.

Search a text file for two strings and display how many strings are in between

How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.
String[] allWords = new String[400000];
int wordCount = 0;
Scanner input = new Scanner(new File("C:\\text.txt"));
while (input.hasNext()) {
String word = input.next();
allWords[wordCount] = word;
wordCount++;
System.out.println(wordCount);
}
Scanner sc = new Scanner(new File("C:\\text.txt"));
while(sc.hasNextLine()){
String in = sc.nextLine();
System.out.println("Enter a string:");
Scanner sc2 = new Scanner(System.in);
String str = sc2.nextLine();
System.out.println("Enter a string:");
Scanner sc3 = new Scanner(System.in);
String str2 = sc3.nextLine();
if (str.contains(str)) {
System.out.println("yes");
}
if (str.contains(str2)) {
System.out.println("yes");
}
Your math is correct. As you have surmised, subtract one from the difference of the positions. If you have any issues with the code, post your attempt to your question.
You could try something like this pseudocode.
int start
int end
a = startingString
b = startingString
String[] lines = StringFromFile.split("\n");
for(x in lines)
if(x=a)
start = position of x
for(x in lines)
if(x=b)
end = position of x
String[] newLines = Arrays.copyOfRange(lines, start,end)
return newLines.length

Create java list from user input

I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method

Java: Two Scanners reading from the same input file. Doable? Useful?

I have to read in integers from an input file based on whether or not a string that appears before them is a certain keyword "load". There is no key number telling how many numbers are about to be inputted. These numbers must be saved to an array. In order to avoid creating and updating a new array for each additional number scanned, I'd like to use a second scanner to first find the amount of integers, and then have the first scanner scan that many times before reverting back to testing for strings. My code:
public static void main(String[] args) throws FileNotFoundException{
File fileName = new File("heapops.txt");
Scanner scanner = new Scanner(fileName);
Scanner loadScan = new Scanner(fileName);
String nextInput;
int i = 0, j = 0;
while(scanner.hasNextLine())
{
nextInput = scanner.next();
System.out.println(nextInput);
if(nextInput.equals("load"))
{
loadScan = scanner;
nextInput = loadScan.next();
while(isInteger(nextInput)){
i++;
nextInput = loadScan.next();
}
int heap[] = new int[i];
for(j = 0; j < i; j++){
nextInput = scanner.next();
System.out.println(nextInput);
heap[j] = Integer.parseInt(nextInput);
System.out.print(" " + heap[j]);
}
}
}
scanner.close();
}
My problem seems to be that scanning via loadscan, the secondary scanner only meant for integers, also moves the primary scanner forward. Is there any way to stop this from happening? Any way to make the compiler treat scanner and loadscan as separate objects despite them preforming the same task?
You may certainly have two Scanner objects read from the same File object simultaneously. Advancing one will not advance the other.
Example
Assume that the contents of myFile are 123 abc. The snippet below
File file = new File("myFile");
Scanner strFin = new Scanner(file);
Scanner numFin = new Scanner(file);
System.out.println(numFin.nextInt());
System.out.println(strFin.next());
... prints the following output...
123
123
However, I don't know why you would want to do that. It would be much simpler to use a single Scanner for your purposes. I called mine fin in the following snippet.
String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
next = fin.next();
while (next.equals("load") {
next = fin.next();
while (isInteger(next)) {
readIntegers.Add(Integer.parseInt(next));
next = fin.next();
}
}
}

Categories

Resources