I am working on a project for a class and I keep running into a problem. I am trying to terminate a program when the user types stop. If I remove text = input.nextLine(); the code works correctly however it does not stop when the user request. I also tried making a new scanner object, but that did not fix the problem. Any help with this problem would be appreciated.
Thank you.
class blah
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String text = ("");
while(!text.equals("stop"))
{
System.out.print("Insert the number of items, holder value and passing value:");
text = input.nextLine();
int items = input.nextInt();
int holder = input.nextInt();
int passing = input.nextInt();
killBot5000 josephus = new killBot5000(items,holder,passing);
josephus.execute();
}
}
}
The problem is that the input can be either a String stop or three integers
You could change your code to just accept a line of input, decide if it is stop and if not then split the line into three tokens which can be converted to ints.
while(!text.equals("stop"))
{
System.out.print("Insert the number of items, holder value and passing value:");
text = input.nextLine();
if (text.equalsIgnoreCase ("stop")) break;
String arr [] = text.split (" ");
int items = Integer.valueOf (arr[0]);
int holder = Integer.valueOf (arr[1]);
int passing = Integer.valueOf (arr[2]);
killBot5000 josephus = new killBot5000(items,holder,passing);
josephus.execute();
}
Related
I am trying to have the user set the name for how many numbers they set. for example if they set 3 the program asks for name 3 times and then sets those names to a different varible inside an array.
public static void main(String[] args) {
Scanner Num = new Scanner(System.in);
Scanner Name = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = Num.nextInt();
int[] numbs = new int[number];
for (int i = 0; i < numbs.length; i++) {
System.out.println("What is your name");
String [] nameArray = Name.nextLine();
Just a small improvement over Titan's answer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int numberOfTimes = sc.nextInt();
String[] names = new String[numberOfTimes];
sc.nextLine();
for (int i = 0; i < numberOfTimes; i++) {
System.out.println("What is your name");
names[i] = sc.nextLine();
}
System.out.println(Arrays.toString(names));
}
Starting point
Here are several things happening in your posted code:
You have two different Scanners, each reading from System.in
After prompting for user input (int number = Num.nextInt()), you're using that number to create an array of size "number"
When you call nextLine(), you are assigning the result to a string array (String []).
Working solution
Here's a variation which addresses those issues, with a few additions, too:
Use one Scanner, and give it a general name ("scanner", not "Num") since a scanner has nothing to do with one specific data type. Any scanner can read strings, integers, booleans, bytes, etc. Look in Javadoc for the full set of supported data types.
Check if user input is valid before trying to create an array – if user enters "-1" that's a valid integer value, but not valid for allocating an array – new int[-1]) would throw a java.lang.NegativeArraySizeException at runtime.
Use "next()" instead of "nextLine()" – with the rest of your example, using "nextLine()" results in skipping one line without direct interaction from the user (so the first "name" is always an empty string)
Assign the result of "next()" to a String (not String[]), matching the return type from the method
Use "System.out.print()" instead of "println()", a little tidier program output
Use lowercase names to follow Java naming conventions ("scanner", not "Scanner")
Scanner scanner = new Scanner(System.in);
System.out.print("How many names do you want to enter: ");
int times = scanner.nextInt();
if (times < 0) {
System.out.println("negative numbers not allowed");
} else {
String[] names = new String[times];
for (int i = 0; i < times; i++) {
System.out.print("What is your name: ");
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
}
And here's a sample run:
How many names do you want to enter: 3
What is your name: one
What is your name: two
What is your name: three
[one, two, three]
Create a String array of number length outside the loop and initialize each index with name as input.
By the way you only need to create one Scanner object for input(Not needed to create various objects for different input).
Edit - There was no use of numbs array.
Scanner sc=new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = sc.nextInt();
String []nameArray=new String[number];
/*Since nextInt() does not read the newline character in your input
created by hitting "Enter"*/.
sc.nextLine();
for (int i = 0; i < number; i++) {
System.out.println("What is your name");
nameArray[i]=sc.nextLine();
}
sc.close(); //To prevent memory leak
I am suppose to ask the user for how many integers they want to enter, and then use a loop to create a prompt message for each integer, so that the numbers can be entered. Each integer that is entered is stored in an array.
However, every time I run the code, an error appears. The code doesn't repeat during the loop, and it looks like this:
Please enter the number of values you would like to enter:
1
Please enter for index value of 0:
-Error-
I can't figure out why the loop and array aren't working, thank you!
```public static void main(String[] args) {
//create and label variables
int intCount, n, x;
//create a scanner that will accept the user's input and figure out how many
numbers the user wants to enter
Scanner Inputnumber = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to
enter:");
n = Inputnumber.nextInt();
Inputnumber.close();
//create a integer array to store the numbers
int [] integers;
integers = new int [n];
//create a while loop to continuously ask the user for what numbers they
want to enter
for (intCount = 0; intCount < n; intCount++){
Scanner InputInt = new Scanner(System.in);
System.out.println("Please enter for index value of "+intCount+": ");
x = InputInt.nextInt();
integers [intCount] = x;
InputInt.close();
}```
Refer this
You don't need to use two separate Scanner Objects.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) throws IOException {
// create and label variables
int intCount, n, x;
// create a scanner that will accept the user's input and figure out how many
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of values you would like to enter:");
n = input.nextInt();
// create a integer array to store the numbers
int[] integers;
integers = new int[n];
// create a while loop to continuously ask the user for what numbers they
for (intCount = 0; intCount < n; intCount++) {
System.out.println("Please enter for index value of " + intCount + ": ");
x = input.nextInt();
integers[intCount] = x;
}
input.close();
}
}
I just started learning Java and I need help on how to modify the program so that the array size is taken as a user input while using a while loop to validate the input so that invalid integers are rejected.
Also, using a while loop, take keyboard inputs and assign values to each array position.
I would appreciate any help!
Here is the code:
double salaries[]=new double[3];
salaries[0] = 80000.0;
salaries[1] = 100000.0;
salaries[2] = 70000.0;
int i = 0;
while (i < 3) {
System.out.println("Salary at element " + i + " is $" + salaries[i]);
i = i + 1;
}
It is very simple to use the while loop and take input from user Please refer below code you will understand how to take input from user and how while loop works. put all code in your main() function and import the import java.util.Scanner; and execute it and do modification to understand code.
Scanner sc= new Scanner (System.in); // this will help to initialize the key board input
System.out.println("Enter the array element");
int N;
N= sc.nextInt(); // take the keyboard input from user
System.out.println("Enter the "+ N + " array element ");
int i =0;
double salaries[]=new double[N]; // take the array lenght as the user wanted to enter
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salaries[i]=sc.nextDouble();
i++; // increment value of i so that it will store in next array element
}
you can use Scanner class for taking input from user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=sc.nextInt();
double salaries[]=new double[n];
for(int i=0;i<n;i++)
{
salaries[i]=sc.nextDouble();
}
You can also achieve using for loop and use Scanner class which is used to take input from keybord.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please enter the length of array you want");
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
double salaries[]=new double[length];
System.out.println("Please enter "+ length+" values");
for(int i=0;i<length; i++){
scanner = new Scanner(System.in);
salaries[i] = scanner.nextDouble();
}
scanner.close();
}
}
On java if you specific he array size, you can not change it,so you need to know array size before adding any value, but you can you use on of the List implementation like ArrayList to be able to add values without caring about the array size.
Example :
List<Double> salarie = new ArrayList<Double>();
while (i<N) { // this will get exit as soon as i is greater than number of elements from user
salarie.add(sc.nextDouble());
i++; // increment value of i so that it will store in next array
}
please read these articles for more details : difference-between-array-vs-arraylist
distinction-between-the-capacity-of-an-array-list-and-the-size-of-an-array
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.
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