I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}
Related
I'm trying to build an Array with 5 strings in there; indexed 0 - 4. After this I need to shuffle the different pieces in the array rounds. The problem that I'm having is that is creating 5 different arrays I think? Could someone explain to me what I'm doing wrong and how to fix it?
To give an better understanding; this is the input of the fileScanner:
5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4
class Pirate {
public static final int MAX_ELEMENTS = 5;
String [] coordinateArray;
int position;
PrintStream out;
Pirate() {
out = new PrintStream(System.out);
}
void addInOrginalArray (String coordinateRowInput) {
coordinateArray = new String [MAX_ELEMENTS];
int position = 0;
coordinateArray[position] = coordinateRowInput;
for (int i = 0; i < coordinateArray.length; i++) {
position += 1;
System.out.println(i + "\t" + coordinateArray [i]);
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
fileScanner.useDelimiter("=");
while (fileScanner.hasNext()) {
String coordinateRowInput = fileScanner.next();
Scanner coordinateInputScanner = new Scanner(coordinateRowInput);
addInOrginalArray(coordinateRowInput);
}
}
public static void main(String[] argv) {
new Pirate().start();
}
}
I'm trying to create a lotto, where you have to read in a data file and match the numbers read in to winning numbers given through the console, my problem is that in the for loop where i read in the players numbers, it reads in fine, i even did a
system.out.print(ticketList.get(i).getNumbers()[j]+" ");
that checked if the numbers were correct, which they were, but when i did the same line of code outside the for loop where i add the instance of a ticket to the arraylist
ticketList.add(new Ticket(Players[i],ticketnumbers));`
It all gets over taken by the last instance ticket that was created, but the wierd part is, its only the player numbers that get over taken, not the player names, so thats what really threw me off, I've been sitting on it for a while trying to find stuff, but I've come up empty so far, any help would be appreciated!
I wanna say that the rest of the code works, because if i put the winning numbers as the last persons numbers he wins the lotto lol. I just know that when i try to match the number arrays it only uses the last persons numbers instead of everyone's individual numbers, so thats why that piece of code does not work.
public class Lottery{
static ArrayList<Ticket> ticketList = new ArrayList();
public static void scanFile() throws FileNotFoundException
{
String fileName;
int[] WinningNumbers = new int[6];
Scanner scan = new Scanner(System.in);
System.out.println("enter a string");
fileName = scan.nextLine();
System.out.println("Enter the winning Lottery Numbers");
for(int i =0; i<WinningNumbers.length;i++)
{
WinningNumbers[i] = scan.nextInt();
}
scan.close();
int NumberofTickets;
File file = new File(fileName);
Scanner scanInput = new Scanner(file);
NumberofTickets = scanInput.nextInt();
scanInput.nextLine();
String[] PlayersName = new String[NumberofTickets];
int[] ticketnumbers = new int[6];
for(int i=0; i < NumberofTickets;i++)
{
scanInput.nextLine();
PlayersName[i] = scanInput.nextLine();
scanInput.nextLine();
for(int j = 0 ; j<6;j++)
{
ticketnumbers[j] = scanInput.nextInt();
}
if(i != NumberofTickets-1)
scanInput.nextLine();
ticketList.add(new Ticket(PlayersName[i],ticketnumbers));
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
for(int i=0; i < NumberofTickets;i++)
{
for(int j = 0 ; j<6;j++)
{
System.out.print(ticketList.get(i).getNumbers()[j]+" ");
}
}
checkTickets(WinningNumbers,NumberofTickets);
scanInput.close();
}
public static void checkTickets(int[] winningNumbers, int NumberofTickets)
{
int[] winnersMatchedNumbers = new int[6];
for(int i =0; i<NumberofTickets; i++)
{
int counter = 0;
if(winningNumbers[j] == ticketList.get(i).getNumbers()[j])
{
counter = counter+1;
}
}
winnersMatchedNumbers[i] = counter;
}
Winners(winnersMatchedNumbers,NumberofTickets);
}
public static void Winners(int[] matchedNumbers, int NumberofTickets)
{
for(int i = 0; i<NumberofTickets;i++)
{
System.out.println(ticketList.get(i).getTicketName()+ " matched "+ matchedNumbers[i]+" and won "+ ticketList.get(i).getWinnings(matchedNumbers[i]));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
scanFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the other class i am using is here
public class Ticket
{
private String ticketName;
private int[] personNumber = new int[6];
public Ticket(String Name,int[] ticketNumbers)
{
ticketName = Name;
personNumber = ticketNumbers;
}
public String getTicketName()
{
return ticketName;
}
public int[] getNumbers()
{
return personNumber;
}
public int getWinnings(int count)
{
int winningsAmount;
switch(count)
{
case 3: winningsAmount = 10;
break;
case 4: winningsAmount = 100;
break;
case 5: winningsAmount = 10000;
break;
case 6: winningsAmount = 1000000;
break;
default: winningsAmount = 0;
break;
}
return winningsAmount;
}
}
Trying to write a java code for a single row Battleship style game, and when I tried to convert from an array to an ArrayList, the game started returning "miss" no matter what.
public class SimpleDotComGame {
public static void main(String[] args) {
int numofGuess = 0;
Scanner sc = new Scanner(System.in);
SimpleDotCom dot = new SimpleDotCom();
int ranNum = (int) (Math.random() * 5);
ArrayList<Integer> locations = new ArrayList<Integer>();
locations.add(ranNum);
locations.add(ranNum + 1);
locations.add(ranNum + 2);
dot.setLocationCells(locations); //think like you're running a
// separate program with parameters to set cells as "locations"
boolean isAlive = true;
while (isAlive == true) {
System.out.println("Enter a number");
String userGuess = sc.next();
String result = dot.checkYourself(userGuess); //run program to
// check if cells were hit by userGuess
numofGuess++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + numofGuess + " guesses");
}
}
sc.close();
}
}
public class SimpleDotCom {
int numofHits = 0;
ArrayList<Integer> locationCells;
public void setLocationCells(ArrayList<Integer> locations) { //locations
// variable described array so we must define it as array now
locationCells = locations;
}
public String checkYourself(String userGuess) { //check using parameter userGuess
int guess = Integer.parseInt(userGuess);
String result = "miss";
int index = locationCells.indexOf(userGuess);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
}
System.out.println(result);
return result;
}
}
Change :
int index = locationCells.indexOf(userGuess);
to
int index = locationCells.indexOf(guess);
userGuess is a String which can not possibly be in a list of Integers. guess is an int which can.
This question already has answers here:
How to read array of integers from the standard input in Java?
(2 answers)
Closed 8 years ago.
So my code looks like this so far:
public class PancakeSort {
public static int flip(int n) {
int temp = 0;
for (int i = 0; i < (n+1) / 2; ++i) {
int[] pancakes = new int[n];
temp = pancakes[i];
pancakes[i] = pancakes[n-i];
pancakes[n-i] = temp;
}
return temp;
}
public static void sort (int[] pancakes) {
for (int i=0; i<pancakes.length; i++){
if (pancakes[i] > pancakes[i+1]){
flip(i+1);
}
}
System.out.println(pancakes);
}
public static void main(String[] args) {
}
}
But how I input a whole array of integers using standard input (StdIn.readLine())? I understand that the code might not be correct and I'm working on figuring that out,and I'm also aware that this question has been asked before in this site, but not specifically using the standard library and that is where I'm stuck.
You can send integer array as input
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(new int[] { 100, 50, 89, 2, 5, 150 });
or Use scanner class as
int arr[] = new int[10];
Scanner sc = new Scanner(System.in);
int i = 0;
while (sc.hasNextInt()) {
arr[i] = sc.nextInt();
i = i + 1;
}
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(arr);
But in last case you must not increased the size of array.Otherwise it will give arrayIndexOutOfBoundException
I believe you may be referencing StdIn such as a class like this one?
http://introcs.cs.princeton.edu/java/stdlib/StdIn.java.html
If so, then to get an int from the console you just call StdIn.readInt. An example of how you could approach this is:
public static void main(String[] args)
{
System.out.println("Enter number of pancakes, or enter 0 to quit");
int[] pancakeArray = new int[0];
while (true)
{
try
{
int entry = StdIn.readInt();
if (entry == 0)
{
break;
}
int[] expandedArray = new int[pancakeArray.length + 1];
System.arraycopy(pancakeArray, 0, expandedArray, 0, pancakeArray.length);
expandedArray[pancakeArray.length] = entry;
pancakeArray = expandedArray;
}
catch (Exception e)
{
System.out.println("Invalid entry detected, closing input");
break;
}
}
System.out.println("Pancake array length: " + pancakeArray.length);
sort(pancakeArray);
System.out.println("Final pancake array in order:");
for (int entry : pancakeArray)
{
System.out.println("Pancake value: " + entry);
}
}
This would read int after int until they entered 0 or an invalid value, then it would call your sort routine from there. There are issues in your sort routine but you said you wanted to look at that, so I will let you figure that part out.
I'm working on a project for a class, and I think I've got it mostly figured out, but it keeps giving me different Exception errors and now I'm stumped.
The instructions can be found here: http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
Here is the code I have thus far, currently giving me and IndexOutOfBounds exception in the getMaximum method.
Any help would be much appreciated.
import java.io.*;
import java.util.*;
public class Project11a {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String fileName = keyboard.nextLine();
Scanner in = new Scanner(new File(fileName));
System.out.print("Enter an output file name: ");
String outFile = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(outFile);
while (in.hasNextLine()) {
String name = in.nextLine();
List<Integer> series = readNextSeries(in);
int mean = getAverage(series);
int median = getMedian(series);
int max = getMaximum(series);
int min = getMinimum(series);
outputFile.printf("%-22s%6d%n", name, mean, median, max, min);
}
in.close();
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a
// negative
// value is read from the Scanner. Store these integers in an
// ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(Scanner inScanner) {
List<Integer> nextSeries = new ArrayList<Integer>();
while (inScanner.hasNextInt()) {
int currentLine = inScanner.nextInt();
if (currentLine != -1) {
nextSeries.add(currentLine);
} else {
break;
}
}
return nextSeries;
}
// Given a List<Integer> of integers, compute the median of the list and
// return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
Collections.sort(inList);
int middle = inList.size() / 2;
int median = -1;
if (inList.size() % 2 == 1) {
median = inList.get(middle);
} else {
try {
median = (inList.get(middle - 1) + inList.get(middle)) / 2;
} catch (Exception e) {
}
}
return median;
}
// Given a List<Integer> of integers, compute the average of the list and
// return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int average = 0;
if (inList.size() == 0) {
return 0;
}
for (int i = 0; i < inList.size(); i++) {
average += inList.get(i);
}
return (average / inList.size());
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMaximum(List<Integer> inList) {
int max = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > max) {
max = inList.get(i);
}
}
return max;
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMinimum(List<Integer> inList) {
int min = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < min) {
min = inList.get(i);
}
}
return min;
}
}
Seemed like that your list is empty.
What can triggered the exception is the statement:
int max = inList.get(0);
So your inList do not have the value in the first index,which means the inList is empty.