I'm making a program for my assignment. This is not the whole program but it's just a part of it.
I want from the user to enter some integer values to be stored in "items" arrays. When the user input "stop" the loop should close and here is the problem.. when I write stop the program stops and give me some errors.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true){
i=i+1;
if ("stop".equals(scan.nextLine()))
break;
else
items[i] = scan.nextInt();
}
}
There are certain mistakes in your code. It's more better if you could just add the error.
Try this code.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0, lines = 1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true){
String InputTxt = scan.nextLine();
if (InputTxt.equals("stop"))
break;
else{
try{
items[i] = Integer.parseInt(InputTxt);
i++;
}catch(Exception e){
System.out.println("Please enter a number");
}
}
}
}
On top of other answers, I would like to advise you to change the looping from
while(true)
to
//first you need to remove the local variable i
for(int i = 0; i < items.length; ++i)
Using this approach will help you to avoid IndexOutOfBoundsException when users key in more than 100 integer values.
your problem is this line : items[i] = scan.nextInt(); because you are trying to get integer while the input is string stop
EDIT
one possible solution is that you get your data as string and check if it is stop or not and if not then try to parse it to integer like code bellow:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i=0, lines=1;
int[] items = new int[100];
int total = 0;
System.out.println("Enter the items with its price");
while(true)
{
i=i+1;
String str = scan.nextLine()
if ("stop".equals(str))
break;
else
{
items[i] = Integer.parseInt(str)
}
}
}
Related
I am trying to add the 1st and last digit of a no but after the programs gets to while loop it starts asking for more inputs,like an infinite loop .
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();//no of testcases
int n[]=new int[t];
int last=0,first = 0;
for(int i=0;i<t;i++){
n[i]=sc.nextInt();
sc.nextLine();
last=n[i]%10;
while(n[i]>=10){
first=n[i]/10;
}
System.out.println(first+last);
}
This is how I did it.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
String temp = t+"";
String[] arr = temp.split("");
int x = Integer.parseInt(arr[0]) + Integer.parseInt(arr[arr.length - 1]);
System.out.println(x);
}
That is because you are not updating the value of n[i] with every iteration.
This is my proposed solution for your while loop:
while(n[i]>=10){
n[i]=n[i]/10;
}
first = n[i]
In while loop you need to update the value of n[i] by using n[i]=n[i]/10; which is causing while loop to become infinite loop
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();//no of testcases
int n[]=new int[t];
int last=0,first = 0;
for(int i=0;i<t;i++){
n[i]=sc.nextInt();
sc.nextLine();
last=n[i]%10;
while(n[i]>=10){
n[i]=n[i]/10;
}
first=n[i]/10;
System.out.println(first+last);
}
My school homework is to declare array with 100 variables.
The actual task is: Declare array with 100 variables. Use do.. while loop to read the data to array. Reading data should be finished when array will be full or when user will enter a negative number.
So far I got:
public static void runTask1() {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
for (int i = 0; i < tab.length; i++);
System.out.println("Enter number for array ");
tab [] = read.nextInt();
Please help. I'm a total newbie in programming.
You should do your homework yourself ;)
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int idx=0;
do{
System.out.println("Number for array idx "+idx);
try{
tab[idx] = read.nextInt();
}catch(Exception e){
System.out.println("Wrong input");
}
if(tab[idx]<0) break;
idx++;
}while(idx<100)
Not compiled, just wrote it here.
Try that
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int[] tab = new int [100];
int index = 0;
while(index < tab.length){
System.out.println("Enter number for array ");
tab[index]= read.nextInt();
if(tab[index]<1) break;
index++;
}
System.out.println(Arrays.toString(tab));
}
I was wondering how to load up an array (with user input) using a while loop. The code below prints a 0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int n = 0;
int[] myArray = new int[10];
System.out.printf("enter a value>>");
while (scan.nextInt() > 0) {
for (i = 0; i > 0; i++) {
myArray[i] = scan.nextInt();
}
System.out.printf("enter a value>>");
}
System.out.printf("array index 2 is %d", myArray[2]);
}
There are multiple things wrong with your code:
First of all
while(scan.nextInt() > 0){
Scanner.nextInt() returns an int from your standard input so you actually have to pick up that value. You are checking here what the user typed but then not using it at all and storing the next thing that the user types by saying:
myArray[i] = scan.nextInt();
You don't really need the outer while loop, just use the for loop, its enough.
However, your for loop is off as well:
for(i = 0; i > 0; i++){
It starts at i equal to 0 and runs while i is greater than 0. This means it will never actually run the code within the loop because 0 is never greater than 0. And if it did run (you started it at some number < 0), you would end up in an infinite loop because your condition i > 0 is always true for positive numbers.
Change the loop to:
for(i = 0; i < 10; i++){
Now, your loop could look like:
for(i = 0; i < 10; i++){ // do this 10 times
System.out.printf("enter a value>>"); // print a statement to the screen
myArray[i] = scan.nextInt(); // read an integer from the user and store it into the array
}
one other way to do it
Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
System.out.println("Enter a value to store in list");
list.add(scan.nextInt());
System.out.println("Enter more value y to continue or enter n to exit");
Scanner s = new Scanner(System.in);
String ans = s.nextLine();
if(ans.equals("n"))
break;
}
System.out.println(list);
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int[] arr=new int[4];
int i;
for(i=0;i<4;i++)
{
System.out.println("Enter the number: ");
arr[i]=input.nextInt();
}
for(i=0;i<4;i++)
{
System.out.println(arr[i]);
}
}
Hope this code helps.
Hi all Java professionals,
I need one piece of guidance which is shifting all the value in an array down by one position and drop the last value in an array so that the new input is added into the beginning of the array in Java. The program keeps looping and the element keep shifting to the right.The following is my code, please help.
import java.util.Scanner;
public class ass3a
{
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
double calculate [] = new double [10];
double read;
String choice;
while (true)
{
System.out.println("\n the first index is "+calculate[0]);
System.out.println("1)Add \n2)Drop \n3)Stop:");
choice=reader.nextLine();
char choose =choice.charAt(0);
switch (choose)
{
case '1':
Add( calculate);
break;
default: System.out.println("No such an option.");
}
}
}
public static double Add (double calculate[])
{
Scanner reader = new Scanner(System.in);
double replace=0;
for(int i = 0; i < 10; i++)
{
if(calculate[i] == 0)
{
System.out.println("-----Adding-----");
System.out.print("Please enter a number to add into the array:");
calculate[i]=reader.nextDouble();
System.out.println(calculate[i]);
replace = calculate[i];
break;
}
}
return replace;
}
}
I have tried few lines of code for you, it drops the last element in your array...
public static double drop (double calculate[])
{
double replace=0;
System.out.println("-----dropping-----");
System.out.print("Please enter a number to add into the array:");
Scanner reader = new Scanner(System.in);
replace=reader.nextDouble();
double temp;
//calculate.length calculates the length of an array
int len=calculate.length-1;
//removing the last element of an array and shifting down the entire array
for(int i = 0; i <len; i++)
{
calculate[len-i]=calculate[len-(i+1)];
}
calculate[0]=replace;
System.out.println("Array now contains...");
for(int j=0;j<calculate.length;j++)
System.out.println(calculate[j]);
return replace;
}
The demerit of using this method will be-- here the last element of the array is getting deleted on the last entered value. I have over come that by modifying your add method, Wherein the first element in stored in the last part of the array and now the code looks like this..
import java.util.Scanner;
public class pg1
{
//Declared for easy access of arrays..
static int temp1;
public static void main(String []args)
{
Scanner reader = new Scanner(System.in);
double calculate [] = new double [10];
//Finding the length.. Have used a variable to increase the flexibility of the code.
//incase, if you want to change the array length at any point
temp1=calculate.length-1;
double read;
String choice;
while (true)
{
System.out.println("\n the first index is "+calculate[0]);
System.out.println("1)Add \n2)Drop \n3)Stop:");
choice=reader.nextLine();
char choose =choice.charAt(0);
switch (choose)
{
case '1':
Add( calculate);
break;
case '2':
drop(calculate);
break;
default: System.out.println("No such an option.");
}
}
}
//This place is where major modifications have taken place
public static double Add (double calculate[])
{
Scanner reader = new Scanner(System.in);
double replace=0;
//Only enters when the first element of the code is zero... Zero is the default value..
if(calculate[0] == 0)
{
//Storing the elements into array and displaying it..
System.out.println("-----Adding-----");
System.out.print("Please enter a number to add into the array:");
calculate[temp1--]=reader.nextDouble();
System.out.println("Array now contains...");
for(int j=0;j<calculate.length;j++)
System.out.println(calculate[j]);
}
return replace;
}
public static double drop (double calculate[])
{
double replace=0;
System.out.println("-----dropping-----");
System.out.print("Please enter a number to add into the array:");
Scanner reader = new Scanner(System.in);
replace=reader.nextDouble();
double temp;
int len=calculate.length-1;
for(int i = 0; i <len; i++)
{
calculate[len-i]=calculate[len-(i+1)];
}
calculate[0]=replace;
System.out.println("Array now contains...");
for(int j=0;j<calculate.length;j++)
System.out.println(calculate[j]);
return replace;
}
}
Happy Coding..
how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();