I have to write a program that reads in a sequence of integers until 'stop' is entered, store the integers in an array and then display the average of the numbers entered. I'm getting an input mismatch exception when entering 'stop' so it doesn't really work, but I have no idea why. Help would be greatly appreciated.
import java.util.Scanner;
public class MeanUsingList {
public void mean() {
String s;
int n = 0;
int i = 1;
int[] array = { n };
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt();
s = in.nextLine();
} while (s != "stop");
{
System.out.println("Enter an integer");
Scanner in2 = new Scanner(System.in);
int x = in2.nextInt();
array[i] = x;
i++;
}
int av = 0;
for (int y = 0; y < array.length; y++) {
av += array[y];
}
System.out.println(av);
}
public static void main(String[] args) {
MeanUsingList obj = new MeanUsingList();
obj.mean();
}
}
First int[] array = { n }; just creates an array with 0 as the element in it.
the logic inside it will never execute while (s != "stop");
You want something like this
List list = new ArrayList();
//instead of array used arraylist because of dynamic size
do {
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt(); //get the input
list.add(n); // add to the list
Scanner ina = new Scanner(System.in); // need new scanner object
s = ina.nextLine(); //ask if want to stop
} while (!s.equals("stop")); // if input matches stop exit the loop
System.out.println(list); // print the list
I recommend you to learn the basics
Related
import java.util.Scanner;
class ArrayofArrays {
public static void main(String[] args) {
String[][] ListofNames = {
{"barbie","cinderella","troomtroom"},
{"wonderwoman","captainmarvel","Cheetah"}
};
for(String[] i : ListofNames) {
for(String x: i) {
System.out.println(x);
}
}
int r,c;
Scanner obj = new Scanner(System.in);
System.out.println("Enter rows\n");
r = obj.nextInt();
System.out.println("Enter columns\n");
c = obj.nextInt();
String[][] Inputnames = new String[r][c];
for(int j = 0;j<r;j++) {
for(int l = 0;l<c;l++) {
System.out.println("Enter name\n");
Inputnames[j][l] = obj.nextLine();
}
for(int m = 0;m<r;m++) {
for(int n = 0;n<c;n++) {
System.out.println(Inputnames[m][n]);
}
}
}
}
}
I was learning java and when I tried to to take in Array of Arrays consisting of strings as user input, it printed out null and didnt take further inputs. What am I missing out?
The output is like this on the cmd:
C:\Users\dynam\Desktop\Java Files>java ArrayofArrays
barbie
cinderella
troomtroom
wonderwoman
captainmarvel
Cheetah
Enter rows
2
Enter columns
1
Enter name
null
Enter name
batman
batman
Because the Scanner.nextInt method does not read the newline character in your input created after pressing "Enter," and so the call to Scanner.nextLine returns after reading that new line.
Also Looks like your for loops are messed up, try the following code (cleaned up a bit)-
package com.example.demo;
import java.util.Scanner;
class ArrayofArrays {
public static void main(String[] args) {
String[][] ListofNames = {
{"barbie", "cinderella", "troomtroom"},
{"wonderwoman", "captainmarvel", "Cheetah"}
};
for (String[] i : ListofNames) {
for (String x : i) {
System.out.println(x);
}
}
int r, c;
Scanner obj = new Scanner(System.in);
System.out.println("Enter rows\n");
r = obj.nextInt();
System.out.println("Enter columns\n");
c = obj.nextInt();
obj.nextLine();
String[][] Inputnames = new String[r][c];
for (int j = 0; j < r; j++) {
for (int l = 0; l < c; l++) {
System.out.println("Enter name\n");
Inputnames[j][l] = obj.nextLine();
}
}
for (int m = 0; m < r; m++) {
for (int n = 0; n < c; n++) {
System.out.println(Inputnames[m][n]);
}
}
}
}
Hope this helps!
I've seen this happen a lot in several questions. The issue is described here more in detail.
To fix your issue, replace the obj.nextInt() with Integer.parseInt(obj.nextLine()). So basically your code should look like the following:
System.out.println("Enter rows\n");
r = Integer.parseInt(obj.nextLine());
System.out.println("Enter columns\n");
c = Integer.parseInt(obj.nextLine());
If by any chance your will enter something else than an integer here, you might have to use a try-catch block to make sure you deal with NumberFormatExceptions.
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0" which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[i]);
++j;
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[i] + " ");
}
}
}
You need to work more about on for loops and study how to iterate values in for loop, the problem in your i,j variables.
Here I fix your code.
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final int NUM_VALS = 5; // number on int user able to enter
int[] userNum = new int[NUM_VALS]; // user integers storage
int j = 0;
int i = 0;
//for 5 inputs you need loop
for(;i<NUM_VALS;i++){
System.out.println("Enter integer values: ");
userNum[i] = scnr.nextInt(); // capture user input int
}
for (j = 0; j < NUM_VALS; j++) {
System.out.print("You entered: ");
System.out.println(userNum[j]);
//++j; //no need to increment as you already did in for loop
}
System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
for (j = NUM_VALS - 1; j >= 0; j--) {
System.out.print(userNum[j] + " ");// userNum[0] = your last value which you reverse
}
}
}
Here is a solution using the collections framework:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class ArrayReverse {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); // scanner for input
final List<Integer> numbers = new ArrayList<>();
System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
while (scnr.hasNextBigInteger()) {
final int n = scnr.nextInt();
System.out.println("Parsed: " + n);
numbers.add(n);
}
System.out.println("Done reading user input.");
System.out.println("Your input: " + numbers);
Collections.reverse(numbers);
System.out.println("Your input reversed: " + numbers);
}
}
I have provided you with a solution. This is a clean way of doing it.
nextInt() reads the next integer that the user inputs. Notice that this will throw a InputMismatchExceptionif the user does not input a integer as value.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> input = new ArrayList<Integer>();
//Simple loop that will read 5 user inputs
//and add them to the input list
for(int i = 0; i < 5; i++){
input.add(scanner.nextInt());
}
//print the 5 values
for(Integer val : input){
System.out.println(val);
}
//reverse the 5 values
Collections.reverse(input);
//print the 5 values again, but they are now reversed
for(Integer val : input){
System.out.println(val);
}
}
I am trying to replace an object in an array if the user inputs the letter E/e. For example the array can contain 2 objects the first object in the array the user entered a 3, the user now inputs a 5 e, they new array object [0] becomes the new user input 5. Here is my code so far:
import java.text.*;
import java.io.*;
public class Lab1a {
public static void main (String argv []) throws IOException {
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
NumberFormat nf = NumberFormat.getNumberInstance ();
nf.setMaximumFractionDigits (2);
nf.setMinimumFractionDigits (2);
String inputValue;
double [] doubleValues = new double [1];
char char1, char2, char3;
inputValue = stdin.readLine ();
String [] Values2 = inputValue.split ("\\s+");
for (int i = 0; i < Values2.length; ++i)
doubleValues [i] = Double.parseDouble (Values2[i]);
double old = doubleValues[0];
double newNum = doubleValues[1];
//Line 3: 3 characters separated by spaces
inputValue = stdin.readLine ();
String [] Values3 = inputValue.split ("\\s+");
for (int i = 0; i < Values3.length; ++i);
char1 = Values3[0].charAt(0);
char2 = Values3[1].charAt(0);
char3 = Values3[2].charAt(0);
if (inputValues == 'double' + "e") {
System.out.println(old);
}
}
so I whipped this up fairly quickly and it answers your posted question.
It initializes your array to a fixed SIZE=10 and asks user for input till 'q' is entered.
if user enters 'digit e/E' then the last entered value will be replaced.
Hope that helps!
cheers!
import java.util.Scanner;
public class Lab1a {
public static void main(String[] args) {
final int SIZE =10;//SIZE of array, you can change that if you want to
int availableIndex =0;//available element to change
double [] values = new double [SIZE];
Scanner kb = new Scanner (System.in);
while(availableIndex < values.length){
System.out.println("Please enter a value, if you wish to modify the last input value, then please enter your new value followed by an E/e");
System.out.println("enter q to exit");
String input = kb.nextLine().trim();
if (input.equalsIgnoreCase("q"))System.exit(0);
String [] arr = input.split("\\s+");
//for (String s : arr)System.out.println(s);
//validate input
if (arr.length == 1){//no change requested
values [availableIndex++] = Double.parseDouble(arr[0]);
}
else{
if (arr[1].equalsIgnoreCase("e")){
values[(availableIndex-1)] = Double.parseDouble(arr[0]);//availableIndex++;
}
else{//user inputed a char other than e/E
values[availableIndex++]= Double.parseDouble(arr[0]);
}
}
//print contents
for (int i=0; i < availableIndex; i++){
System.out.print(values[i]+"; ");
}
System.out.println();
}
}
}
When I tried to run this code noOfSub() methods executed properly;
but GC() method faces the following problem:
Enter the number of subjects:
2
Enter Your Subject 1 Grade:
s
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35)
Java Result: 1
Here is my code:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i=1;
Scanner gradeInput = new Scanner(System.in);
String[] grade = new String[noOfSubjects];
int[] credit = new int[noOfSubjects];
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC() {
while(i<=noOfSubjects)
{
System.out.println("Enter Your Subject "+i+" Grade:" );
grade[i] = gradeInput.nextLine();
System.out.println("Enter the Subject "+i+" Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
When you do:
public int noOfSubjects;
noOfSubjects is set to 0 which is its default value
So when you have the following code:
String[] grade = new String[noOfSubjects];
it essentially means,
String[] grade = new String[0]; //create a new String array with size 0
which creates an empty array for you.
So when you do,
grade[i] = gradeInput.nextLine(); //where i is 1
you get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at GPA.GC(GPA.java:21)
at GPA.main(GPA.java:35
because there is no index 1 in String[] grade.
Problem in your array initialization. You can initialize your array after take the input from user.
For example :
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
And change your while condition. Instead of this you use
while(i < noOfSubjects)
and set i = 0
If you want to get the size for the array from the user, create the array after getting it from stdin. Otherwise it will create a array with the size of 0 which is the default value for int in java.
Separate your declaration and initalization
String[] grade = null;
int[] credit = null;
...
noOfSubjects = scan.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
Why don't you use ArrayList because the size of array isn't know for you
public class GPA {
public int noOfSubjects;
public int i=0;
Scanner gradeInput = new Scanner(System.in);
List<String> grade = new ArrayList<>();
List<Integer> credit = new ArrayList<>();
public void noOfSub(){
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
}
public void GC(){
while(i<noOfSubjects)
{
System.out.println("Enter Your Subject "+(i+1)+" Grade:" );
grade.add(gradeInput.nextLine());
System.out.println("Enter the Subject "+(i+1)+" Credit:");
credit.add(gradeInput.nextInt());
gradeInput.nextLine();
i++;
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
Note : i added gradeInput.nextLine() after i++ because the Scanner.nextInt() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to Scanner.nextLine() so i fire a blank gradeInput.nextLine() call after gradeInput.nextInt() to consume rest of that line including newline
Since the noOfSubjects has run time value so the code should be:
import java.util.Scanner;
public class GPA {
public int noOfSubjects;
public int i = 0;
Scanner gradeInput = new Scanner(System.in);
String[] grade;
int[] credit;
public void noOfSub() {
System.out.println("Enter the number of subjects:");
Scanner sub = new Scanner(System.in);
noOfSubjects = sub.nextInt();
grade = new String[noOfSubjects];
credit = new int[noOfSubjects];
}
public void GC() {
while (i < noOfSubjects) {
System.out.println("Enter Your Subject " + (i + 1) + " Grade:");
grade[i] = gradeInput.next();
System.out.println("Enter the Subject " + (i + 1) + " Credit:");
credit[i] = gradeInput.nextInt();
i++;
}
for (int j = 0; j < grade.length; j++) {
System.out.println(grade[j] + " " + credit[j]);
}
}
public static void main(String[] args) {
GPA obj = new GPA();
obj.noOfSub();
obj.GC();
}
}
I can't figure out why is the array out of its borders, eclipes says the problem is at line 15
int d = array[1] - array[0];
import java.util.*;
public class Arrays1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int N = reader.nextInt();
int[] array = new int[N];
boolean right = true;
for (int i=0; i<array.length; i++)
{
System.out.println("Enter number for array");
array[i] = reader.nextInt();
}
int d = array[1] - array[0];
if ((array[N]-1)%d !=0)
{
right = false;
}
}
}
You probably want something like that:
public class Main {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int N = reader.nextInt();
int[] array = new int[N];
boolean right = true;
for (int i=0; i<array.length; i++)
{
System.out.println("Enter number for array");
array[i] = reader.nextInt();
}
int d = array[1] - array[0];
if ((array[N-1])%d !=0)
{
right = false;
}
}
}
Have a look at this part:
if ((array[N-1])%d !=0)
You were doing: if ((array[N]-1)%d !=0)
Btw, is aways a problem to trust the scan, you will need several validations.
Since you read the bounds of your array from the reader, it may be 0 or 1. To ensure it is big enough, you can try something like:
if(N > 1) {
int d = array[1] - array[0];
if ((array[N]-1)%d !=0)
{
right = false;
}
}
If it has to be bigger than 1 for you application to work, you could enforse this contraint right at the beginning:
int N = reader.nextInt();
if(N <= 1) {
System.out.println("N must be bigger than 1");
System.exit(1); // exit with error code
}
Try to validate the user input before you read your Array items, as the user may enter 1 for example when he is prompted for the array size thus there well be only one item in the array and accessing the item in second index (1 as it 0 based) will result in an ArrayOutOfBoundsException:
import java.util.*;
public class Arrays1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
int N = reader.nextInt();
while (N < 2) {
System.out.println("Enter a valid size for the array");
N = reader.nextInt();
}
int[] array = new int[N];
boolean right = true;
for (int i=0; i<array.length; i++)
{
System.out.println("Enter number for array");
array[i] = reader.nextInt();
}
int d = array[1] - array[0];
if ((array[N]-1)%d !=0)
{
right = false;
}
}
}
As a side note, pay attention to follow Java naming conventions as of the camelCase,so identifiers may begin with lowercase character not upper ones such as for int N which should be int n.